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

时间:2017-08-21 09:35:43

标签: 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;
}

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

1 个答案:

答案 0 :(得分:3)

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

A branch and its commit history

如RüdigerHerrmann所述,虽然通常在分支上创建提交,但事实之后你不能说提交“在分支上完成”。之后可以添加,删除,重命名或更新分支。例如,即使删除了分支或标记<Content> <Text>Vehicle Stats:</Text> <Text>Year: {this.state.vehicleYear}</Text> <Text>Make: {this.state.vehicleMake}</Text> <Text>Model: {this.state.vehicleModel}</Text> {this.state.vehicleYear === "" ? <VehicleYearPicker vehicleYear={this.yearPicked}/> : undefined} {this.state.vehicleYear !== "" && this.state.vehicleMake === "" ? <VehicleMakePicker pickedYear={this.state.vehicleYear} vehicleMake={this.makePicked}/> : undefined} {this.state.vehicleModel === "" && this.state.vehicleMake !== "" ? <VehicleModelPicker homeState={this.state} vehicleModel={this.modelPicked}/> : undefined} </Content> ,提交v1.098ca934ac2仍然存在,并且可以通过f30ab访问。我建议你阅读Pro Git (2nd Edition), Chapter 3.1 Git - Branches in a Nutshell了解更多细节。

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

master
相关问题