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?
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.
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.
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.
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
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.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