Skip to content
Advertisement

How to get the file list for a commit with JGit

I have been working on a Java based product for which the Git features are going to be integrated. Using one of the Git features, I have done adding 10+ files into the Git repository by staging followed by committing them in a single commit.

Is the reverse of the above process possible? I.e Finding the list of files committed as part of a commit.

I got the commit with the help of the git.log() command but I am not sure how to get the file list for the commit.

Example Code:

Git git = (...);
Iterable<RevCommit> logs = git.log().call();
for(RevCommit commit : logs) {
    String commitID = commit.getName();
    if(commitID != null && !commitID.isEmpty()) {
    TableItem item = new TableItem(table, SWT.None);
    item.setText(commitID);
    // Here I want to get the file list for the commit object
}
}

Advertisement

Answer

Each commit points to a tree that denotes all files that make up the commit.

Note, that this not only includes the files that were added, modified, or removed with this particular commit but all files contained in this revision.

If the commit is represented as a RevCommit, the ID of the tree can be obtained like this:

ObjectId treeId = commit.getTree().getId();

If the commit ID originates from another source, it needs to be resolved first to get the associated tree ID. See here, for example: How to obtain the RevCommit or ObjectId from a SHA1 ID string with JGit?

In order to iterate over a tree, use a TreeWalk:

try (TreeWalk treeWalk = new TreeWalk(repository)) {
  treeWalk.reset(treeId);
  while (treeWalk.next()) {
    String path = treeWalk.getPathString();
    // ...
  }
}

If you are only interested in the changes that were recorded with a certain commit, see here: Creating Diffs with JGit or here: File diff against the last commit with JGit

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement