I want to list the commits of a local Git repository in Java. So I am using below code to do so:
Iterable<RevCommit> commits = git.log().all().call();
But I also need the path of every file that was committed and listed in git log.
I want to list the commits of a local Git repository in Java. So I am using below code to do so:
Iterable<RevCommit> commits = git.log().all().call();
But I also need the path of every file that was committed and listed in git log.
Solution worked for me:
ObjectReader or = repository.newObjectReader();
RevWalk rw = new RevWalk(or);
TreeWalk tw = new TreeWalk(or);
tw.setFilter(TreeFilter.ANY_DIFF);
tw.setRecursive(true);
ObjectId start = repository.resolve(Constants.HEAD);
startId = or.abbreviate(start);
rw.markStart(rw.parseCommit(start));
for(;;){
RevCommit c = rw.next();
if (c == null){
break;
}
if (c.getParentCount() != 1){
continue;
}
RevCommit p = c.getParent(0);
rw.parseHeaders(p);
tw.reset(p.getTree(), c.getTree());
while (tw.next()) {
System.out.println(tw.getPathString()+" id: "+c.getId());
}
}
Regarding IncorrectObjectTypeException
, you do have the TreeWalk.reset() throwing that exception because, from the Javadoc:
the given object id does not denote a tree, but instead names some other non-tree type of object. Note that commits are not trees, even if they are sometimes called a "tree-ish".
See those examples of TreeWalk.reset
to see how to access the tree from a given commit. Like rev.getTree()
.