简体   繁体   中英

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))
        {
           treeWalk.addTree(tree);
           treeWalk.setRecursive(true);

           ObjectId entryId = null;

           while (treeWalk.next())
           {
              entryId = treeWalk.getObjectId(0);
           }

           ObjectLoader loader = gitRepository.open(entryId);
        }

        revWalk.dispose();
     }

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.

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);
    formatter.setRepository(gitRepository);
    formatter.format(de);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM