2012-06-12 40 views

回答

0

通過使用這個。 Iterable<RevCommit> gitLog = gitRepo.log().call();您可以從該對象獲取所有提交哈希。

+0

是。我得到了我想要的提交哈希。但是,如何讀取散列樹中某個特定文件的內容? –

+0

你需要檢出散列並獲取文件的內容。在終端,你可以做'git checkout '。 –

+0

這是一個裸倉庫。 –

0

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

好主意。要重點演示ObjectLoader,可以簡化代碼片段:'setBare(false)'是默認值,不需要重新打開回收 - 重新使用'initialized','firstCommit'從'ci.call() ',不需要再次提交。 BTW臨時文件夾不會被刪除。 –

+0

感謝您的建議簡化;這些應該現在整合在一起。我不知道可以通過'Repository repository = git.getRepository()'獲取版本庫 - 很好的發現了這一點。是的,臨時文件夾不會被刪除,我只是留下它,因爲這不是一個真正的單元測試,而是一直運行,只是演示代碼。 –