List of usage examples for org.eclipse.jgit.revwalk RevWalk lookupCommit
@NonNull
public RevCommit lookupCommit(AnyObjectId id)
From source file:br.com.riselabs.cotonet.builder.NetworkBuilder.java
License:Open Source License
/** * Returns the conflicting merge scenarios * /* w w w .jav a 2 s.c o m*/ * @return - a list of merge scenarios. it may be empty in case of no * conflict. * @throws IOException */ private List<MergeScenario> getMergeScenarios() throws IOException { List<MergeScenario> result = new ArrayList<MergeScenario>(); List<RevCommit> mergeCommits = new ArrayList<RevCommit>(); Iterable<RevCommit> gitlog; try { Git git = Git.wrap(getProject().getRepository()); gitlog = git.log().call(); for (RevCommit commit : gitlog) { if (commit.getParentCount() == 2) { mergeCommits.add(commit); // collecting merge commits // we know there is only to parents RevCommit leftParent = commit.getParent(0); RevCommit rightParent = commit.getParent(1); ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(getProject().getRepository(), true); // selecting the conflicting ones boolean noConflicts = false; try { noConflicts = merger.merge(leftParent, rightParent); } catch (NoMergeBaseException e) { StringBuilder sb = new StringBuilder(); sb.append("[" + project.getName() + ":" + project.getUrl() + "] " + "Skipping merge scenario due to '" + e.getMessage() + "'\n"); sb.append("---> Skipped scenario:\n"); sb.append("::Base (<several>): \n"); sb.append("::Left (" + leftParent.getAuthorIdent().getWhen().toString() + "):" + leftParent.getName() + "\n"); sb.append("::Right (" + rightParent.getAuthorIdent().getWhen().toString() + "):" + rightParent.getName() + "\n"); Logger.log(log, sb.toString()); Logger.logStackTrace(log, e); continue; } if (noConflicts) { continue; } RevWalk walk = new RevWalk(getProject().getRepository()); // for merges without a base commit if (merger.getBaseCommitId() == null) continue; RevCommit baseCommit = walk.lookupCommit(merger.getBaseCommitId()); walk.close(); Timestamp mergeDate = new Timestamp(commit.getAuthorIdent().getWhen().getTime()); result.add(new MergeScenario(baseCommit, leftParent, rightParent, commit, mergeDate)); } } } catch (GitAPIException e) { Logger.logStackTrace(log, e); } return result; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Returns true if the commit identified by commitId is an ancestor or the * the commit identified by tipId.//ww w . jav a 2s. com * * @param repository * @param commitId * @param tipId * @return true if there is the commit is an ancestor of the tip */ public static boolean isMergedInto(Repository repository, ObjectId commitId, ObjectId tipCommitId) { // traverse the revlog looking for a commit chain between the endpoints RevWalk rw = new RevWalk(repository); try { // must re-lookup RevCommits to workaround undocumented RevWalk bug RevCommit tip = rw.lookupCommit(tipCommitId); RevCommit commit = rw.lookupCommit(commitId); return rw.isMergedInto(commit, tip); } catch (Exception e) { LOGGER.error("Failed to determine isMergedInto", e); } finally { rw.dispose(); } return false; }
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 ww w . ja v a 2 s . c om*/ * * @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.google.gerrit.acceptance.git.GitUtil.java
License:Apache License
private static ObjectId computeChangeId(Git git, PersonIdent i, String msg) throws IOException { RevWalk rw = new RevWalk(git.getRepository()); try {/*from www . jav a 2 s .c o m*/ Ref head = git.getRepository().getRef(Constants.HEAD); if (head.getObjectId() != null) { RevCommit parent = rw.lookupCommit(head.getObjectId()); return ChangeIdUtil.computeChangeId(parent.getTree(), parent.getId(), i, i, msg); } else { return ChangeIdUtil.computeChangeId(null, null, i, i, msg); } } finally { rw.release(); } }
From source file:com.google.gerrit.acceptance.git.ssh.GitUtil.java
License:Apache License
private static ObjectId computeChangeId(Git git, PersonIdent i, String msg) throws IOException { RevWalk rw = new RevWalk(git.getRepository()); try {// w w w . j a v a 2 s. c om RevCommit parent = rw.lookupCommit(git.getRepository().getRef(Constants.HEAD).getObjectId()); return ChangeIdUtil.computeChangeId(parent.getTree(), parent.getId(), i, i, msg); } finally { rw.release(); } }
From source file:com.googlesource.gerrit.plugins.github.git.PullRequestImportJob.java
License:Apache License
private List<Id> addPullRequestToChange(ReviewDb db, GHPullRequest pr, Repository gitRepo) throws Exception { String destinationBranch = pr.getBase().getRef(); List<Id> prChanges = Lists.newArrayList(); ObjectId baseObjectId = ObjectId.fromString(pr.getBase().getSha()); ObjectId prHeadObjectId = ObjectId.fromString(pr.getHead().getSha()); RevWalk walk = new RevWalk(gitRepo); walk.markUninteresting(walk.lookupCommit(baseObjectId)); walk.markStart(walk.lookupCommit(prHeadObjectId)); walk.sort(RevSort.REVERSE);// www.j a va 2 s .c o m int patchNr = 1; for (GHPullRequestCommitDetail ghCommitDetail : pr.listCommits()) { status.update(Code.SYNC, "Patch #" + patchNr, "Patch#" + patchNr + ": Inserting PullRequest into Gerrit"); RevCommit revCommit = walk.parseCommit(ObjectId.fromString(ghCommitDetail.getSha())); GHUser prUser = pr.getUser(); GitUser commitAuthor = ghCommitDetail.getCommit().getAuthor(); GitHubUser gitHubUser = GitHubUser.from(prUser, commitAuthor); Account.Id pullRequestOwner = getOrRegisterAccount(db, gitHubUser); Id changeId = createChange.addCommitToChange(db, project, gitRepo, destinationBranch, pullRequestOwner, revCommit, getChangeMessage(pr), String.format(TOPIC_FORMAT, pr.getNumber()), false); if (changeId != null) { prChanges.add(changeId); } } return prChanges; }
From source file:com.googlesrouce.gerrit.plugins.github.git.PullRequestImportJob.java
License:Apache License
private List<Id> addPullRequestToChange(ReviewDb db, GHPullRequest pr, Repository gitRepo) throws Exception { String destinationBranch = pr.getBase().getRef(); List<Id> prChanges = Lists.newArrayList(); ObjectId baseObjectId = ObjectId.fromString(pr.getBase().getSha()); ObjectId prHeadObjectId = ObjectId.fromString(pr.getHead().getSha()); RevWalk walk = new RevWalk(gitRepo); walk.markUninteresting(walk.lookupCommit(baseObjectId)); walk.markStart(walk.lookupCommit(prHeadObjectId)); walk.sort(RevSort.REVERSE);/*from w ww .j a v a2 s.c o m*/ int patchNr = 1; for (GHPullRequestCommitDetail ghCommitDetail : pr.listCommits()) { status.update(Code.SYNC, "Patch #" + patchNr, "Patch#" + patchNr + ": Inserting PullRequest into Gerrit"); RevCommit revCommit = walk.parseCommit(ObjectId.fromString(ghCommitDetail.getSha())); Account.Id pullRequestOwner; // It may happen that the user that created the Pull Request has been // removed from GitHub: we assume that the commit author was that user // as there are no other choices. if (pr.getUser() == null) { pullRequestOwner = getOrRegisterAccount(db, ghCommitDetail.getCommit().getAuthor()); } else { pullRequestOwner = getOrRegisterAccount(db, pr.getUser()); } Id changeId = createChange.addCommitToChange(db, project, gitRepo, destinationBranch, pullRequestOwner, revCommit, getChangeMessage(pr), String.format(TOPIC_FORMAT, pr.getNumber()), false); if (changeId != null) { prChanges.add(changeId); } } return prChanges; }
From source file:com.hatis.gitblit.plugin.TicketsGroovyHook.java
@Override public void onMergePatchset(TicketModel ticket) { RepositoryModel repositoryModel = gitblit.getRepositoryModel(ticket.repository); Repository repository = gitblit.getRepository(repositoryModel.name); Collection<ReceiveCommand> commands = new ArrayList<>(); Change lastMerged = null;//from w ww . j a v a 2s .com for (Change change : ticket.changes) { if (change.isMerge()) lastMerged = change; } if (lastMerged == null) { LOGGER.error("Cant find last merg change"); return; } UserModel userModel = gitblit.getUserModel(lastMerged.author); if (userModel == null) { LOGGER.error("Change author not exists"); return; } RevWalk revWalk = null; try { revWalk = new RevWalk(repository); RevCommit branchTip = revWalk.lookupCommit(repository.resolve(ticket.mergeTo)); ReceiveCommand receiveCommand = new ReceiveCommand(branchTip, branchTip, "refs/heads/" + ticket.mergeTo); commands.add(receiveCommand); } catch (IOException e) { LOGGER.error("Failed to determine merge branch", e); } finally { if (revWalk != null) { revWalk.release(); } } Set<String> scripts = new LinkedHashSet<>(); scripts.addAll(gitblit.getPostReceiveScriptsInherited(repositoryModel)); if (!ArrayUtils.isEmpty(repositoryModel.postReceiveScripts)) { scripts.addAll(repositoryModel.postReceiveScripts); } runGroovy(commands, scripts, repositoryModel, userModel); }
From source file:com.microsoft.gittf.core.util.CommitWalker.java
License:Open Source License
/** * Get the list of commit deltas that represents the commits between a * source commit and a target commit. The method skips walking parents that * are ignored.//from w w w.ja v a2s . c o m * * @param repository * the git repository * @param sourceCommitID * the source commit id * @param targetCommitID * the target commit * @param ignoreCommitIDs * the list of commits to ignore * @return * @throws Exception * throws an exception if the path between to commits is ambigous */ public static List<CommitDelta> getCommitList(final Repository repository, final ObjectId sourceCommitID, final ObjectId targetCommitID, final AbbreviatedObjectId[] ignoreCommitIDs) throws Exception { Check.notNull(repository, "repository"); //$NON-NLS-1$ Check.notNull(targetCommitID, "targetCommitID"); //$NON-NLS-1$ List<CommitDelta> commitList = new ArrayList<CommitDelta>(); RevWalk walker = new RevWalk(repository); try { final RevCommit headCommit = walker.lookupCommit(targetCommitID); walker.parseHeaders(headCommit); RevCommit currentCommit = headCommit; /* * Walk backwards from the destination commit searching for the * starting commit. */ while (currentCommit != null && !currentCommit.getId().equals(sourceCommitID)) { final RevCommit[] parents = currentCommit.getParents(); RevCommit fromCommit = null; final RevCommit toCommit = currentCommit; /* The repository's initial commit. */ if (parents == null || parents.length == 0) { /* * Sanity check: make sure we are in an unbridged * repository. */ if (sourceCommitID != null) { throw new Exception(Messages.formatString("CheckinHeadCommitTask.LatestNotInTreeFormat", //$NON-NLS-1$ ObjectIdUtil.abbreviate(repository, sourceCommitID))); } fromCommit = null; } else if (parents.length == 1) { for (AbbreviatedObjectId ignore : ignoreCommitIDs) { if (ignore.prefixCompare(parents[0].getId()) == 0) { throw new Exception(Messages.formatString( "CheckinHeadCommitTask.CommitHasOneParentThatIsSquashedFormat", //$NON-NLS-1$ ObjectIdUtil.abbreviate(repository, currentCommit), ObjectIdUtil.abbreviate(repository, parents[0].getId()))); } } fromCommit = parents[0]; walker.parseHeaders(fromCommit); } else { RevCommit possibleFrom = null; /* * See if one of the parents is our destination - if so, * we'll simply use it. (This commit is the result of a * merge with the latest changeset on the TFS server. We * won't preserve history before the merge.) */ for (RevCommit parent : currentCommit.getParents()) { if (parent.getId().equals(sourceCommitID)) { possibleFrom = parent; break; } } if (possibleFrom == null) { /* * See if all the parents but one have been squashed - * if so, we can follow the non-squashed parent for its * history. */ for (RevCommit parent : currentCommit.getParents()) { boolean parentIgnored = false; for (AbbreviatedObjectId ignore : ignoreCommitIDs) { if (ignore.prefixCompare(parent.getId()) == 0) { parentIgnored = true; break; } } /* This parent is squashed, continue */ if (parentIgnored) { continue; } /* * This is a possible (non-squashed) avenue to * follow, mark it as such and investigate other * parents. */ else if (possibleFrom == null) { possibleFrom = parent; } /* * We have two non-squashed parents. We cannot * reconcile history. */ else { throw new Exception( Messages.formatString("CheckinHeadCommitTask.NonLinearHistoryFormat", //$NON-NLS-1$ ObjectIdUtil.abbreviate(repository, currentCommit.getId()))); } } } /* All our parents were squashed! */ if (possibleFrom == null) { throw new Exception(Messages.formatString("CheckinHeadCommitTask.AllParentsSquashedFormat", //$NON-NLS-1$ ObjectIdUtil.abbreviate(repository, currentCommit.getId()))); } /* We only had one non-squashed parent */ else { fromCommit = possibleFrom; walker.parseHeaders(possibleFrom); } } commitList.add(new CommitDelta(fromCommit, toCommit)); currentCommit = fromCommit; } } finally { if (walker != null) { walker.dispose(); } } Collections.reverse(commitList); return commitList; }
From source file:com.microsoft.gittf.core.util.CommitWalker.java
License:Open Source License
/** * Get the list of commit deltas that represent the commits between a source * commit and a target commit. If there are multiple paths available the * method will select the first valid path found. * //from w ww . j av a 2s . c o m * @param repository * the git repository * @param sourceCommitID * the source commit id * @param targetCommitID * the target commit id * @return * @throws Exception */ public static List<CommitDelta> getAutoSquashedCommitList(final Repository repository, final ObjectId sourceCommitID, final ObjectId targetCommitID) throws Exception { Check.notNull(repository, "repository"); //$NON-NLS-1$ Check.notNull(targetCommitID, "targetCommitID"); //$NON-NLS-1$ RevWalk walker = null; try { walker = new RevWalk(repository); RevCommit start = walker.lookupCommit(targetCommitID); RevCommit end = sourceCommitID != null ? walker.lookupCommit(sourceCommitID) : null; walker.parseHeaders(start); if (end != null) walker.parseHeaders(end); List<RevCommit> commitPath = detectAutoSquashedPath(walker, start, end); if (commitPath == null || commitPath.size() < 2) { throw new Exception(Messages.formatString("CheckinHeadCommitTask.LatestNotInTreeFormat", //$NON-NLS-1$ ObjectIdUtil.abbreviate(repository, end.getId()))); } List<CommitDelta> deltas = new ArrayList<CommitDelta>(); for (int i = 0; i < commitPath.size() - 1; i++) { deltas.add(new CommitDelta(commitPath.get(i), commitPath.get(i + 1))); } return deltas; } finally { if (walker != null) { walker.dispose(); } } }