Search code examples
javagitjgit

Git show file in target branch in JGit?


I want to show to file content of a target branch in JGit without checking out that branch. For example, showing the content of README.md of master branch while the current branch is iss1. The equivalent Git command should be:

myProj (iss1) $ git show master:README.md
Hello world!

How can I do it using JGit?


Solution

  • 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 treeId = 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.md", treeId);
    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.