List of usage examples for org.eclipse.jgit.revwalk RevWalk setRevFilter
public void setRevFilter(RevFilter newFilter)
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Returns a list of commits since the minimum date starting from the * specified object id.//from ww w .ja va 2 s.co m * * @param repository * @param objectId * if unspecified, HEAD is assumed. * @param minimumDate * @return list of commits */ public static List<RevCommit> getRevLog(Repository repository, String objectId, Date minimumDate) { List<RevCommit> list = new ArrayList<RevCommit>(); if (!hasCommits(repository)) { return list; } try { // resolve branch ObjectId branchObject; if (StringUtils.isEmpty(objectId)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(objectId); } RevWalk rw = new RevWalk(repository); rw.markStart(rw.parseCommit(branchObject)); rw.setRevFilter(CommitTimeRevFilter.after(minimumDate)); Iterable<RevCommit> revlog = rw; for (RevCommit rev : revlog) { list.add(rev); } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to get {1} revlog for minimum date {2}", objectId, minimumDate); } return list; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Search the commit history for a case-insensitive match to the value. * Search results require a specified SearchType of AUTHOR, COMMITTER, or * COMMIT. Results may be paginated using offset and maxCount. If the * repository does not exist or is empty, an empty list is returned. * * @param repository// w ww. j a v a 2 s. c o m * @param objectId * if unspecified, HEAD is assumed. * @param value * @param type * AUTHOR, COMMITTER, COMMIT * @param offset * @param maxCount * if < 0, all matches are returned * @return matching list of commits */ public static List<RevCommit> searchRevlogs(Repository repository, String objectId, String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) { List<RevCommit> list = new ArrayList<RevCommit>(); if (StringUtils.isEmpty(value)) { return list; } if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } final String lcValue = value.toLowerCase(); try { // resolve branch ObjectId branchObject; if (StringUtils.isEmpty(objectId)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(objectId); } RevWalk rw = new RevWalk(repository); rw.setRevFilter(new RevFilter() { @Override public RevFilter clone() { // FindBugs complains about this method name. // This is part of JGit design and unrelated to Cloneable. return this; } @Override public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException { boolean include = false; switch (type) { case AUTHOR: include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getAuthorIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1); break; case COMMITTER: include = (commit.getCommitterIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getCommitterIdent().getEmailAddress().toLowerCase() .indexOf(lcValue) > -1); break; case COMMIT: include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1; break; } return include; } }); rw.markStart(rw.parseCommit(branchObject)); Iterable<RevCommit> revlog = rw; if (offset > 0) { int count = 0; for (RevCommit rev : revlog) { count++; if (count > offset) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } } else { for (RevCommit rev : revlog) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value); } return list; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Returns the merge base of two commits or null if there is no common * ancestry.//from www .j a v a2 s .c o m * * @param repository * @param commitIdA * @param commitIdB * @return the commit id of the merge base or null if there is no common base */ public static String getMergeBase(Repository repository, ObjectId commitIdA, ObjectId commitIdB) { RevWalk rw = new RevWalk(repository); try { RevCommit a = rw.lookupCommit(commitIdA); RevCommit b = rw.lookupCommit(commitIdB); rw.setRevFilter(RevFilter.MERGE_BASE); rw.markStart(a); rw.markStart(b); RevCommit mergeBase = rw.next(); if (mergeBase == null) { return null; } return mergeBase.getName(); } catch (Exception e) { LOGGER.error("Failed to determine merge base", e); } finally { rw.dispose(); } return null; }
From source file:com.github.checkstyle.regression.git.DiffParser.java
License:Open Source License
/** * Gets the merge-base of two commits.// ww w . j av a 2 s. c o m * A merge-base is a best common ancestor between two commits. One common ancestor is * better than another common ancestor if the latter is an ancestor of the former. * A common ancestor that does not have any better common ancestor is a best common ancestor. * @param walk the {@link RevWalk} for computing merge bases * @param commitA the first commit to start the walk with * @param commitB the second commit to start the walk with * @return the merge-base of two commits * @throws IOException JGit library exception */ private static RevCommit getMergeBaseCommit(RevWalk walk, RevCommit commitA, RevCommit commitB) throws IOException { walk.reset(); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(commitA); walk.markStart(commitB); return walk.next(); }
From source file:com.google.appraise.eclipse.core.client.git.AppraiseGitReviewClient.java
License:Open Source License
/** * Gets the merge base for the two given commits. * Danger -- the commits need to be from the given RevWalk or this will * fail in a not-completely-obvious way. *//*from w ww.j av a 2 s .co m*/ private RevCommit getMergeBase(RevWalk walk, RevCommit commit1, RevCommit commit2) throws GitClientException { try { walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(commit1); walk.markStart(commit2); return walk.next(); } catch (Exception e) { throw new GitClientException("Failed to get merge base commit for " + commit1 + " and " + commit2, e); } }
From source file:com.google.gerrit.server.git.ReceiveCommits.java
License:Apache License
private void parseMagicBranch(final ReceiveCommand cmd) { // Permit exactly one new change request per push. if (magicBranch != null) { reject(cmd, "duplicate request"); return;/*from ww w. j a va 2 s. c o m*/ } magicBranch = new MagicBranchInput(cmd, labelTypes, notesMigration); magicBranch.reviewer.addAll(reviewersFromCommandLine); magicBranch.cc.addAll(ccFromCommandLine); String ref; CmdLineParser clp = optionParserFactory.create(magicBranch); magicBranch.clp = clp; try { ref = magicBranch.parse(clp, repo, rp.getAdvertisedRefs().keySet()); } catch (CmdLineException e) { if (!clp.wasHelpRequestedByOption()) { reject(cmd, e.getMessage()); return; } ref = null; // never happen } if (clp.wasHelpRequestedByOption()) { StringWriter w = new StringWriter(); w.write("\nHelp for refs/for/branch:\n\n"); clp.printUsage(w, null); addMessage(w.toString()); reject(cmd, "see help"); return; } if (!rp.getAdvertisedRefs().containsKey(ref) && !ref.equals(readHEAD(repo))) { if (ref.startsWith(Constants.R_HEADS)) { String n = ref.substring(Constants.R_HEADS.length()); reject(cmd, "branch " + n + " not found"); } else { reject(cmd, ref + " not found"); } return; } magicBranch.dest = new Branch.NameKey(project.getNameKey(), ref); magicBranch.ctl = projectControl.controlForRef(ref); if (!magicBranch.ctl.canWrite()) { reject(cmd, "project is read only"); return; } if (magicBranch.draft) { if (!receiveConfig.allowDrafts) { errors.put(Error.CODE_REVIEW, ref); reject(cmd, "draft workflow is disabled"); return; } else if (projectControl.controlForRef("refs/drafts/" + ref).isBlocked(Permission.PUSH)) { errors.put(Error.CODE_REVIEW, ref); reject(cmd, "cannot upload drafts"); return; } } if (!magicBranch.ctl.canUpload()) { errors.put(Error.CODE_REVIEW, ref); reject(cmd, "cannot upload review"); return; } if (magicBranch.draft && magicBranch.submit) { reject(cmd, "cannot submit draft"); return; } if (magicBranch.submit && !projectControl.controlForRef(MagicBranch.NEW_CHANGE + ref).canSubmit()) { reject(cmd, "submit not allowed"); return; } RevWalk walk = rp.getRevWalk(); RevCommit tip; try { tip = walk.parseCommit(magicBranch.cmd.getNewId()); } catch (IOException ex) { magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT); log.error("Invalid pack upload; one or more objects weren't sent", ex); return; } // If tip is a merge commit, or the root commit or // if %base was specified, ignore newChangeForAllNotInTarget if (tip.getParentCount() > 1 || magicBranch.base != null || tip.getParentCount() == 0) { newChangeForAllNotInTarget = false; } if (magicBranch.base != null) { magicBranch.baseCommit = Lists.newArrayListWithCapacity(magicBranch.base.size()); for (ObjectId id : magicBranch.base) { try { magicBranch.baseCommit.add(walk.parseCommit(id)); } catch (IncorrectObjectTypeException notCommit) { reject(cmd, "base must be a commit"); return; } catch (MissingObjectException e) { reject(cmd, "base not found"); return; } catch (IOException e) { log.warn(String.format("Project %s cannot read %s", project.getName(), id.name()), e); reject(cmd, "internal server error"); return; } } } else if (newChangeForAllNotInTarget) { String destBranch = magicBranch.dest.get(); try { Ref r = repo.getRefDatabase().exactRef(destBranch); if (r == null) { reject(cmd, destBranch + " not found"); return; } ObjectId baseHead = r.getObjectId(); magicBranch.baseCommit = Collections.singletonList(walk.parseCommit(baseHead)); } catch (IOException ex) { log.warn(String.format("Project %s cannot read %s", project.getName(), destBranch), ex); reject(cmd, "internal server error"); return; } } // Validate that the new commits are connected with the target // branch. If they aren't, we want to abort. We do this check by // looking to see if we can compute a merge base between the new // commits and the target branch head. // try { Ref targetRef = rp.getAdvertisedRefs().get(magicBranch.ctl.getRefName()); if (targetRef == null || targetRef.getObjectId() == null) { // The destination branch does not yet exist. Assume the // history being sent for review will start it and thus // is "connected" to the branch. return; } final RevCommit h = walk.parseCommit(targetRef.getObjectId()); final RevFilter oldRevFilter = walk.getRevFilter(); try { walk.reset(); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(tip); walk.markStart(h); if (walk.next() == null) { reject(magicBranch.cmd, "no common ancestry"); } } finally { walk.reset(); walk.setRevFilter(oldRevFilter); } } catch (IOException e) { magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT); log.error("Invalid pack upload; one or more objects weren't sent", e); } }
From source file:com.hpe.application.automation.tools.octane.model.processors.scm.GitSCMProcessor.java
License:Open Source License
@Override public CommonOriginRevision getCommonOriginRevision(final Run run) { //for phase 1 this is hard coded since its not possible to calculate it, and configuration from outside will complicate the feature //so for this phase we keep it hardcoded. CommonOriginRevision commonOriginRevision = new CommonOriginRevision(); try {// w ww . j a v a 2s . c om final AbstractBuild abstractBuild = (AbstractBuild) run; FilePath workspace = ((AbstractBuild) run).getWorkspace(); if (workspace != null) { commonOriginRevision = workspace.act(new FilePath.FileCallable<CommonOriginRevision>() { @Override public CommonOriginRevision invoke(File file, VirtualChannel channel) throws IOException, InterruptedException { CommonOriginRevision result = new CommonOriginRevision(); File repoDir = new File(getRemoteString(abstractBuild) + File.separator + ".git"); Git git = Git.open(repoDir); Repository repo = git.getRepository(); final RevWalk walk = new RevWalk(repo); ObjectId resolveForCurrentBranch = repo.resolve(Constants.HEAD); RevCommit currentBranchCommit = walk.parseCommit(resolveForCurrentBranch); ObjectId resolveForMaster = repo.resolve(MASTER); RevCommit masterCommit = walk.parseCommit(resolveForMaster); walk.reset(); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(currentBranchCommit); walk.markStart(masterCommit); final RevCommit base = walk.next(); if (base == null) return result; final RevCommit base2 = walk.next(); if (base2 != null) { throw new NoMergeBaseException( NoMergeBaseException.MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED, MessageFormat.format(JGitText.get().multipleMergeBasesFor, currentBranchCommit.name(), masterCommit.name(), base.name(), base2.name())); } result.revision = base.getId().getName(); result.branch = getBranchName(run); return result; } @Override public void checkRoles(RoleChecker roleChecker) throws SecurityException { if (roleChecker != null) { logger.info("Note : roleChecker is not empty, but no action was taken"); } } }); } logger.info("most recent common revision resolved to " + commonOriginRevision.revision + " (branch: " + commonOriginRevision.branch + ")"); } catch (Exception e) { logger.error("failed to resolve most recent common revision", e); return commonOriginRevision; } return commonOriginRevision; }
From source file:com.mycila.maven.plugin.license.git.GitLookup.java
License:Apache License
/** * Returns the year of the last change of the given {@code file} based on the history of the present git branch. The * year is taken either from the committer date or from the author identity depending on how {@link #dateSource} was * initialized./*from w ww. j a v a 2 s. co m*/ * <p> * See also the note on time zones in {@link #GitLookup(File, DateSource, TimeZone, int)}. * * @param file * @return * @throws NoHeadException * @throws GitAPIException * @throws IOException */ public int getYearOfLastChange(File file) throws NoHeadException, GitAPIException, IOException { String repoRelativePath = pathResolver.relativize(file); Status status = new Git(repository).status().addPath(repoRelativePath).call(); if (!status.isClean()) { /* Return the current year for modified and unstaged files */ return toYear(System.currentTimeMillis(), timeZone != null ? timeZone : DEFAULT_ZONE); } RevWalk walk = new RevWalk(repository); walk.markStart(walk.parseCommit(repository.resolve(Constants.HEAD))); walk.setTreeFilter(AndTreeFilter.create(PathFilter.create(repoRelativePath), TreeFilter.ANY_DIFF)); walk.setRevFilter(MaxCountRevFilter.create(checkCommitsCount)); walk.setRetainBody(false); int commitYear = 0; for (RevCommit commit : walk) { int y; switch (dateSource) { case COMMITER: int epochSeconds = commit.getCommitTime(); y = toYear(epochSeconds * 1000L, timeZone); break; case AUTHOR: PersonIdent id = commit.getAuthorIdent(); Date date = id.getWhen(); y = toYear(date.getTime(), id.getTimeZone()); break; default: throw new IllegalStateException("Unexpected " + DateSource.class.getName() + " " + dateSource); } if (y > commitYear) { commitYear = y; } } walk.dispose(); return commitYear; }
From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java
License:Open Source License
public static List<Commit> getLog(Repository r, String revision, String path, Region region) throws IOException { if (path.startsWith("/")) { path = path.substring(1);// w ww. j a v a 2 s. c om } List<Commit> commits = new ArrayList<Commit>(); ObjectId revId = r.resolve(revision); RevWalk walk = new RevWalk(r); walk.markStart(walk.parseCommit(revId)); if (path != null && path.trim().length() != 0) { walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.createFromStrings(path), TreeFilter.ANY_DIFF)); } if (region != null) { // if (region.getOffset() > 0 && region.getSize() > 0) // walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(region.getOffset()), // MaxCountRevFilter.create(region.getSize()))); /* else */if (region.getOffset() > 0) { walk.setRevFilter(SkipRevFilter.create(region.getOffset())); } // else if (region.getSize() > 0) { // walk.setRevFilter(MaxCountRevFilter.create(region.getSize())); // } } int max = region != null && region.getSize() > 0 ? region.getSize() : -1; for (RevCommit revCommit : walk) { Commit commit = GitDomain.createCommit(revCommit); commit.setRepository(r.getDirectory().getName()); commits.add(commit); if (max != -1) { if (max == 0) { break; } max--; } } return commits; }
From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java
License:Open Source License
protected static RevCommit getBaseCommit(RevWalk walk, RevCommit a, RevCommit b) throws IncorrectObjectTypeException, IOException { walk.reset();//ww w . j a v a 2 s . co m walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(a); walk.markStart(b); final RevCommit base = walk.next(); if (base == null) return null; final RevCommit base2 = walk.next(); if (base2 != null) { // throw new NoMergeBaseException(MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED, // MessageFormat.format(JGitText.get().multipleMergeBasesFor, a.name(), b.name(), base.name(), // base2.name())); throw new IOException(MessageFormat.format(JGitText.get().multipleMergeBasesFor, a.name(), b.name(), base.name(), base2.name())); } return base; }