JGit:在分支中的提交处读取文件的内容

Mas*_*ind 5 java jgit

我想读取某个分支中某个提交处的文件内容:我目前正在使用此代码来读取某个提交处的文件内容,忽略该分支。

    public static String readContentOfFileAtCommit(String commitStr, String fileName)
        throws IOException {

    String content = null;
    ObjectId lastCommitId = currentRepo.resolve(commitStr);

    try (RevWalk revWalk = new RevWalk(currentRepo)) {
        RevCommit commit = revWalk.parseCommit(lastCommitId);
        RevTree tree = commit.getTree();

        try (TreeWalk treeWalk = new TreeWalk(currentRepo)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(fileName));
            if (!treeWalk.next()) {
                throw new IllegalStateException("Did not find expected file:" + fileName);
            }

            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = currentRepo.open(objectId);
            content = new String(loader.getBytes());
        }

        revWalk.dispose();
    }

    return content;
}
Run Code Online (Sandbox Code Playgroud)

我的目标是在某个分支上完成的某个提交中获取文件的内容。

Min*_*ang 8

与大多数较旧的 VCS 工具分支不同,Git 中的分支只是指向这些提交之一的轻量级可移动指针。它本身不“包含”任何提交。换句话说,它只是一个简单的文件,包含它指向的提交的 40 个字符 SHA-1 校验和。Git - Branches in a Nutshell中还有一个非常说明性的示例:

\n\n

分支及其提交历史

\n\n

正如 R\xc3\xbcdiger Herrmann 所说,虽然提交通常是在分支上创建的,但事后你不能说提交“是在分支上完成的”。之后可以添加、删除、重命名或更新分支。例如,即使分支或标签v1.0被删除,提交98ca9, 34ac2,f30ab仍然存在,并且可以通过 到达master。我建议您阅读Pro Git(第 2 版),第 3.1 章 Git - 分支简述,了解更多详细信息。

\n\n

至于 JGit,这是我对特定提交的读取路径的实现:

\n\n
private String getContent(RevCommit commit, String path) throws IOException {\n  try (TreeWalk treeWalk = TreeWalk.forPath(git.getRepository(), path, commit.getTree())) {\n    ObjectId blobId = treeWalk.getObjectId(0);\n    try (ObjectReader objectReader = repo.newObjectReader()) {\n      ObjectLoader objectLoader = objectReader.open(blobId);\n      byte[] bytes = objectLoader.getBytes();\n      return new String(bytes, StandardCharsets.UTF_8);\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n