While there is no direct equivalent to git show
in JGit, it provides API to implement what the command does yourself.
If all you have is the ref to a branch, then you first need to resolve the tree id of its head commit. Luckily, Repository::resolve
accepts an expression that will return the necessary tree id:
ObjectId masterTreeId = repository.resolve( "refs/heads/master^{tree}" );
Given the tree id, you can use a TreeWalk
to obtain the blob id that holds the contents of the desired file.
TreeWalk treeWalk = TreeWalk.forPath( git.getRepository(), "readme", masterTreeId );
ObjectId blobId = treeWalk.getObjectId( 0 );
The forPath
factory method creates a TreeWalk
and positions it at the path that was given in the second argument.
With the blob id in turn, you can finally load the contents from Git's object database.
ObjectReader objectReader = repository.newObjectReader();
ObjectLoader objectLoader = objectReader.open( blobId );
byte[] bytes = objectLoader.getBytes();
objectReader.close();
The complete source code can be found here: https://gist.github.com/rherrmann/0c682ea327862cb6847704acf90b1d5d
For more details about the inner workings of the Git object database, you may want to read Explore Git Internals with the JGit API.