com.atlassian.bitbucket.pull.PullRequest Java Examples
The following examples show how to use
com.atlassian.bitbucket.pull.PullRequest.
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: PullRequestListener.java From pr-harmony with GNU General Public License v3.0 | 6 votes |
PullRequest findPRByCommitId(String commitId) { PullRequestSearchRequest request = new PullRequestSearchRequest.Builder() .state(PullRequestState.OPEN) .withProperties(false) .build(); PageRequest nextPage = new PageRequestImpl(0, SEARCH_PAGE_SIZE); do { Page<PullRequest> page = prService.search(request, nextPage); PullRequest pr = searchForPR(page, commitId); if(pr != null) { return pr; } else { nextPage = page.getNextPageRequest(); } } while(nextPage != null); return null; }
Example #2
Source File: TeamcityPullrequestEventListener.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 6 votes |
@EventListener public void onPullRequestRescoped(final PullRequestRescopedEvent event) throws IOException, JSONException { final String previousFromHash = event.getPreviousFromHash(); final String currentFromHash = event.getPullRequest().getFromRef().getLatestCommit(); if (currentFromHash.equals(previousFromHash)) { return; } final PullRequest pr = event.getPullRequest(); final Repository repo = pr.getFromRef().getRepository(); final Optional<Settings> settings = this.settingsService.getSettings(repo); if(!settings.isPresent()) { return; } try { TeamcityLogger.logMessage(settings.get(), "Run PullRequest Rescoped Event : " + pr.getFromRef().getDisplayId()); TriggerBuildFromPullRequest(pr, false); } catch (final IOException | JSONException ex) { TeamcityLogger.logMessage(settings.get(), "PullRequest Rescoped Event Failed: " + ex.getMessage() + " " + pr.getFromRef().getDisplayId()); } }
Example #3
Source File: TeamcityPullrequestEventListener.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 6 votes |
@EventListener public void onPullRequestParticipantsUpdatedEvent(final PullRequestParticipantsUpdatedEvent event) throws IOException, JSONException { final PullRequest pr = event.getPullRequest(); final Set<PullRequestParticipant> reviewers = pr.getReviewers(); final Repository repo = pr.getFromRef().getRepository(); final Optional<Settings> settings = this.settingsService.getSettings(repo); if(!settings.isPresent()) { return; } if (event.getAddedParticipants().size() > 0 && reviewers.size() > 0) { // trigger only when number of participations is 2 or higher (author + reviewer) try { TriggerBuildFromPullRequest(event.getPullRequest(), true); } catch (final IOException | JSONException ex) { TeamcityLogger.logMessage(settings.get(), "PullRequest Reviwer update event failed: " + ex.getMessage()); } } }
Example #4
Source File: TeamcityPullrequestEventListener.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 6 votes |
@EventListener public void onPullRequestOpenedEvent(final PullRequestOpenedEvent event) throws IOException, JSONException { final PullRequest pr = event.getPullRequest(); final Repository repo = pr.getFromRef().getRepository(); final Optional<Settings> settings = this.settingsService.getSettings(repo); if(!settings.isPresent()) { return; } try { TriggerBuildFromPullRequest(pr, false); } catch (final IOException | JSONException ex) { TeamcityLogger.logMessage(settings.get(), "PullRequest Opened Event Failed: " + ex.getMessage()); } }
Example #5
Source File: ChangesetService.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 6 votes |
public static ArrayList<String> GetChangedFiles(final PullRequest pr, final PullRequestService pullRequestService) { final ArrayList<String> changedfilespath = new ArrayList<>(); pullRequestService.streamChanges(new PullRequestChangesRequest.Builder(pr).build(), new ChangeCallback() { @Override public boolean onChange(Change change) throws IOException { changedfilespath.add(change.getPath().toString()); return true; } @Override public void onEnd(ChangeSummary cs) throws IOException { // dont do anything. } @Override public void onStart(ChangeContext cc) throws IOException { // dont do anything. } }); return changedfilespath; }
Example #6
Source File: ScheduledMetricEvaluatorImpl.java From prom-bitbucket-exporter with BSD 2-Clause "Simplified" License | 6 votes |
private void calculateTotalPullRequests() { try { securityService.withPermission(Permission.ADMIN, "Read all pull requests").call(new Operation<Object, Throwable>() { @Override public Object perform() { int pullRequests = 0; PageRequest nextPage = new PageRequestImpl(0, 10000); do { Page<PullRequest> pullRequestPage = pullRequestService.search(new PullRequestSearchRequest.Builder().state(OPEN).build(), nextPage); pullRequests += pullRequestPage.getSize(); nextPage = pullRequestPage.getNextPageRequest(); } while (nextPage != null); totalPullRequests.set(pullRequests); return null; } }); } catch (Throwable th) { log.error("Cannot read all pull requests", th); } }
Example #7
Source File: MergeBlocker.java From pr-harmony with GNU General Public License v3.0 | 6 votes |
@Override public void check(@Nonnull MergeRequest mergeRequest) { PullRequest pr = mergeRequest.getPullRequest(); Repository repo = pr.getToRef().getRepository(); final Config config = configDao.getConfigForRepo(repo.getProject().getKey(), repo.getSlug()); String branch = regexUtils.formatBranchName(pr.getToRef().getId()); if (regexUtils.match(config.getBlockedPRs(), branch)) { mergeRequest.veto("Pull Request Blocked", "Pull requests have been disabled for branch [" + branch + "]"); } else { PullRequestApproval approval = new PullRequestApproval(config, userUtils); if (!approval.isPullRequestApproved(pr)) { Set<String> missing = approval.missingRevieiwersNames(pr); mergeRequest.veto("Required reviewers must approve", (config.getRequiredReviews() - approval.seenReviewers(pr).size()) + " more approvals required from the following users: " + Joiner.on(", ").join(missing)); } else { Boolean needsWork = config.getBlockMergeIfPrNeedsWork(); final Boolean blockAutoMergeBecausePrNeedsWork = needsWork != null && needsWork && needsWork(pr); if (blockAutoMergeBecausePrNeedsWork) { mergeRequest.veto("Needs work", "PR marked as Needs Work from reviewer(s)"); } } } }
Example #8
Source File: PullRequestListener.java From pr-harmony with GNU General Public License v3.0 | 5 votes |
void automergePullRequest(PullRequest pr) { Repository repo = pr.getToRef().getRepository(); Config config = configDao.getConfigForRepo(repo.getProject().getKey(), repo.getSlug()); String toBranch = regexUtils.formatBranchName(pr.getToRef().getId()); String fromBranch = regexUtils.formatBranchName(pr.getFromRef().getId()); if((regexUtils.match(config.getAutomergePRs(), toBranch) || regexUtils.match(config.getAutomergePRsFrom(), fromBranch)) && !regexUtils.match(config.getBlockedPRs(), toBranch) && prService.canMerge(repo.getId(), pr.getId()).canMerge()) { securityService.impersonating(pr.getAuthor().getUser(), "Performing automerge on behalf of " + pr.getAuthor().getUser().getSlug()).call(() -> { prService.merge(new PullRequestMergeRequest.Builder(pr).build()); return null; }); } }
Example #9
Source File: PullRequestListener.java From pr-harmony with GNU General Public License v3.0 | 5 votes |
private PullRequest searchForPR(Page<PullRequest> requests, String commitId) { for(PullRequest pr : requests.getValues()) { AtomicBoolean found = new AtomicBoolean(false); prService.streamCommits(pr.getToRef().getRepository().getId(), pr.getId(), commit -> { found.set(commit.getId().equals(commitId)); return !found.get(); }); if(found.get()) { return pr; } } return null; }
Example #10
Source File: AreBuildsInQueueOrRunningCheck.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
@Override public RepositoryHookResult preUpdate(@Nonnull PreRepositoryHookContext prhc, @Nonnull PullRequestMergeHookRequest t) { PullRequest pr = t.getPullRequest(); Repository repository = pr.getToRef().getRepository(); Optional<Settings> settings = this.settingsService.getSettings(repository); if(!settings.isPresent()) { return RepositoryHookResult.accepted(); } TeamcityLogger.logMessage(settings.get(), "[AreBuildsInQueueOrRunningCheck] Queue Checker Started"); final String teamcityAddress = settings.get().getString("teamCityUrl"); if(teamcityAddress == null || "".equals(teamcityAddress)) { return RepositoryHookResult.accepted(); } final String password = this.connectionSettings.getPassword(repository); final TeamcityConfiguration conf = new TeamcityConfiguration( settings.get().getString("teamCityUrl"), settings.get().getString("teamCityUserName"), password); final String branch = pr.getFromRef().getDisplayId(); if(AreBuildsInQueueForBranch(branch, conf, settings.get())) { TeamcityLogger.logMessage(settings.get(), "Builds in queue for " + branch); String teamcityAddressQueue = settings.get().getString("teamCityUrl") + "/queue.html"; String summaryMsg = i18nService.getText("mergecheck.builds.inqueue.summary", "Builds in queue or running"); String detailedMsg = i18nService.getText("mergecheck.builds.inqueue.detailed", "Builds are still in queue or running, visit: ") + teamcityAddressQueue; TeamcityLogger.logMessage(settings.get(), "[AreBuildsInQueueOrRunningCheck] builds in queue for " + branch + " reject"); return RepositoryHookResult.rejected(summaryMsg, detailedMsg); } TeamcityLogger.logMessage(settings.get(), "[AreBuildsInQueueOrRunningCheck] No builds in queue for " + branch); return RepositoryHookResult.accepted(); }
Example #11
Source File: PullRequestListener.java From pr-harmony with GNU General Public License v3.0 | 5 votes |
@Override public void run() { securityService.withPermission(Permission.ADMIN, "Automerge check (PR approval)").call(() -> { PullRequest pr = findPRByCommitId(commitId); if(pr != null) { automergePullRequest(pr); } return null; }); }
Example #12
Source File: FileNameHook.java From stash-filehooks-plugin with Apache License 2.0 | 5 votes |
@Override public void check(RepositoryMergeRequestCheckContext context) { final MergeRequest request = context.getMergeRequest(); final PullRequest pr = request.getPullRequest(); final Commit prFrom = getChangeSet(pr.getFromRef()); final Commit prTo = getChangeSet(pr.getToRef()); final Commit base = mergeBaseResolver.findMergeBase(prFrom, prTo); final FileNameHookSetting setting = getSettings(context.getSettings()); final ChangesRequest.Builder builder = new ChangesRequest.Builder(prFrom.getRepository(), prFrom.getId()); if (base.getId() != null) { builder.sinceId(base.getId()); } final ChangesRequest pathsRequest = builder.build(); final ChangedPathsCollector pathsCallback = new ChangedPathsCollector(); commitService.streamChanges(pathsRequest, pathsCallback); Collection<String> filteredFiles = pathsCallback.getChangedPaths(); filteredFiles = filteredFiles.stream().filter(setting.getIncludePattern().asPredicate()).collect(Collectors.toList()); if(setting.getExcludePattern().isPresent()) { Pattern excludePattern = setting.getExcludePattern().get(); filteredFiles = filteredFiles.stream().filter(excludePattern.asPredicate().negate()).collect(Collectors.toList()); } if (filteredFiles.size() > 0) { request.veto(i18n.getText("filename-hook.mergecheck.veto", "File Name Hook: The following files violate the file name pattern [{0}]:", setting.getIncludePattern().pattern()), getPullRequestError(filteredFiles)); } }
Example #13
Source File: PullRequestApproval.java From pr-harmony with GNU General Public License v3.0 | 5 votes |
public Set<String> missingRevieiwersNames(PullRequest pr) { Map<String, PullRequestParticipant> map = transformReviewers(pr); Set<String> missingReviewers = newHashSet(); for(String req : concat(config.getRequiredReviewers(), utils.dereferenceGroups(config.getRequiredReviewerGroups()))) { if(reviewerIsMissing(map.get(req.toLowerCase())) && !(submitterIsRequiredReviewer(pr, req.toLowerCase()) && exactlyEnoughRequiredReviewers())) { missingReviewers.add(utils.getUserDisplayNameByName(req)); } } return missingReviewers; }
Example #14
Source File: PullRequestApproval.java From pr-harmony with GNU General Public License v3.0 | 5 votes |
public Set<String> missingRevieiwers(PullRequest pr) { Map<String, PullRequestParticipant> map = transformReviewers(pr); Set<String> missingReviewers = newHashSet(); for(String req : concat(config.getRequiredReviewers(), utils.dereferenceGroups(config.getRequiredReviewerGroups()))) { if(reviewerIsMissing(map.get(req.toLowerCase())) && !(submitterIsRequiredReviewer(pr, req.toLowerCase()) && exactlyEnoughRequiredReviewers())) { missingReviewers.add(req); } } return missingReviewers; }
Example #15
Source File: WebhookIsEnabledCondition.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
private PullRequest getPullRequest(Map<String, Object> context, Repository repo) { Object request = context.get("request"); if (!(request instanceof HttpServletRequest)) { return null; } String path = ((HttpServletRequest) request).getRequestURI(); Matcher matcher = REPOREGEX.matcher(path); if (matcher.matches()) { long prId = Long.parseLong(matcher.group(3)); return pullRequestService.getById(repo.getId(), prId); } return null; }
Example #16
Source File: TeamcityPullrequestEventListener.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 4 votes |
private void TriggerBuildFromPullRequest(final PullRequest pr, Boolean UpdatedReviewers) throws IOException, JSONException { final Repository repo = pr.getFromRef().getRepository(); final Optional<Settings> settings = this.settingsService.getSettings(repo); if(!settings.isPresent()) { return; } final String password = this.connectionSettings.getPassword(pr.getFromRef().getRepository()); // has one reviewer final Boolean areParticipants = !pr.getReviewers().isEmpty(); final TeamcityConfiguration conf = new TeamcityConfiguration( settings.get().getString("teamCityUrl"), settings.get().getString("teamCityUserName"), password); final String branch = pr.getFromRef().getId(); final String repositoryTriggersJson = settings.get().getString(Field.REPOSITORY_TRIGGERS_JSON, StringUtils.EMPTY); if (repositoryTriggersJson.isEmpty()) { return; } Set triggeredBuilds = new HashSet(); final ArrayList<String> changes = ChangesetService.GetChangedFiles(pr, pullRequestService); final Trigger[] configurations = Trigger.GetBuildConfigurationsFromBranch(repositoryTriggersJson, branch); for (final Trigger buildConfig : configurations) { TeamcityLogger.logMessage(settings.get(), "Try Trigger: " + buildConfig.getBranchConfig() + " " + branch + " : " + buildConfig.getTarget()); if (buildConfig.isTriggerOnPullRequest()) { if (UpdatedReviewers && buildConfig.isTriggerWhenNoReviewers()) { TeamcityLogger.logMessage(settings.get(), "Skip For Update Reviewers: " + buildConfig.getBranchConfig() + " " + branch); // we dont want to build when reviewers were updated and we allow to trigger when no reviwers are defined continue; } if (!areParticipants && !buildConfig.isTriggerWhenNoReviewers()) { // we dont want to build if there are no participants TeamcityLogger.logMessage(settings.get(), "Skip: " + buildConfig.getBranchConfig() + " " + branch); continue; } if (triggeredBuilds.contains(buildConfig.getTarget())) { continue; } if (!ExclusionTriggers.ShouldTriggerOnListOfFiles(buildConfig.gettriggerInclusion(), buildConfig.gettriggerExclusion(), changes)) { continue; } TeamcityLogger.logMessage(settings.get(), "Trigger BuildId: " + buildConfig.getTarget() + " " + branch); try { if (this.connector.IsInQueue(conf, buildConfig.getTarget(), buildConfig.getBranchConfig(), settings.get())) { TeamcityLogger.logMessage(settings.get(), "Skip already in queue: " + buildConfig.getTarget()+ " " + branch); continue; } } catch (IOException | JSONException ex) { TeamcityLogger.logMessage(settings.get(), "Exception: " + ex.getMessage() + " " + branch); } // check if build is running final String buildData = this.connector.GetBuildsForBranch( conf, buildConfig.getBranchConfig(), buildConfig.getTarget(), settings.get()); final JSONObject obj = new JSONObject(buildData); final String count = obj.getString("count"); if (count.equals("0") || !buildConfig.isCancelRunningBuilds()) { this.connector.QueueBuild( conf, buildConfig.getBranchConfig(), buildConfig.getTarget(), "Trigger from Bitbucket: Pull Request: " + pr.getId(), false, settings.get()); triggeredBuilds.add(buildConfig.getTarget()); } else { final JSONArray builds = obj.getJSONArray("build"); for (int i = 0; i < builds.length(); i++) { final Boolean isRunning = builds.getJSONObject(i).getString("state").equals("running"); if (isRunning) { final String id = builds.getJSONObject(i).getString("id"); this.connector.ReQueueBuild(conf, id, settings.get(), false); } } // at this point all builds were finished, so we need to trigger this.connector.QueueBuild( conf, buildConfig.getBranchConfig(), buildConfig.getTarget(), "Trigger from Bitbucket: Pull Request: " + pr.getId(), false, settings.get()); } } } }
Example #17
Source File: PullRequestListener.java From pr-harmony with GNU General Public License v3.0 | 4 votes |
public ApprovalTaskProcessor(PullRequest pr) { this.pr = pr; }
Example #18
Source File: WebhookIsEnabledCondition.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 4 votes |
/** * {@inheritDoc} */ @Override public boolean shouldDisplay(final Map<String, Object> context) { final Repository repository = getRepository(context); if (repository == null) { return false; } try { final RepositoryHook hook = this.settingsService.getRepositoryHook(repository); final Optional<Settings> settings = this.settingsService.getSettings(repository); if(!settings.isPresent()) { return false; } if (hook == null || !hook.isEnabled()) { return false; } final PullRequest pullrequest = getPullRequest(context, repository); if (pullrequest == null) { return false; } final String repositoryTriggersJson = settings.get().getString(Field.REPOSITORY_TRIGGERS_JSON, StringUtils.EMPTY); if (repositoryTriggersJson.isEmpty()) { return false; } // check if builds are configured final PullRequestRef ref = pullrequest.getFromRef(); final String branch = ref.getId(); final Trigger[] configurations = Trigger.GetBuildConfigurationsFromBranch(repositoryTriggersJson, branch); if (configurations.length > 0) { return true; } } catch (final Exception ex) { } return false; }
Example #19
Source File: PullRequestApproval.java From pr-harmony with GNU General Public License v3.0 | 4 votes |
Boolean submitterIsRequiredReviewer(PullRequest pr, String username) { return pr.getAuthor().getUser().getSlug().equals(username); }
Example #20
Source File: PullRequestApproval.java From pr-harmony with GNU General Public License v3.0 | 4 votes |
Map<String, PullRequestParticipant> transformReviewers(PullRequest pr) { return uniqueIndex(pr.getReviewers(), input -> input.getUser().getSlug()); }
Example #21
Source File: PullRequestApproval.java From pr-harmony with GNU General Public License v3.0 | 4 votes |
public Set<String> seenReviewers(PullRequest pr) { Set<String> required = newHashSet(concat(config.getRequiredReviewers(), utils.dereferenceGroups(config.getRequiredReviewerGroups()))); return difference(required, missingRevieiwers(pr)); }
Example #22
Source File: PullRequestApproval.java From pr-harmony with GNU General Public License v3.0 | 4 votes |
public boolean isPullRequestApproved(PullRequest pr) { Integer requiredReviews = config.getRequiredReviews(); return requiredReviews == null || seenReviewers(pr).size() >= requiredReviews; }