Amy Amy - 4 years ago 143
Git Question

How do I do “git show sha1” using JGit

Basically I would like to read the contents of all files in a commit based on the commit hash.

I've tried the following:

try(RevWalk revWalk = new RevWalk(gitRepository))
RevCommit commit = revWalk.parseCommit(ObjectId.fromString(commitSha));
RevTree tree = commit.getTree();

try(TreeWalk treeWalk = new TreeWalk(gitRepository))

ObjectId entryId = null;

while (
entryId = treeWalk.getObjectId(0);

ObjectLoader loader =;


but it seems to be picking up files from previous commits as well.

EDIT: I realize that I wasn't very specific in my original post.

Let's say I make a commit (Commit1) where I add a file (File1). Then I make a commit (Commit2) where I add a different file (File2). Then I make another commit (Commit3) where I modified File2. I would now like to get the contents of File2 from Commit2 for whatever reason. Using the above, the treewalk will retrieve the contents of Commit2 AND Commit1 which is not what I want.

Answer Source

As you've noticed, Git does not store a commit as a diff to the prior commit, it stores a commit as a snapshot of the entire repository at that point in time.

This is not terribly obvious, because even git show <commitid> will provide you with a diff between a commit and its parent. But it becomes clear when you iterate over the contents of a commit like you've done.

If you want to emulate git show <commitid> and look at what changes were introduced by a commit, you'll need to compare it to its parent.

Git git = new Git(gitRepository);

ObjectId newTreeId = ObjectId.fromString(commitSha + "^{tree}");
ObjectId oldTreeId = gitRepository.resolve(commitSha + "^^{tree}");

CanonicalTreeParser newTree = new CanonicalTreeParser();
newTree.reset(reader, newTreeId);

CanonicalTreeParser oldTree = new CanonicalTreeParser();
oldTree.reset(reader, oldTreeId);

for (DiffEntry de : git.diff().setNewTree(newTree).setOldTree(oldTree).call())
    /* Print the file diff */
    DiffFormatter formatter = new DiffFormatter(System.out);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download