org.kohsuke.github.GHPullRequest Java Examples

The following examples show how to use org.kohsuke.github.GHPullRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitHubPRBranchRestriction.java    From github-integration-plugin with MIT License 6 votes vote down vote up
public boolean isBranchBuildAllowed(GHPullRequest remotePR) {
    String branchName = remotePR.getBase().getRef();
    //if allowed branch list is empty, it's allowed to build any branch
    boolean isAllowed = targetBranchList.isEmpty();

    for (String branch : targetBranchList) {
        //if branch name matches to pattern, allow build
        isAllowed = Pattern.compile(branch).matcher(branchName).matches();
        if (isAllowed) {
            break;
        }
    }

    LOGGER.trace("Target branch {} is {} in our whitelist of target branches", branchName,
            (isAllowed ? "" : "not "));
    return isAllowed;
}
 
Example #2
Source File: GitHubPRLabelExistsEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        return null; // already closed, skip check?
    }

    GitHubPRCause cause = null;

    Collection<GHLabel> remoteLabels = remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels();
    Set<String> existingLabels = new HashSet<>();

    for (GHLabel ghLabel : remoteLabels) {
        existingLabels.add(ghLabel.getName());
    }

    if (existingLabels.containsAll(label.getLabelsSet())) {
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": " + label.getLabelsSet() + " found");
        cause = prDecisionContext.newCause(label.getLabelsSet() + " labels exist", isSkip());
    }

    return cause;
}
 
Example #3
Source File: GitHubHelpers.java    From updatebot with Apache License 2.0 6 votes vote down vote up
public static boolean isMergeable(GHPullRequest pullRequest) throws IOException {
    boolean canMerge = false;
    Boolean mergeable = pullRequest.getMergeable();
    GHPullRequest single = null;
    if (mergeable == null) {
        single = pullRequest.getRepository().getPullRequest(pullRequest.getNumber());
        mergeable = single.getMergeable();
    }
    if (mergeable == null) {
        LOG.warn("Mergeable flag is still null on pull request " + pullRequest.getHtmlUrl() + " assuming its still mergable. Probably a caching issue and this flag may appear again later");
        return true;
    }
    if (mergeable != null && mergeable.booleanValue()) {
        canMerge = true;
    }
    return canMerge;
}
 
Example #4
Source File: GitHubPRCloseEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();
    final GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();

    if (isNull(localPR)) {
        return null;
    }

    GitHubPRCause cause = null;

    // must be closed once
    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        logger.println(DISPLAY_NAME + ": state has changed (PR was closed)");
        cause = prDecisionContext.newCause("PR was closed", false);
    }

    return cause;
}
 
Example #5
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
private static void ensureDetailedGHPullRequest(GHPullRequest pr, TaskListener listener, GitHub github, GHRepository ghRepository) throws IOException, InterruptedException {
    final long sleep = 1000;
    int retryCountdown = 4;

    Connector.checkApiRateLimit(listener, github);
    while (pr.getMergeable() == null && retryCountdown > 1) {
        listener.getLogger().format(
            "Waiting for GitHub to create a merge commit for pull request %d.  Retrying %d more times...%n",
            pr.getNumber(),
            retryCountdown);
        retryCountdown -= 1;
        Thread.sleep(sleep);
        Connector.checkApiRateLimit(listener, github);
    }


}
 
Example #6
Source File: GitHubPRLabelPatternExistsEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();

    for (GHLabel ghLabel : remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels()) {
        for (String labelPatternStr : label.getLabelsSet()) {
            Pattern labelPattern = Pattern.compile(labelPatternStr);
            if (labelPattern.matcher(ghLabel.getName()).matches()) {
                logger.println(DISPLAY_NAME + ": Pull request has label: " + labelPatternStr);
                LOGGER.info("Pull request has '{}' label.", labelPatternStr);
                return prDecisionContext.newCause("PR has label: " + labelPatternStr, isSkip());
            }
        }
    }

    return null;
}
 
Example #7
Source File: GitHubHelpers.java    From updatebot with Apache License 2.0 6 votes vote down vote up
public static Boolean waitForPullRequestToHaveMergable(GHPullRequest pullRequest, long sleepMS, long maximumTimeMS) throws IOException {
    long end = System.currentTimeMillis() + maximumTimeMS;
    while (true) {
        Boolean mergeable = pullRequest.getMergeable();
        if (mergeable == null) {
            GHRepository repository = pullRequest.getRepository();
            int number = pullRequest.getNumber();
            pullRequest = repository.getPullRequest(number);
            mergeable = pullRequest.getMergeable();
        }
        if (mergeable != null) {
            return mergeable;
        }
        if (System.currentTimeMillis() > end) {
            return null;
        }
        try {
            Thread.sleep(sleepMS);
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #8
Source File: GitHubPRTrigger.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * @return remote pull requests for future analysing.
 */
private static Set<GHPullRequest> pullRequestsToCheck(@Nullable Integer prNumber,
                                                      @Nonnull GHRepository remoteRepo,
                                                      @Nonnull GitHubPRRepository localRepo) throws IOException {
    if (prNumber != null) {
        return execute(() -> singleton(remoteRepo.getPullRequest(prNumber)));
    } else {
        List<GHPullRequest> remotePulls = execute(() -> remoteRepo.getPullRequests(GHIssueState.OPEN));

        Set<Integer> remotePRNums = from(remotePulls).transform(extractPRNumber()).toSet();

        return from(localRepo.getPulls().keySet())
                // add PRs that was closed on remote
                .filter(not(in(remotePRNums)))
                .transform(fetchRemotePR(remoteRepo))
                .filter(notNull())
                .append(remotePulls)
                .toSet();
    }
}
 
Example #9
Source File: GitHubPRNonMergeableEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();

    Boolean mergeable;
    try {
        mergeable = remotePR.getMergeable();
    } catch (IOException e) {
        listener.error(DISPLAY_NAME + ": can't get mergeable status {}", e);
        LOGGER.warn("Can't get mergeable status: {}", e);
        mergeable = false;
    }
    mergeable = mergeable != null ? mergeable : false;

    if (!mergeable) {
        return prDecisionContext.newCause(DISPLAY_NAME, isSkip());
    }

    return null;
}
 
Example #10
Source File: AbstractRepairStep.java    From repairnator with MIT License 6 votes vote down vote up
protected void createPullRequest(String baseBranch,String newBranch) throws IOException, GitAPIException, URISyntaxException {
    GitHub github = RepairnatorConfig.getInstance().getGithub();

    GHRepository originalRepository = github.getRepository(this.getInspector().getRepoSlug());
    GHRepository ghForkedRepo = originalRepository.fork();

    String base = baseBranch;
    String head = ghForkedRepo.getOwnerName() + ":" + newBranch;

    System.out.println("base: " + base + " head:" + head);
    String travisURL = this.getInspector().getBuggyBuild() == null ? "" : Utils.getTravisUrl(this.getInspector().getBuggyBuild().getId(), this.getInspector().getRepoSlug());
    Map<String, String> values = new HashMap<String, String>();
    values.put("travisURL", travisURL);
    values.put("tools", String.join(",", this.getConfig().getRepairTools()));
    values.put("slug", this.getInspector().getRepoSlug());

    if (prText == null) {
        StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
        this.prText = sub.replace(DEFAULT_TEXT_PR);
    }

    GHPullRequest pullRequest = originalRepository.createPullRequest(prTitle, head, base, this.prText);
    String prURL = "https://github.com/" + this.getInspector().getRepoSlug() + "/pull/" + pullRequest.getNumber();
    this.getLogger().info("Pull request created on: " + prURL);
    this.getInspector().getJobStatus().addPRCreated(prURL);
}
 
Example #11
Source File: GitHubPROpenEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState() == CLOSED) {
        return null; // already closed, nothing to check
    }

    GitHubPRCause cause = null;
    String causeMessage = "PR opened";
    if (isNull(localPR)) { // new
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": state has changed (PR was opened)");
        cause = prDecisionContext.newCause(causeMessage, false);
    }

    return cause;
}
 
Example #12
Source File: BranchDiscoveryTrait.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isExcluded(@NonNull SCMSourceRequest request, @NonNull SCMHead head) {
    if (head instanceof BranchSCMHead && request instanceof GitHubSCMSourceRequest) {
        for (GHPullRequest p : ((GitHubSCMSourceRequest) request).getPullRequests()) {
            GHRepository headRepo = p.getHead().getRepository();
            if (headRepo != null // head repo can be null if the PR is from a repo that has been deleted
                    && p.getBase().getRepository().getFullName().equalsIgnoreCase(headRepo.getFullName())
                    && p.getHead().getRef().equals(head.getName())) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example #13
Source File: GithubSCMSourcePRsTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void testOpenMultiplePRs() throws IOException {
    // Situation: Hitting the Github API all the PRs and they are all Open. Then we close the request at the end
    githubApi.stubFor(
            get(urlEqualTo("/repos/cloudbeers/yolo/pulls?state=open"))
                    .willReturn(
                            aResponse()
                                    .withHeader("Content-Type", "application/json; charset=utf-8")
                                    .withBodyFile("../PRs/_files/body-yolo-pulls-open-multiple-PRs.json")));
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantOriginPRs(true);
    GitHubSCMSourceRequest request = context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    Iterator<GHPullRequest> pullRequest = new GitHubSCMSource("cloudbeers", "yolo", null, false)
            .new LazyPullRequests(request, repo).iterator();
    // Expected: In the iterator will have 2 items in it
    assertTrue(pullRequest.hasNext());
    assertEquals(1, pullRequest.next().getId());
    assertTrue(pullRequest.hasNext());
    assertEquals(2, pullRequest.next().getId());
    assertFalse(pullRequest.hasNext());
    request.close();
}
 
Example #14
Source File: PullRequestSCMHead.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
PullRequestSCMHead(GHPullRequest pr, String name, boolean merge) {
    super(name);
    // the merge flag is encoded into the name, so safe to store here
    this.merge = merge;
    this.number = pr.getNumber();
    this.target = new BranchSCMHead(pr.getBase().getRef());
    // the source stuff is immutable for a pull request on github, so safe to store here
    GHRepository repository = pr.getHead().getRepository(); // may be null for deleted forks JENKINS-41246
    this.sourceOwner = repository == null ? null : repository.getOwnerName();
    this.sourceRepo = repository == null ? null : repository.getName();
    this.sourceBranch = pr.getHead().getRef();

    if (pr.getRepository().getOwnerName().equalsIgnoreCase(sourceOwner)) {
        this.origin = SCMHeadOrigin.DEFAULT;
    } else {
        // if the forked repo name differs from the upstream repo name
        this.origin = pr.getBase().getRepository().getName().equalsIgnoreCase(sourceRepo)
                ? new SCMHeadOrigin.Fork(this.sourceOwner)
                : new SCMHeadOrigin.Fork(repository == null ? this.sourceOwner : repository.getFullName());
    }
}
 
Example #15
Source File: GithubSCMSourcePRsTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void testClosedSinglePR() throws IOException {
    // Situation: Hitting the Github API for a PR and getting a closed PR
    githubApi.stubFor(
            get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1"))
                    .willReturn(
                            aResponse()
                                    .withHeader("Content-Type", "application/json; charset=utf-8")
                                    .withBodyFile("../PRs/_files/body-yolo-pulls-closed-pr.json")));
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    Mockito.when(mockSCMHeadObserver.getIncludes()).thenReturn(Collections
            .singleton(new PullRequestSCMHead("PR-1", "*",
                    "http://localhost:" + githubApi.port(), "master", 1,
                    new BranchSCMHead("master"), SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.MERGE)));
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantPRs();
    GitHubSCMSourceRequest request = context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    Iterator<GHPullRequest> pullRequest = new GitHubSCMSource("cloudbeers", "yolo", null, false)
            .new LazyPullRequests(request, repo).iterator();
    // Expected: In the iterator will be empty
    assertFalse(pullRequest.hasNext());
}
 
Example #16
Source File: GithubSCMSourcePRsTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void testOpenSinglePR() throws IOException {
    // Situation: Hitting the Github API for a PR and getting a open PR
    githubApi.stubFor(
            get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1"))
                    .willReturn(
                            aResponse()
                                    .withHeader("Content-Type", "application/json; charset=utf-8")
                                    .withBodyFile("../PRs/_files/body-yolo-pulls-open-pr.json")));
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    Mockito.when(mockSCMHeadObserver.getIncludes()).thenReturn(Collections
            .singleton(new PullRequestSCMHead("PR-1", "ataylor",
                    "http://localhost:" + githubApi.port(), "master", 1,
                    new BranchSCMHead("master"), SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.MERGE)));
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantPRs();
    GitHubSCMSourceRequest request = context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    Iterator<GHPullRequest> pullRequest = new GitHubSCMSource("cloudbeers", "yolo", null, false)
            .new LazyPullRequests(request, repo).iterator();
    // Expected: In the iterator will have one item in it
    assertTrue(pullRequest.hasNext());
    assertEquals(1, pullRequest.next().getId());
    
    assertFalse(pullRequest.hasNext());
}
 
Example #17
Source File: PullRequestToCauseConverter.java    From github-integration-plugin with MIT License 5 votes vote down vote up
/**
 * TODO migrate to java8 and cleanup.
 *
 * @return only real trigger cause if matched trigger (not skip) event found for this remotePr.
 */
@CheckForNull
@Override
public GitHubPRCause apply(final GHPullRequest remotePR) {

    @CheckForNull
    GitHubPRPullRequest localPR = localRepo.getPulls().get(remotePR.getNumber());
    GitHubPRDecisionContext context = newGitHubPRDecisionContext()
            .withListener(listener)
            .withLocalPR(localPR)
            .withRemotePR(remotePR)
            .withLocalRepo(localRepo)
            .withPrTrigger(trigger)
            .withPrHandler(prHandler)
            .withSCMSource(source)
            .build();

    final List<GitHubPRCause> causes = getEvents().stream()
            .map(e -> toCause(e, context))
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

    GitHubPRCause cause = GitHubPRCause.skipTrigger(causes);

    if (cause != null) {
        LOGGER.debug("Cause [{}] indicated build should be skipped.", cause);
        listener.getLogger().println(String.format("Build of pr %s skipped: %s.", remotePR.getNumber(), cause.getReason()));
        return null;
    } else if (!causes.isEmpty()) {
        // use the first cause from the list
        cause = causes.get(0);
        LOGGER.debug("Using build cause [{}] as trigger for pr [{}].", cause, remotePR.getNumber());
    }

    return cause;
}
 
Example #18
Source File: LocalRepoUpdater.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GHPullRequest apply(GHPullRequest remotePR) {
    if (remotePR.getState() == OPEN) {
        localRepo.getPulls().put(remotePR.getNumber(), new GitHubPRPullRequest(remotePR));
    } else if (remotePR.getState() == CLOSED) {
        localRepo.getPulls().remove(remotePR.getNumber()); // don't store
    }

    return remotePR;
}
 
Example #19
Source File: UserRestrictionFilter.java    From github-integration-plugin with MIT License 5 votes vote down vote up
public static Predicate<GHPullRequest> withUserRestriction(LoggingTaskListenerWrapper listener,
                                                           GitHubPRUserRestriction userRestriction) {
    if (isNull(userRestriction)) {
        return Predicates.alwaysTrue();
    } else {
        return new UserRestrictionFilter(listener, userRestriction);
    }
}
 
Example #20
Source File: GitHubPRCause.java    From github-integration-plugin with MIT License 5 votes vote down vote up
public GitHubPRCause(GHPullRequest remotePr,
                     GitHubPRRepository localRepo,
                     String reason,
                     boolean skip) {
    this(new GitHubPRPullRequest(remotePr), remotePr.getUser(), localRepo, skip, reason);
    withRemoteData(remotePr);
    if (localRepo != null) {
        withLocalRepo(localRepo);
    }
}
 
Example #21
Source File: BranchRestrictionFilterTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldFilterWithRestrictedBranchRestriction() throws Exception {
    when(bRestr.isBranchBuildAllowed(any(GHPullRequest.class))).thenReturn(false);
    
    assertThat("when not allowed", 
            withBranchRestriction(tlRule.getListener(), bRestr).apply(new GHPullRequest()), is(false));
}
 
Example #22
Source File: NotUpdatedPRFilter.java    From github-integration-plugin with MIT License 5 votes vote down vote up
/**
 * lightweight check that comments and time were changed
 */
private static boolean isUpdated(GHPullRequest remotePR, GitHubPRPullRequest localPR) {
    if (isNull(localPR)) {
        return true; // we don't know yet
    }
    try {

        boolean prUpd = new CompareToBuilder()
                .append(localPR.getPrUpdatedAt(), remotePR.getUpdatedAt()).build() < 0; // by time

        boolean issueUpd = new CompareToBuilder()
                .append(localPR.getIssueUpdatedAt(), remotePR.getIssueUpdatedAt()).build() < 0;

        boolean headUpd = !StringUtils.equals(localPR.getHeadSha(), remotePR.getHead().getSha()); // or head?
        boolean updated = prUpd || issueUpd || headUpd;

        if (updated) {
            LOGGER.info("Pull request #{} was created by {}, last updated: {}",
                    localPR.getNumber(), localPR.getUserLogin(), localPR.getPrUpdatedAt());
        }

        return updated;
    } catch (IOException e) {
        // should never happen because
        LOGGER.warn("Can't compare PR [#{} {}] with local copy for update",
                remotePR.getNumber(), remotePR.getTitle(), e);
        return false;
    }
}
 
Example #23
Source File: GithubSCMSourcePRsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void testOpenSinglePRThrowsIOOnObserve() throws Exception {
    // Situation: Hitting the Github API for a PR and an IO exception during the getPullRequest
    githubApi.stubFor(
            get(urlEqualTo("/repos/cloudbeers/yolo/pulls/1"))
                    .willReturn(
                            aResponse()
                                    .withHeader("Content-Type", "application/json; charset=utf-8")
                                    .withBodyFile("../PRs/_files/body-yolo-pulls-open-pr.json")));
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    Mockito.when(mockSCMHeadObserver.getIncludes()).thenReturn(Collections
            .singleton(new PullRequestSCMHead("PR-1", "ataylor",
                    "http://localhost:" + githubApi.port(), "master", 1,
                    new BranchSCMHead("master"), SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.MERGE)));
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantPRs();

    //Spy on repo
    GHRepository repoSpy = Mockito.spy(repo);
    GHPullRequest pullRequestSpy = Mockito.spy(repoSpy.getPullRequest(1));
    Mockito.when(repoSpy.getPullRequest(1)).thenReturn(pullRequestSpy);
    //then throw on the PR during observe
    Mockito.when(pullRequestSpy.getUser()).thenThrow(new IOException("Failed to get user"));
    GitHubSCMSourceRequest request = context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    Iterator<GHPullRequest> pullRequestIterator = new GitHubSCMSource("cloudbeers", "yolo", null, false)
            .new LazyPullRequests(request, repoSpy).iterator();

    // Expected: In the iterator will have one item in it but when getting that item you receive an IO exception
    assertTrue(pullRequestIterator.hasNext());
    try{
        pullRequestIterator.next();
        fail();
    } catch (Exception e) {
        assertEquals("java.io.IOException: Failed to get user", e.getMessage());
    }
}
 
Example #24
Source File: SkipPRInBadState.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public boolean apply(@Nullable GHPullRequest remotePR) {
    if (isNull(remotePR)) {
        return true;
    }

    @CheckForNull GitHubPRPullRequest localPR = localRepo.getPulls().get(remotePR.getNumber());

    if (localPR != null && localPR.isInBadState()) {
        logger.error("local PR [#{} {}] is in bad state", remotePR.getNumber(), remotePR.getTitle());
        return false;
    }

    return true;
}
 
Example #25
Source File: UserRestrictionFilter.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public boolean apply(GHPullRequest remotePR) {
    if (!userRestriction.isWhitelisted(remotePR.getUser())) {
        listener.info("Skipping [#{} {}] because of user restriction (user - {})",
                remotePR.getNumber(), remotePR.getTitle(), remotePR.getUser());
        return false;
    }

    return true;
}
 
Example #26
Source File: GitHubPRCommentEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) {
    final TaskListener listener = prDecisionContext.getListener();
    final PrintStream llog = listener.getLogger();
    final GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    final GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final GitHubPRUserRestriction prUserRestriction = prDecisionContext.getPrUserRestriction();

    GitHubPRCause cause = null;
    try {
        for (GHIssueComment issueComment : remotePR.getComments()) {
            if (isNull(localPR) // test all comments for trigger word even if we never saw PR before
                    || isNull(localPR.getLastCommentCreatedAt()) // PR was created but had no comments
                    // don't check comments that we saw before
                    || localPR.getLastCommentCreatedAt().compareTo(issueComment.getCreatedAt()) < 0) {
                llog.printf("%s: state has changed (new comment found - '%s')%n",
                        DISPLAY_NAME, issueComment.getBody());

                cause = checkComment(prDecisionContext, issueComment, prUserRestriction, listener);
                if (nonNull(cause)) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("Couldn't obtain comments: {}", e);
        listener.error("Couldn't obtain comments", e);
    }

    if (isNull(cause)) {
        LOG.debug("No matching comments found for {}", remotePR.getNumber());
        llog.println("No matching comments found for " + remotePR.getNumber());
    }

    return cause;
}
 
Example #27
Source File: PRHelperFunctions.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GHPullRequest apply(Integer input) {
    try {
        return ghRepository.getPullRequest(input);
    } catch (IOException e) {
        LOGGER.error("Can't fetch pr by num {}", input, e);
        return null;
    }
}
 
Example #28
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public void detectAtPullRequest(String cloneURL, int pullRequestId, RefactoringHandler handler, int timeout) throws IOException {
	GitHub gitHub = connectToGitHub();
	String repoName = extractRepositoryName(cloneURL);
	GHRepository repository = gitHub.getRepository(repoName);
	GHPullRequest pullRequest = repository.getPullRequest(pullRequestId);
	PagedIterable<GHPullRequestCommitDetail> commits = pullRequest.listCommits();
	for(GHPullRequestCommitDetail commit : commits) {
		detectAtCommit(cloneURL, commit.getSha(), handler, timeout);
	}
}
 
Example #29
Source File: GithubSCMSourcePRsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void testOpenMultiplePRsWithMasterAsOrigin() throws IOException {
    // Situation: Hitting the Github API all the PRs and they are all Open but the master is the head branch
    githubApi.stubFor(
            get(urlEqualTo("/repos/cloudbeers/yolo/pulls?state=open&head=cloudbeers%3Amaster"))
                    .willReturn(
                            aResponse()
                                    .withHeader("Content-Type", "application/json; charset=utf-8")
                                    .withBodyFile("../PRs/_files/body-yolo-pulls-open-multiple-PRs.json")));
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantOriginPRs(true);
    Set<SCMHead> masterSet = new HashSet<>();
    SCMHead masterHead = new BranchSCMHead("master");
    masterSet.add(masterHead);
    GitHubSCMSourceContext contextSpy = Mockito.spy(context);
    Mockito.when(contextSpy.observer().getIncludes()).thenReturn(masterSet);
    GitHubSCMSourceRequest request = contextSpy.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    Iterator<GHPullRequest> pullRequest = new GitHubSCMSource("cloudbeers", "yolo", null, false)
            .new LazyPullRequests(request, repo).iterator();
    // Expected: In the iterator will have 2 items in it
    assertTrue(pullRequest.hasNext());
    assertEquals(1, pullRequest.next().getId());
    assertTrue(pullRequest.hasNext());
    assertEquals(2, pullRequest.next().getId());
    assertFalse(pullRequest.hasNext());
}
 
Example #30
Source File: CompositeCommand.java    From updatebot with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked from a polling/update command
 */
public void run(CommandContext context, GHRepository ghRepository, GHPullRequest pullRequest) throws IOException {
    for (CommandSupport command : getCommands()) {
        command.validateConfiguration(context.getConfiguration());
        if (command instanceof ModifyFilesCommandSupport) {
            ModifyFilesCommandSupport modifyCommand = (ModifyFilesCommandSupport) command;
            modifyCommand.run(context, ghRepository, pullRequest);
        }
    }
}