Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a merge-base done in JGit?

Tags:

java

git

jgit

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?

like image 235
Ed I Avatar asked Oct 17 '14 22:10

Ed I


2 Answers

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.

like image 108
robinst Avatar answered Nov 02 '22 03:11

robinst


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;
    }
}
like image 28
arjunmathur Avatar answered Nov 02 '22 04:11

arjunmathur