com.atlassian.bitbucket.repository.Repository Java Examples
The following examples show how to use
com.atlassian.bitbucket.repository.Repository.
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: ChangesetService.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 7 votes |
public static ArrayList<String> GetChangedFiles(final CommitService scmService, final Repository repository, RefChange refChange) { final ArrayList<String> changedfilespath = new ArrayList<>(); ChangesRequest changesRequest = new ChangesRequest.Builder(repository, refChange.getToHash()).sinceId(refChange.getFromHash()).build(); scmService.streamChanges(changesRequest, 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 { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void onStart(ChangeContext cc) throws IOException { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); return changedfilespath; }
Example #2
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 #3
Source File: WebhookIsEnabledCondition.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 6 votes |
private Repository getRepository(Map<String, Object> context) { final Object obj = context.get("repository"); if (!(obj instanceof Repository)) { Object request = context.get("request"); if (!(request instanceof HttpServletRequest)) { return null; } String path = ((HttpServletRequest) request).getRequestURI(); Matcher matcher = REPOREGEX.matcher(path); if (matcher.matches()) { String projectKey = matcher.group(1); String repoSlug = matcher.group(2); return repositoryService.getBySlug(projectKey, repoSlug); } return null; } return (Repository) obj; }
Example #4
Source File: MirrorRepositoryHook.java From stash-hook-mirror with MIT License | 6 votes |
/** * Schedules pushes to apply the latest changes to any configured mirrors. * * @param context provides hook settings and a way to obtain the commits added/removed * @param request provides details about the refs that have been updated */ @Override public void postUpdate(@Nonnull PostRepositoryHookContext context, @Nonnull RepositoryHookRequest request) { if (TRIGGERS_TO_IGNORE.contains(request.getTrigger())) { logger.trace("MirrorRepositoryHook: skipping trigger {}", request.getTrigger()); return; } Repository repository = request.getRepository(); if (!GitScm.ID.equalsIgnoreCase(repository.getScmId())) { return; } List<MirrorSettings> mirrorSettings = getMirrorSettings(context.getSettings()); if (mirrorSettings.isEmpty()) { logger.debug("{}: Mirroring is not configured", repository); } else { logger.debug("{}: Scheduling pushes for {} remote(s) after {}", repository, mirrorSettings.size(), request.getTrigger()); schedulePushes(repository, mirrorSettings); } }
Example #5
Source File: TeamctiyRest.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 6 votes |
/** * Trigger a build on the Teamcity instance using vcs root * * @param repository The repository to trigger * @return The response. Ok if it worked. Otherwise, an error. */ @GET @Path(value = "triggerexternalurl") public String triggerexternalurl(@Context final Repository repository, @QueryParam("url") final String url, @QueryParam("method") final String method) { final HttpConnector dummyConnector = new HttpConnector(); String returnData; try { final Optional<Settings> settings = this.settingsService.getSettings(repository); if (!settings.isPresent()) { return "{\"status\": \"error\", \"message\": \"hook not configured\"}"; } returnData = dummyConnector.Get(url, settings.get()); return "{\"status\": \"ok\", \"message\": \" " + returnData + "\" }"; } catch (final IOException ex) { return "{\"status\": \"failed\", \"message\": \" " + ex.getMessage() + "\" }"; } }
Example #6
Source File: MirrorRepositoryHookTest.java From stash-hook-mirror with MIT License | 6 votes |
@Test public void testPostUpdate() { when(passwordEncryptor.decrypt(anyString())).thenReturn(password); Repository repo = mock(Repository.class); when(repo.getId()).thenReturn(1); when(repo.getScmId()).thenReturn(GitScm.ID); hook.postUpdate(buildContext(), new RepositoryPushHookRequest.Builder(repo).build()); verify(repo).getId(); verify(repo).getScmId(); verify(bucketedExecutor).schedule(requestCaptor.capture(), eq(5L), same(TimeUnit.SECONDS)); MirrorRequest request = requestCaptor.getValue(); assertEquals(1, request.getRepositoryId()); }
Example #7
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 #8
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 #9
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 #10
Source File: ChangesetServiceImpl.java From stash-filehooks-plugin with Apache License 2.0 | 6 votes |
private Iterable<Changeset> getChangesets(final Repository repository, Iterable<Commit> commits) { Iterable<Changeset> changesets = new ArrayList<>(); final Collection<String> commitIds = StreamSupport.stream(commits.spliterator(), false) .map(Commit::getId) .collect(Collectors.toSet()); if (!commitIds.isEmpty()) { changesets = new PagedIterable<>(pageRequest -> scmService.getCommandFactory(repository).changesets( new ChangesetsCommandParameters.Builder() .commitIds(commitIds) .maxChangesPerCommit(MAX_CHANGES_PER_COMMIT) .maxMessageLength(0) .build(), pageRequest).call(), PAGE_REQUEST); } return changesets; }
Example #11
Source File: CommitBlockerHook.java From pr-harmony with GNU General Public License v3.0 | 6 votes |
@Override public boolean onReceive(Repository repository, Collection<RefChange> collection, HookResponse hookResponse) { Config config = configDao.getConfigForRepo(repository.getProject().getKey(), repository.getSlug()); UserProfile user = userManager.getRemoteUser(); for(RefChange ch : collection) { String branch = regexUtils.formatBranchName(ch.getRef().getId()); Set<String> excluded = newHashSet(concat(config.getExcludedUsers(), userUtils.dereferenceGroups(config.getExcludedGroups()))); if(regexUtils.match(config.getBlockedCommits(), branch) && !excluded.contains(user.getUsername())) { hookResponse.err().write("\n" + "******************************\n" + "* !! Commit Rejected !! *\n" + "******************************\n\n" + "Direct commits are not allowed\n" + "to branch [" + branch + "].\n\n" ); return false; } } return true; }
Example #12
Source File: ScheduledMetricEvaluatorImpl.java From prom-bitbucket-exporter with BSD 2-Clause "Simplified" License | 6 votes |
private void calculateTotalRepositories() { try { securityService.withPermission(Permission.ADMIN, "Read all repositories").call(new Operation<Object, Throwable>() { @Override public Object perform() { int repositories = 0; PageRequest nextPage = new PageRequestImpl(0, 10000); do { Page<Repository> repositoryPage = repositoryService.findAll(nextPage); repositories += repositoryPage.getSize(); nextPage = repositoryPage.getNextPageRequest(); } while (nextPage != null); totalRepositories.set(repositories); return null; } }); } catch (Throwable th) { log.error("Cannot read all repositories", th); } }
Example #13
Source File: ConfigServlet.java From pr-harmony with GNU General Public License v3.0 | 6 votes |
void renderRepoSettings(String projectKey, String repoSlug, String username, HttpServletResponse response) throws IOException { Repository repo = repoService.getBySlug(projectKey, repoSlug); if(repo == null) { logger.warn("Project/Repo [{}/{}] not found for user {}", projectKey, repoSlug, username); response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } ApplicationUser appUser = userUtils.getApplicationUserByName(username); if(permissionService.hasRepositoryPermission(appUser, repo, Permission.REPO_ADMIN)) { response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html;charset=utf-8"); renderer.render("repo-config.html", ImmutableMap.<String, Object>of( "projectKey", projectKey, "repositorySlug", repoSlug ), response.getWriter()); } else { logger.debug("Permission denied for user [{}]", username); response.setStatus(HttpServletResponse.SC_FORBIDDEN); } }
Example #14
Source File: TeamctiyRest.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
/** * Trigger a build on the Teamcity instance using vcs root * * @param repository The repository to trigger * @param page * @return The response. Ok if it worked. Otherwise, an error. */ @GET @Path(value = "loadjs") @Produces("text/javascript") public String loadjs(@Context final Repository repository, @QueryParam("page") final String page) { final ClassLoader classloader = Thread.currentThread().getContextClassLoader(); final InputStream is = classloader.getResourceAsStream("public/" + page); final String file = convertStreamToString(is); return file; }
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: SettingsService.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
public Optional<Settings> getSettings(final Repository repository) { try { final RepositoryHookSettings settings = this.securityService .withPermission(Permission.REPO_ADMIN, "Retrieving settings") .call( new Operation<RepositoryHookSettings, Exception>() { @Override public RepositoryHookSettings perform() throws Exception { final RepositoryHook hook = SettingsService.this.hookService.getByKey( new RepositoryScope(repository), SettingsService.KEY); if (!hook.isEnabled() || !hook.isEnabled()) { return null; } final GetRepositoryHookSettingsRequest req = new GetRepositoryHookSettingsRequest.Builder( new RepositoryScope(repository), SettingsService.KEY) .build(); return SettingsService.this.hookService.getSettings(req); } }); if (settings == null) { return empty(); } LOGGER.info("Using settings:\n" + settings); return Optional.of(settings.getSettings()); } catch (final Exception e) { LOGGER.error("Unexpected exception trying to get repository settings", e); return empty(); } }
Example #17
Source File: SettingsService.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
/** * Get the repository hook context for this hook in the provided repository. * @param repository The repository * @return The hook context */ public RepositoryHook getRepositoryHook(final Repository repository) { try { return this.securityService.withPermission(Permission.REPO_ADMIN, "Retrieving repository hook") .call(new Operation<RepositoryHook, RuntimeException>() { @Override public RepositoryHook perform() throws RuntimeException { return SettingsService.this.hookService.getByKey(new RepositoryScope(repository), SettingsService.KEY); } }); } catch (final Exception e) { LOGGER.error("Unexpected exception trying to get repository hook", e); return null; } }
Example #18
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 #19
Source File: TeamctiyRest.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
/** * Trigger a build on the Teamcity instance using vcs root * * @param repository The repository to trigger * @return The response. Ok if it worked. Otherwise, an error. */ @POST @Path(value = "triggervcs") public Response triggervcs(@Context final Repository repository, @QueryParam("vcs") final String vcs, @QueryParam("url") final String sha1, @QueryParam("username") final String username, @QueryParam("password") final String password) { try { return Response.noContent().build(); } catch (final Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } }
Example #20
Source File: TeamctiyRest.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
/** * Trigger a build on the Teamcity instance using vcs root * * @param repository The repository to trigger * @return The response. Ok if it worked. Otherwise, an error. */ @GET @Path(value = "build") public String getbuild(@Context final Repository repository, @QueryParam("id") final String id) { final Optional<Settings> settings = this.settingsService.getSettings(repository); if (!settings.isPresent()) { return "{\"status\": \"error\", \"message\": \"hook not configured\"}"; } final String url = settings.get().getString("teamCityUrl", ""); final String username = settings.get().getString("teamCityUserName", ""); final String password = this.connectionSettings.getPassword(repository); if (url.isEmpty()) { return "{\"status\": \"error\", \"message\": \"invalid id\"}"; } if (password.isEmpty()) { return "{\"status\": \"error\", \"message\": \"password is empty\"}"; } final TeamcityConfiguration conf = new TeamcityConfiguration(url, username, password); try { return this.connector.GetBuild(conf, id, settings.get()); } catch (final IOException ex) { return "{\"status\": \"error\", \"message\": \"" + ex.getMessage() + "\"}"; } }
Example #21
Source File: TeamctiyRest.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
/** * Trigger a build on the Teamcity instance using vcs root * * @param repository - {@link Repository} * @param url - url to TeamCity server * @param username - TeamCity user name * @param password - TeamCity user password * @return "OK" if it worked. Otherwise, an error message. */ @GET @Path(value = "testconnection") @Produces("text/plain; charset=UTF-8") public Response testconnection( @Context final Repository repository, @QueryParam("url") final String url, @QueryParam("username") final String username, @QueryParam("password") final String password, @QueryParam("debugon") final String isDebugOn) { String realPasswordValue = password; if (Constant.TEAMCITY_PASSWORD_SAVED_VALUE.equals(realPasswordValue)) { realPasswordValue = this.connectionSettings.getPassword(repository); } final Client restClient = Client.create(Constant.REST_CLIENT_CONFIG); restClient.addFilter(new HTTPBasicAuthFilter(username, realPasswordValue)); try { final ClientResponse response = restClient.resource(url + "/app/rest/builds?locator=lookupLimit:0").accept(MediaType.APPLICATION_XML).get(ClientResponse.class); if (ClientResponse.Status.OK == response.getClientResponseStatus()) { this.connectionSettings.savePassword(realPasswordValue, repository); return Response.ok(Constant.TEAMCITY_PASSWORD_SAVED_VALUE).build(); } else { return Response.status(response.getClientResponseStatus()).entity(response.getEntity(String.class)).build(); } } catch (final UniformInterfaceException | ClientHandlerException e) { return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } finally { restClient.destroy(); } }
Example #22
Source File: TeamcityConnectionSettings.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
/** * Retrieves TeamCity password for specified repository * * @param repository - {@link Repository} * @return password */ public String getPassword(final Repository repository) { final Object passwordObj = this.pluginSettings.get(createKey(repository)); if (null == passwordObj) { return StringUtils.EMPTY; } else { return passwordObj.toString(); } }
Example #23
Source File: MirrorBucketProcessor.java From stash-hook-mirror with MIT License | 5 votes |
@Override public void process(@Nonnull String key, @Nonnull List<MirrorRequest> requests) { if (requests.isEmpty()) { return; } // Every request is for the same mirror URL, and the same repository ID. In case the // settings (e.g. username/password) have been changed since the first request was // queued, we process the _last_ request in the list. Since mirroring pushes all of // the configured refspecs, any single request should roll up changes from any number // of requests MirrorRequest request = requests.get(requests.size() - 1); securityService.withPermission(Permission.REPO_READ, "Mirror changes") .call(() -> { Repository repository = repositoryService.getById(request.getRepositoryId()); if (repository == null) { log.debug("{}: Repository has been deleted", request.getRepositoryId()); return null; } if (repositoryService.isEmpty(repository)) { log.debug("{}: The repository is empty", repository); return null; } runMirrorCommand(request.getSettings(), repository); return null; }); }
Example #24
Source File: TeamctiyRest.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
@GET @Path(value = "loadcss") @Produces("text/css") public String loadcss(@Context final Repository repository, @QueryParam("page") final String page) { final ClassLoader classloader = Thread.currentThread().getContextClassLoader(); final InputStream is = classloader.getResourceAsStream("public/" + page); final String file = convertStreamToString(is); return file; }
Example #25
Source File: TeamctiyRest.java From TeamcityTriggerHook with GNU Lesser General Public License v3.0 | 5 votes |
/** * Trigger a build on the Teamcity instance using vcs root * * @param repository The repository to trigger * @return The response. Ok if it worked. Otherwise, an error. */ @GET @Path(value = "loadhtml") @Produces(MediaType.TEXT_HTML) public String loadhtml(@Context final Repository repository, @QueryParam("page") final String page) { final ClassLoader classloader = Thread.currentThread().getContextClassLoader(); final InputStream is = classloader.getResourceAsStream("public/" + page); final String file = convertStreamToString(is); return file; }
Example #26
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 #27
Source File: FileNameHook.java From stash-filehooks-plugin with Apache License 2.0 | 5 votes |
@Override public boolean onReceive(@Nonnull RepositoryHookContext context, @Nonnull Collection<RefChange> refChanges, @Nonnull HookResponse hookResponse) { Repository repository = context.getRepository(); FileNameHookSetting setting = getSettings(context.getSettings()); Optional<Pattern> branchesPattern = setting.getBranchesPattern(); Collection<RefChange> filteredRefChanges = refChanges.stream().filter(isNotDeleteRefChange).filter(isNotTagRefChange).collect(Collectors.toList()); if(branchesPattern.isPresent()) { filteredRefChanges = filteredRefChanges.stream().filter(matchesBranchPattern(branchesPattern.get())).collect(Collectors.toList()); } Iterable<Change> changes = changesetService.getChanges(filteredRefChanges, repository); Collection<String> filteredPaths = StreamSupport.stream(changes.spliterator(), false).filter(isNotDeleteChange).map(Functions.CHANGE_TO_PATH).filter(setting.getIncludePattern().asPredicate()).collect(Collectors.toList()); if(setting.getExcludePattern().isPresent()) { Pattern excludePattern = setting.getExcludePattern().get(); filteredPaths = filteredPaths.stream().filter(excludePattern.asPredicate().negate()).collect(Collectors.toList()); } if (filteredPaths.size() > 0) { hookResponse.out().println("================================="); for (String path : filteredPaths) { String msg; if(branchesPattern.isPresent()) { msg = String.format("File [%s] violates file name pattern [%s] for branch [%s].", path, setting.getIncludePattern().pattern(), branchesPattern.get()); } else { msg = String.format("File [%s] violates file name pattern [%s].", path, setting.getIncludePattern().pattern()); } hookResponse.out().println(msg); } hookResponse.out().println("================================="); return false; } return true; }
Example #28
Source File: FileSizeHook.java From stash-filehooks-plugin with Apache License 2.0 | 5 votes |
private Map<String, Long> getSizeForContentIds(final Repository repository, Iterable<String> contentIds) { CatFileBatchCheckHandler handler = new CatFileBatchCheckHandler(contentIds); Command<Map<String, Long>> cmd = commandFactory.builder(repository) .command("cat-file") .argument("--batch-check") .inputHandler(handler) .build(handler); return filterOutNullSizes(cmd.call()); }
Example #29
Source File: ChangesetServiceImpl.java From stash-filehooks-plugin with Apache License 2.0 | 5 votes |
@Override public Iterable<Change> getChanges(Iterable<RefChange> refChanges, final Repository repository) { List<Change> changes = new ArrayList<>(); Iterable<Commit> commits = getCommitsBetween(repository, refChanges); for (Iterable<Change> values : getChanges(repository, commits).values()) { Iterables.addAll(changes, values); } return changes; }
Example #30
Source File: MirrorRepositoryHookTest.java From stash-hook-mirror with MIT License | 5 votes |
@Test public void testPostUpdateForHgRepository() { Repository repo = mock(Repository.class); when(repo.getScmId()).thenReturn("hg"); hook.postUpdate(buildContext(), new RepositoryPushHookRequest.Builder(repo).build()); verifyZeroInteractions(bucketedExecutor); }