Search code examples
javajgitgit-log

List all commits of a branch since it was created from master with JGit


I'm trying to use JGit to get a commit log specific to a branch since it was created. I've found several posts in forums that sound like they are describing this, but they seem to all return commits to the branch and everything prior.

I basically want to emulate this git command with JGit

git log master..testBranch

which does exactly what I want.


Solution

  • The following snippet should do this, it walks the branch testBranch backwards until the commits are on master.

    I have also added this to the sample snippet in my jgit-cookbook

            try (Git git = new Git(repository)) {
                Iterable<RevCommit> logs = git.log()
                        .not(repository.resolve("master"))
                        .add(repository.resolve("remotes/origin/testBranch"))
                        .call();
                count = 0;
                for (RevCommit rev : logs) {
                    System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
                    count++;
                }
                System.out.println("Had " + count + " commits only on test-branch");
            }