gpt4 book ai didi

jgit - 我如何使用 JGit 做 "git show sha1:file"

转载 作者:行者123 更新时间:2023-12-01 06:49:36 25 4
gpt4 key购买 nike

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

最佳答案

comment of Rüdiger Herrmann in this answer包含相关提示;但是为了让复制和粘贴解决方案的 friend 更容易,我在此处提供了一个完整的自包含的 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

关于jgit - 我如何使用 JGit 做 "git show sha1:file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10993634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com