如何使用JGit执行“git show sha1:file”

时间:2012-06-12 09:13:40

标签: jgit

我使用JGit在本地磁盘上克隆存储库。现在,我需要在任何给定的提交ID(SHA1)中读取文件的内容。我该怎么做?

2 个答案:

答案 0 :(得分:1)

comment of Rüdiger Herrmann in this answer包含相关提示;但为了使复制和朋友的朋友更容易在此处粘贴解决方案我的完整自包含的junit测试示例代码,该代码创建文件的修订版,然后检索此修订版的内容。适用于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);
    }
}

修改以添加:另一个,可能更好的示例是https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadFileFromCommit.java

答案 1 :(得分:0)

使用这个。 Iterable<RevCommit> gitLog = gitRepo.log().call();您可以从该对象获取所有提交哈希值。