10

This question is the inverse of this question: JGit how do i get the SHA1 from a RevCommit?.

If I am given the SHA1 ID of a particular commit as a string, how can I obtain the ObjectId or associated RevCommit in JGit?

Here is a possible answer, which iterates through all RevCommits:

RevCommit findCommit(String SHAId)
{
    Iterable<RevCommit> commits = git_.log().call();    
    for (RevCommit commit: commits)
    {
        if (commit.getName().equals(SHAId))
            return commit;
    }    
    return null;
}

Is there anything better than this implementation above?

Community
  • 1
  • 1
modulitos
  • 14,737
  • 16
  • 67
  • 110

2 Answers2

19

It is probably easier to first convert the string into an ObjectId and then have the RevWalk look it up.

ObjectId commitId = ObjectId.fromString("ab434...");
try (RevWalk revWalk = new RevWalk(repository)) {
  RevCommit commit = revWalk.parseCommit(commitId);
}
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
  • 3
    The [jgit-cookbook](https://github.com/centic9/jgit-cookbook) has a ready-to-run snippet for this [here](https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/GetRevCommitFromObjectId.java). – centic Sep 12 '14 at 05:48
3

Notice that RevWalk is now auto-closable, so you can also use the try-with-resources statement:

try (RevWalk revWalk = new RevWalk(repository)) {
    RevCommit commit = revWalk.parseCommit(commitId);
}
Mincong Huang
  • 5,284
  • 8
  • 39
  • 62