我使用 JGit 在本地磁盘上克隆了一个存储库。现在,我需要读取任何给定提交 id (SHA1) 的文件内容。我该怎么做呢 ?
问问题
2401 次
2 回答
3
Rüdiger Herrmann 在此答案中的评论包含相关提示;但是为了让复制和粘贴解决方案的朋友在这里更容易,我完整的自包含 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
于 2016-03-21T14:58:06.943 回答
0
通过使用这个。Iterable<RevCommit> gitLog = gitRepo.log().call();
您可以从该对象获取所有提交哈希。
于 2012-06-13T05:44:35.943 回答