Esempio n. 1
0
    def process_comment_jobs(self,
                             event: PullRequestCommentEvent) -> HandlerResults:
        # packit_command can be `/packit build` or `/packit build <with_args>`
        msg = f"PR comment '{event.comment[:35]}'"
        try:
            (packit_mark, *packit_command) = event.comment.split(maxsplit=3)
        except ValueError:
            return HandlerResults(success=False,
                                  details={"msg": f"{msg} is empty."})

        if REQUESTED_PULL_REQUEST_COMMENT != packit_mark:
            return HandlerResults(
                success=False,
                details={"msg": f"{msg} is not handled by packit-service."},
            )

        if not packit_command:
            return HandlerResults(
                success=False,
                details={
                    "msg": f"{msg} does not contain a packit-service command."
                },
            )

        # packit has command `copr-build`. But PullRequestCommentAction has enum `copr_build`.
        try:
            packit_action = PullRequestCommentAction[packit_command[0].replace(
                "-", "_")]
        except KeyError:
            return HandlerResults(
                success=False,
                details={
                    "msg":
                    f"{msg} does not contain a valid packit-service command."
                },
            )
        handler_kls: Type[
            PullRequestCommentHandler] = PULL_REQUEST_COMMENT_HANDLER_MAPPING.get(
                packit_action, None)
        if not handler_kls:
            return HandlerResults(
                success=False,
                details={"msg": f"{msg} is not a packit-service command."},
            )

        handler = handler_kls(self.config, event)

        try:
            # check whitelist approval for every job to be able to track down which jobs
            # failed because of missing whitelist approval
            whitelist = Whitelist()
            if not whitelist.check_and_report(event, event.get_project()):
                handlers_results = HandlerResults(
                    success=False,
                    details={"msg": "Account is not whitelisted!"})
                return handlers_results
            handlers_results = handler.run()
        finally:
            handler.clean()
        return handlers_results
Esempio n. 2
0
def test_check_and_report_pr_comment_approve(whitelist):
    event = PullRequestCommentEvent(PullRequestAction["opened"], 0, "", "", "",
                                    "", "", "lojzo", "")
    gp = GitProject("", GitService(), "")
    flexmock(gp).should_receive("pr_comment").with_args(
        0, "Account is not whitelisted!").never()
    assert whitelist.check_and_report(event, gp)
Esempio n. 3
0
def test_check_and_report_pr_comment_reject(whitelist):
    event = PullRequestCommentEvent(PullRequestAction["opened"], 0, "brcalnik",
                                    "", "", "", "", "rakosnicek", "")
    gp = GitProject("", GitService(), "")
    flexmock(gp).should_receive("pr_comment").with_args(
        0,
        "Neither account rakosnicek nor owner brcalnik are on our whitelist!"
    ).once()
    assert not whitelist.check_and_report(event, gp)
Esempio n. 4
0
def events(request) -> List[Tuple[AbstractGithubEvent, bool]]:
    """
    :param request: event type to create Event instances of that type
    :return: list of Events that check_and_report accepts together with whether they should pass
    """
    approved_accounts = [
        ("foo", "bar", False),
        ("foo", "lojzo", True),
        ("lojzo", "bar", True),
        ("lojzo", "fero", True),
    ]

    if request.param == "release":
        return [
            (ReleaseEvent("foo", "", "", ""), False),
            (ReleaseEvent("lojzo", "", "", ""), True),
        ]
    elif request.param == "pr":
        return [(
            PullRequestEvent(PullRequestAction.opened, 1, namespace, "", "",
                             "", "", "", login),
            approved,
        ) for namespace, login, approved in approved_accounts]
    elif request.param == "pr_comment":
        return [(
            PullRequestCommentEvent(
                PullRequestCommentAction.created,
                1,
                namespace,
                "",
                "",
                "",
                "",
                login,
                "",
            ),
            approved,
        ) for namespace, login, approved in approved_accounts]
    elif request.param == "issue_comment":
        return [(
            IssueCommentEvent(
                IssueCommentAction.created,
                1,
                namespace,
                "",
                "",
                "",
                login,
                "",
            ),
            approved,
        ) for namespace, login, approved in approved_accounts]
    return []
 def __init__(self, config: ServiceConfig, event: PullRequestCommentEvent):
     super().__init__(config=config, event=event)
     self.config = config
     self.event = event
     self.project: GitProject = event.get_project()
     # Get the latest pull request commit
     self.event.commit_sha = self.project.get_all_pr_commits(
         self.event.pr_id)[-1]
     self.event.base_ref = self.event.commit_sha
     self.package_config: PackageConfig = self.get_package_config_from_repo(
         self.project, self.event.commit_sha, self.event.pr_id)
     self.package_config.upstream_project_url = event.project_url
Esempio n. 6
0
 def __init__(self, config: ServiceConfig, event: PullRequestCommentEvent):
     super().__init__(config=config, event=event)
     self.config = config
     self.event = event
     self.project: GitProject = event.get_project()
     # Get the latest pull request commit
     self.event.commit_sha = self.project.get_all_pr_commits(self.event.pr_id)[-1]
     self.event.base_ref = self.event.commit_sha
     self.package_config: PackageConfig = get_package_config_from_repo(
         self.project, self.event.commit_sha
     )
     if not self.package_config:
         raise ValueError(f"No config file found in {self.project.full_repo_name}")
     self.package_config.upstream_project_url = event.project_url
Esempio n. 7
0
    def parse_pull_request_comment_event(
            event) -> Optional[PullRequestCommentEvent]:
        """ Look into the provided event and see if it is Github PR comment event. """
        if not nested_get(event, "issue", "pull_request"):
            return None

        pr_id = nested_get(event, "issue", "number")
        action = event.get("action")
        if action not in {"created", "edited"} or not pr_id:
            return None

        comment = nested_get(event, "comment", "body")
        logger.info(
            f"Github PR#{pr_id} comment: {comment!r} {action!r} event.")

        base_repo_namespace = nested_get(event, "repository", "owner", "login")
        base_repo_name = nested_get(event, "repository", "name")
        if not (base_repo_name and base_repo_namespace):
            logger.warning("No full name of the repository.")
            return None

        github_login = nested_get(event, "comment", "user", "login")
        if not github_login:
            logger.warning("No GitHub login name from event.")
            return None
        if github_login in {
                "packit-as-a-service[bot]", "packit-as-a-service-stg[bot]"
        }:
            logger.debug("Our own comment.")
            return None

        target_repo = nested_get(event, "repository", "full_name")
        logger.info(f"Target repo: {target_repo}.")
        https_url = event["repository"]["html_url"]
        return PullRequestCommentEvent(
            PullRequestCommentAction[action],
            pr_id,
            base_repo_namespace,
            base_repo_name,
            None,  # the payload does not include this info
            target_repo,
            https_url,
            github_login,
            comment,
        )
Esempio n. 8
0
    if raises is not None:
        fas.and_raise(raises)

    assert whitelist._signed_fpca(account_name) is signed_fpca


@pytest.mark.parametrize(
    "event, method, approved",
    [
        (
            PullRequestCommentEvent(
                PullRequestCommentAction.created,
                0,
                "foo",
                "",
                "",
                "",
                "",
                "bar",
                "",
            ),
            "pr_comment",
            False,
        ),
        (
            IssueCommentEvent(
                IssueCommentAction.created,
                0,
                "foo",
                "",
                "",
Esempio n. 9
0
     PullRequestEvent(PullRequestAction.opened, 1, "death-star", "", "",
                      "", "", "", "anakin"),
     True,
 ),
 (
     PullRequestEvent(PullRequestAction.opened, 1, "naboo", "", "", "",
                      "", "", "anakin"),
     True,
 ),
 (
     PullRequestCommentEvent(
         PullRequestCommentAction.created,
         1,
         "death-star",
         "",
         "",
         "",
         "",
         "darth-criplicus",
         "",
     ),
     False,
 ),
 (
     PullRequestCommentEvent(
         PullRequestCommentAction.created,
         1,
         "naboo",
         "",
         "",
         "",