Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call git show --first-parent in jgit?

Tags:

java

git

jgit

I need to get the commits from master that are not of type merge and do not come from other branches (they were directly put on master). The git command is

git log --no-merges --first-parent

How can I do this using JGit? I managed to get the commits that are not of type merge using

RevFilter.NO_MERGES

But how can I get the commits that were commited direct into master branch?

like image 991
israell Avatar asked Oct 09 '15 12:10

israell


People also ask

What is first parent in git?

Git "First Parent" meaning The parent that gets recorded first (in the commit object of the new commit) is considered the "first parent", while the other one is considered the "second parent". It is possible for a commit to have an arbitrary number of parents.

What is the parent of a git commit?

The parent commit is the commit this current commit is based on. Usually: When you git commit normally, the current commit becomes the parent commit of the new commit that's introduced by the command.


1 Answers

For getting the first parent, you could just call the RevCommit.getParent() and work your way from there.

The rationale behind not using a RevWalk for visiting the tree is that RevWalk walks through revs without following the hierarchy -- i.e., if you didn't read the commit, it's parent will be read --, which is not what --first-parent does, and what we want here.

So Rüdiger Herrmann's answer will fail to remove the commits made on (n+1,...)th branches. It would only remove the first commit made on those branches.

Code

Repository repo = git.getRepository();
try (RevWalk walk = new RevWalk(repo)) {
    RevCommit head = walk.parseCommit(repo.getRef(MASTER).getObjectId());
    int count = 0;
    while (head != null) {
        count++;
        RevCommit[] parents = head.getParents();
        if (parents != null && parents.length > 0) {
            head = walk.parseCommit(parents[0]);
        } else {
            head = null;
        }
    }
    return count;
}

This is converted from groovy source

Notes

  1. The call to walk.parseCommit(parents[0]) is required as the commits returned by .getParents() will not be parsed completely, and will give null on calling .getParents() on themselves.
  2. This was written for finding version code from git repo for Android build script (gradle) based on my another answer. (see source)
like image 129
Avinash R Avatar answered Oct 26 '22 01:10

Avinash R