I'm looking at the JGit Documentation, currently at version 3.5.1.201410131835-r, and I cannot find the equivalent of git-merge-base.
I would like to determine if a branch is up-to-date, behind, ahead, or diverged, as shown in git: check if pull needed.
What is the most concise way in JGit to find as good common ancestors as possible for a merge?
You can use RevFilter.MERGE_BASE
for that:
RevWalk walk = new RevWalk(repository);
walk.setRevFilter(RevFilter.MERGE_BASE);
walk.markStart(commit1);
walk.markStart(commit2);
RevCommit mergeBase = walk.next();
Also note that there is BranchTrackingStatus if all you are interested in is ahead/behind count of a branch compared to its remote-tracking branch.
Here it is with JGit using BranchTrackingStatus:
public enum TrackingStatus {
SAME, BEHIND, AHEAD, DIVERGED
}
public TrackingStatus getTrackingStatus() throws IOException, GitAPIException {
Repository userRepo = new FileRepository(<path_to_.git_file>);
Git git = new Git(userRepo);
git.fetch().call();
BranchTrackingStatus bts = BranchTrackingStatus.of(git.getRepository(),
git.getRepository().getBranch());
int aheadCount = bts.getAheadCount();
int behindCount = bts.getBehindCount();
if (aheadCount == 0 && behindCount == 0) {
return TrackingStatus.SAME;
} else if (aheadCount > 0 && behindCount == 0) {
return TrackingStatus.AHEAD;
} else if (aheadCount == 0 && behindCount > 0) {
return TrackingStatus.BEHIND;
} else {
return TrackingStatus.DIVERGED;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With