Gaurav Shah
Gaurav Shah

Reputation: 51

How do I do "git show sha1:file" using JGit

I clone a repository as bare on my local disk using JGit. Now, I need to read the contents of a file at any given commit id (SHA1). How do I do this ?

Upvotes: 4

Views: 2889

Answers (2)

Clemens Klein-Robbenhaar
Clemens Klein-Robbenhaar

Reputation: 3527

The comment of Rüdiger Herrmann in this answer contains the relevant hints; but to make it easier for the friends of copy & paste solutions here my complete self-contained example code of a junit test that creates a revision of a file and then retrieves the contents of this revision. Works with jGit 4.2.0.

@Test
public void test() throws IOException, GitAPIException
{
    //
    // init the git repository in a temporary directory
    //
    File repoDir = Files.createTempDirectory("jgit-test").toFile();
    Git git = Git.init().setDirectory(repoDir).call();

    //
    // add file with simple text content
    //
    String testFileName = "testFile.txt";
    File testFile = new File(repoDir, testFileName);
    writeContent(testFile, "initial content");

    git.add().addFilepattern(testFileName).call();
    RevCommit firstCommit = git.commit().setMessage("initial commit").call();

    //
    // given the "firstCommit": use its "tree" and 
    // localize the test file by its name with the help of a tree parser
    //
    Repository repository = git.getRepository();
    try (ObjectReader reader = repository.newObjectReader())
    {
        CanonicalTreeParser treeParser = new CanonicalTreeParser(null, reader, firstCommit.getTree());
        boolean haveFile = treeParser.findFile(testFileName);
        assertTrue("test file in commit", haveFile);
        assertEquals(testFileName, treeParser.getEntryPathString());
        ObjectId objectForInitialVersionOfFile = treeParser.getEntryObjectId();

        // now we have the object id of the file in the commit:
        // open and read it from the reader
        ObjectLoader oLoader = reader.open(objectForInitialVersionOfFile);
        ByteArrayOutputStream contentToBytes = new ByteArrayOutputStream();
        oLoader.copyTo(contentToBytes);
        assertEquals("initial content", new String(contentToBytes.toByteArray(), "utf-8"));
    }

    git.close();
}

// simple helper to keep the main code shorter
private void writeContent(File testFile, String content) throws IOException
{
    try (OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream(testFile), Charset.forName("utf-8")))
    {
        wr.append(content);
    }
}

Edit to add: another, probably better example is at https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadFileFromCommit.java

Upvotes: 3

code-red
code-red

Reputation: 306

By using this. Iterable<RevCommit> gitLog = gitRepo.log().call(); you can get all the commit hash from that object.

Upvotes: 0

Related Questions