List of usage examples for org.eclipse.jgit.transport ReceivePack getRepository
public Repository getRepository()
From source file:com.gitblit.git.GitblitReceivePack.java
License:Apache License
/** * Instrumentation point where the incoming push event has been parsed, * validated, objects created BUT refs have not been updated. You might * use this to enforce a branch-write permissions model. */// w w w.j a v a2s . c o m @Override public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (commands.size() == 0) { // no receive commands to process // this can happen if receive pack subclasses intercept and filter // the commands LOGGER.debug("skipping pre-receive processing, no refs created, updated, or removed"); return; } if (repository.isMirror) { // repository is a mirror for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is a mirror!", repository.name); } return; } if (repository.isFrozen) { // repository is frozen/readonly for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name); } return; } if (!repository.isBare) { // repository has a working copy for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name); } return; } if (!canPush(commands)) { // user does not have push permissions for (ReceiveCommand cmd : commands) { sendRejection(cmd, "User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name); } return; } if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) { // enforce committer verification if (StringUtils.isEmpty(user.emailAddress)) { // reject the push because the pushing account does not have an email address for (ReceiveCommand cmd : commands) { sendRejection(cmd, "Sorry, the account \"{0}\" does not have an email address set for committer verification!", user.username); } return; } // Optionally enforce that the committer of first parent chain // match the account being used to push the commits. // // This requires all merge commits are executed with the "--no-ff" // option to force a merge commit even if fast-forward is possible. // This ensures that the chain first parents has the commit // identity of the merging user. boolean allRejected = false; for (ReceiveCommand cmd : commands) { String firstParent = null; try { List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name()); for (RevCommit commit : commits) { if (firstParent != null) { if (!commit.getName().equals(firstParent)) { // ignore: commit is right-descendant of a merge continue; } } // update expected next commit id if (commit.getParentCount() == 0) { firstParent = null; } else { firstParent = commit.getParents()[0].getId().getName(); } PersonIdent committer = commit.getCommitterIdent(); if (!user.is(committer.getName(), committer.getEmailAddress())) { // verification failed String reason = MessageFormat.format( "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress); LOGGER.warn(reason); cmd.setResult(Result.REJECTED_OTHER_REASON, reason); allRejected &= true; break; } else { allRejected = false; } } } catch (Exception e) { LOGGER.error("Failed to verify commits were made by pushing user", e); } } if (allRejected) { // all ref updates rejected, abort return; } } for (ReceiveCommand cmd : commands) { String ref = cmd.getRefName(); if (ref.startsWith(Constants.R_HEADS)) { switch (cmd.getType()) { case UPDATE_NONFASTFORWARD: case DELETE: // reset branch commit cache on REWIND and DELETE CommitCache.instance().clear(repository.name, ref); break; default: break; } } else if (ref.equals(BranchTicketService.BRANCH)) { // ensure pushing user is an administrator OR an owner // i.e. prevent ticket tampering boolean permitted = user.canAdmin() || repository.isOwner(user.username); if (!permitted) { sendRejection(cmd, "{0} is not permitted to push to {1}", user.username, ref); } } else if (ref.startsWith(Constants.R_FOR)) { // prevent accidental push to refs/for sendRejection(cmd, "{0} is not configured to receive patchsets", repository.name); } } // call pre-receive plugins for (ReceiveHook hook : gitblit.getExtensions(ReceiveHook.class)) { try { hook.onPreReceive(this, commands); } catch (Exception e) { LOGGER.error("Failed to execute extension", e); } } Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(gitblit.getPreReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) { scripts.addAll(repository.preReceiveScripts); } runGroovy(commands, scripts); for (ReceiveCommand cmd : commands) { if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) { LOGGER.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(), cmd.getResult(), cmd.getMessage())); } } }
From source file:com.gitblit.git.GitblitReceivePack.java
License:Apache License
/** * Instrumentation point where the incoming push has been applied to the * repository. This is the point where we would trigger a Jenkins build * or send an email./*from w w w . j a va 2 s.com*/ */ @Override public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (commands.size() == 0) { LOGGER.debug("skipping post-receive processing, no refs created, updated, or removed"); return; } logRefChange(commands); updateIncrementalPushTags(commands); updateGitblitRefLog(commands); // check for updates pushed to the BranchTicketService branch // if the BranchTicketService is active it will reindex, as appropriate for (ReceiveCommand cmd : commands) { if (Result.OK.equals(cmd.getResult()) && BranchTicketService.BRANCH.equals(cmd.getRefName())) { rp.getRepository().fireEvent(new ReceiveCommandEvent(repository, cmd)); } } // call post-receive plugins for (ReceiveHook hook : gitblit.getExtensions(ReceiveHook.class)) { try { hook.onPostReceive(this, commands); } catch (Exception e) { LOGGER.error("Failed to execute extension", e); } } // run Groovy hook scripts Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(gitblit.getPostReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.postReceiveScripts)) { scripts.addAll(repository.postReceiveScripts); } runGroovy(commands, scripts); }
From source file:com.gitblit.git.ReceiveHook.java
License:Apache License
/** * Instrumentation point where the incoming push event has been parsed, * validated, objects created BUT refs have not been updated. You might * use this to enforce a branch-write permissions model. *///from w w w. j av a2 s . c o m @Override public void onPreReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (repository.isFrozen) { // repository is frozen/readonly String reason = MessageFormat.format("Gitblit does not allow pushes to \"{0}\" because it is frozen!", repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (!repository.isBare) { // repository has a working copy String reason = MessageFormat.format( "Gitblit does not allow pushes to \"{0}\" because it has a working copy!", repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (!user.canPush(repository)) { // user does not have push permissions String reason = MessageFormat.format("User \"{0}\" does not have push permissions for \"{1}\"!", user.username, repository.name); logger.warn(reason); for (ReceiveCommand cmd : commands) { cmd.setResult(Result.REJECTED_OTHER_REASON, reason); } return; } if (repository.accessRestriction.atLeast(AccessRestrictionType.PUSH) && repository.verifyCommitter) { // enforce committer verification if (StringUtils.isEmpty(user.emailAddress)) { // emit warning if user does not have an email address logger.warn(MessageFormat.format( "Consider setting an email address for {0} ({1}) to improve committer verification.", user.getDisplayName(), user.username)); } // Optionally enforce that the committer of the left parent chain // match the account being used to push the commits. // // This requires all merge commits are executed with the "--no-ff" // option to force a merge commit even if fast-forward is possible. // This ensures that the chain of left parents has the commit // identity of the merging user. boolean allRejected = false; for (ReceiveCommand cmd : commands) { String linearParent = null; try { List<RevCommit> commits = JGitUtils.getRevLog(rp.getRepository(), cmd.getOldId().name(), cmd.getNewId().name()); for (RevCommit commit : commits) { if (linearParent != null) { if (!commit.getName().equals(linearParent)) { // ignore: commit is right-descendant of a merge continue; } } // update expected next commit id if (commit.getParentCount() == 0) { linearParent = null; } else { linearParent = commit.getParents()[0].getId().getName(); } PersonIdent committer = commit.getCommitterIdent(); if (!user.is(committer.getName(), committer.getEmailAddress())) { String reason; if (StringUtils.isEmpty(user.emailAddress)) { // account does not have an email address reason = MessageFormat.format("{0} by {1} <{2}> was not committed by {3} ({4})", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username); } else { // account has an email address reason = MessageFormat.format( "{0} by {1} <{2}> was not committed by {3} ({4}) <{5}>", commit.getId().name(), committer.getName(), StringUtils.isEmpty(committer.getEmailAddress()) ? "?" : committer.getEmailAddress(), user.getDisplayName(), user.username, user.emailAddress); } logger.warn(reason); cmd.setResult(Result.REJECTED_OTHER_REASON, reason); allRejected &= true; break; } else { allRejected = false; } } } catch (Exception e) { logger.error("Failed to verify commits were made by pushing user", e); } } if (allRejected) { // all ref updates rejected, abort return; } } // reset branch commit cache on REWIND and DELETE for (ReceiveCommand cmd : commands) { String ref = cmd.getRefName(); if (ref.startsWith(Constants.R_HEADS)) { switch (cmd.getType()) { case UPDATE_NONFASTFORWARD: case DELETE: CommitCache.instance().clear(repository.name, ref); break; default: break; } } } Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(GitBlit.self().getPreReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.preReceiveScripts)) { scripts.addAll(repository.preReceiveScripts); } runGroovy(repository, user, commands, rp, scripts); for (ReceiveCommand cmd : commands) { if (!Result.NOT_ATTEMPTED.equals(cmd.getResult())) { logger.warn(MessageFormat.format("{0} {1} because \"{2}\"", cmd.getNewId().getName(), cmd.getResult(), cmd.getMessage())); } } }
From source file:com.gitblit.git.ReceiveHook.java
License:Apache License
/** * Instrumentation point where the incoming push has been applied to the * repository. This is the point where we would trigger a Jenkins build * or send an email./* ww w . j a v a 2s . com*/ */ @Override public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { if (commands.size() == 0) { logger.debug("skipping post-receive hooks, no refs created, updated, or removed"); return; } // log ref changes for (ReceiveCommand cmd : commands) { if (Result.OK.equals(cmd.getResult())) { // add some logging for important ref changes switch (cmd.getType()) { case DELETE: logger.info(MessageFormat.format("{0} DELETED {1} in {2} ({3})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name())); break; case CREATE: logger.info(MessageFormat.format("{0} CREATED {1} in {2}", user.username, cmd.getRefName(), repository.name)); break; case UPDATE: logger.info(MessageFormat.format("{0} UPDATED {1} in {2} (from {3} to {4})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name(), cmd.getNewId().name())); break; case UPDATE_NONFASTFORWARD: logger.info(MessageFormat.format("{0} UPDATED NON-FAST-FORWARD {1} in {2} (from {3} to {4})", user.username, cmd.getRefName(), repository.name, cmd.getOldId().name(), cmd.getNewId().name())); break; default: break; } } } if (repository.useIncrementalPushTags) { // tag each pushed branch tip String emailAddress = user.emailAddress == null ? rp.getRefLogIdent().getEmailAddress() : user.emailAddress; PersonIdent userIdent = new PersonIdent(user.getDisplayName(), emailAddress); for (ReceiveCommand cmd : commands) { if (!cmd.getRefName().startsWith("refs/heads/")) { // only tag branch ref changes continue; } if (!ReceiveCommand.Type.DELETE.equals(cmd.getType()) && ReceiveCommand.Result.OK.equals(cmd.getResult())) { String objectId = cmd.getNewId().getName(); String branch = cmd.getRefName().substring("refs/heads/".length()); // get translation based on the server's locale setting String template = Translation.get("gb.incrementalPushTagMessage"); String msg = MessageFormat.format(template, branch); String prefix; if (StringUtils.isEmpty(repository.incrementalPushTagPrefix)) { prefix = GitBlit.getString(Keys.git.defaultIncrementalPushTagPrefix, "r"); } else { prefix = repository.incrementalPushTagPrefix; } JGitUtils.createIncrementalRevisionTag(rp.getRepository(), objectId, userIdent, prefix, "0", msg); } } } // update push log try { RefLogUtils.updateRefLog(user, rp.getRepository(), commands); logger.debug(MessageFormat.format("{0} push log updated", repository.name)); } catch (Exception e) { logger.error(MessageFormat.format("Failed to update {0} pushlog", repository.name), e); } // run Groovy hook scripts Set<String> scripts = new LinkedHashSet<String>(); scripts.addAll(GitBlit.self().getPostReceiveScriptsInherited(repository)); if (!ArrayUtils.isEmpty(repository.postReceiveScripts)) { scripts.addAll(repository.postReceiveScripts); } runGroovy(repository, user, commands, rp, scripts); }
From source file:com.google.gerrit.sshd.commands.Receive.java
License:Apache License
@Override protected void runImpl() throws IOException, Failure { if (!projectControl.canRunReceivePack()) { throw new Failure(1, "fatal: receive-pack not permitted on this server"); }/*ww w .ja v a 2s . c o m*/ final ReceiveCommits receive = factory.create(projectControl, repo).getReceiveCommits(); Capable r = receive.canUpload(); if (r != Capable.OK) { throw new UnloggedFailure(1, "\nfatal: " + r.getMessage()); } verifyProjectVisible("reviewer", reviewerId); verifyProjectVisible("CC", ccId); receive.addReviewers(reviewerId); receive.addExtraCC(ccId); final ReceivePack rp = receive.getReceivePack(); rp.setRefLogIdent(currentUser.newRefLogIdent()); rp.setTimeout(config.getTimeout()); rp.setMaxObjectSizeLimit(config.getEffectiveMaxObjectSizeLimit(projectControl.getProjectState())); init(rp); rp.setPostReceiveHook(PostReceiveHookChain.newChain(Lists.newArrayList(postReceiveHooks))); try { rp.receive(in, out, err); } catch (UnpackException badStream) { // In case this was caused by the user pushing an object whose size // is larger than the receive.maxObjectSizeLimit gerrit.config parameter // we want to present this error to the user if (badStream.getCause() instanceof TooLargeObjectInPackException) { StringBuilder msg = new StringBuilder(); msg.append("Receive error on project \"").append(projectControl.getProject().getName()) .append("\""); msg.append(" (user "); msg.append(currentUser.getAccount().getUserName()); msg.append(" account "); msg.append(currentUser.getAccountId()); msg.append("): "); msg.append(badStream.getCause().getMessage()); log.info(msg.toString()); throw new UnloggedFailure(128, "error: " + badStream.getCause().getMessage()); } // This may have been triggered by branch level access controls. // Log what the heck is going on, as detailed as we can. // StringBuilder msg = new StringBuilder(); msg.append("Unpack error on project \"").append(projectControl.getProject().getName()).append("\":\n"); msg.append(" AdvertiseRefsHook: ").append(rp.getAdvertiseRefsHook()); if (rp.getAdvertiseRefsHook() == AdvertiseRefsHook.DEFAULT) { msg.append("DEFAULT"); } else if (rp.getAdvertiseRefsHook() instanceof VisibleRefFilter) { msg.append("VisibleRefFilter"); } else { msg.append(rp.getAdvertiseRefsHook().getClass()); } msg.append("\n"); if (rp.getAdvertiseRefsHook() instanceof VisibleRefFilter) { Map<String, Ref> adv = rp.getAdvertisedRefs(); msg.append(" Visible references (").append(adv.size()).append("):\n"); for (Ref ref : adv.values()) { msg.append(" - ").append(ref.getObjectId().abbreviate(8).name()).append(" ") .append(ref.getName()).append("\n"); } Map<String, Ref> allRefs = rp.getRepository().getRefDatabase().getRefs(RefDatabase.ALL); List<Ref> hidden = new ArrayList<>(); for (Ref ref : allRefs.values()) { if (!adv.containsKey(ref.getName())) { hidden.add(ref); } } msg.append(" Hidden references (").append(hidden.size()).append("):\n"); for (Ref ref : hidden) { msg.append(" - ").append(ref.getObjectId().abbreviate(8).name()).append(" ") .append(ref.getName()).append("\n"); } } IOException detail = new IOException(msg.toString(), badStream); throw new Failure(128, "fatal: Unpack error, check server log", detail); } }
From source file:com.googlesource.gerrit.plugins.quota.MaxRepositorySizeQuota.java
License:Apache License
@Override public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { Project.NameKey project = projectNameResolver.projectName(rp.getRepository()); if (needPack(commands)) { try {/*w w w . ja v a 2 s . com*/ cache.get(project).getAndAdd(rp.getPackSize()); } catch (ExecutionException e) { log.warn("Couldn't process onPostReceive for " + project.get(), e); } } }
From source file:com.tasktop.c2c.server.scm.service.EventGeneratingPostRecieveHook.java
License:Open Source License
@Override public void onPostReceive(ReceivePack rp, Collection<ReceiveCommand> commands) { for (ReceiveCommand command : commands) { switch (command.getType()) { case CREATE: case UPDATE: sendCommits(rp.getRepository(), command.getRefName(), command.getOldId(), command.getNewId()); break; // TODO handle other cases }/*from w w w .j av a 2 s . com*/ } }