How to get RevCommit or ObjectId from SHA1 ID string using JGit?

This question is the opposite of this question: JGit, how do I get SHA1 from RevCommit? .

If I am assigned the SHA1 identifier of a particular commit as a string, how can I get the ObjectId or the associated RevCommit in JGit?

Here is a possible answer that RevCommit through all RevCommit s:

 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?

+7
jgit sha1
source share
2 answers

It might be easier to convert the string to ObjectId first and then view RevWalk .

 ObjectId commitId = ObjectId.fromString( "ab434..." ); RevWalk revWalk = new RevWalk( repository ); RevCommit commit = revWalk.parseCommit( commitId ); revWalk.close() 
+10
source share

Note that RevWalk now closes automatically, so you can also use the try-with-resources statement:

 try (RevWalk revWalk = new RevWalk(repository)) { RevCommit commit = revWalk.parseCommit(commitId); } 
+1
source share

All Articles