如何在JGit中“cat”文件?

2022-09-01 10:26:58

不久前,我一直在Java中寻找一个可嵌入的分布式版本控制系统,我想我已经在JGit中找到了它,JGit是git的纯Java实现。但是,示例代码或教程的方式并不多。

如何使用JGit检索某个文件的HEAD版本(就像或咕噜咕噜一样)?svn cathg cat

我想这涉及一些rev-tree-walk,并且正在寻找一个代码示例。


答案 1

不幸的是,Thilo的答案不适用于最新的JGit API。以下是我发现的解决方案:

File repoDir = new File("test-git");
// open the repository
Repository repository = new Repository(repoDir);
// find the HEAD
ObjectId lastCommitId = repository.resolve(Constants.HEAD);
// now we have to get the commit
RevWalk revWalk = new RevWalk(repository);
RevCommit commit = revWalk.parseCommit(lastCommitId);
// and using commit's tree find the path
RevTree tree = commit.getTree();
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(path));
if (!treeWalk.next()) {
  return null;
}
ObjectId objectId = treeWalk.getObjectId(0);
ObjectLoader loader = repository.open(objectId);

// and then one can use either
InputStream in = loader.openStream()
// or
loader.copyTo(out)

我希望它更简单。


答案 2

以下是@morisil的答案的更简单版本,使用了@directed笑声中的一些概念,并用JGit 2.2.0进行了测试:

private String fetchBlob(String revSpec, String path) throws MissingObjectException, IncorrectObjectTypeException,
        IOException {

    // Resolve the revision specification
    final ObjectId id = this.repo.resolve(revSpec);

    // Makes it simpler to release the allocated resources in one go
    ObjectReader reader = this.repo.newObjectReader();

    try {
        // Get the commit object for that revision
        RevWalk walk = new RevWalk(reader);
        RevCommit commit = walk.parseCommit(id);

        // Get the revision's file tree
        RevTree tree = commit.getTree();
        // .. and narrow it down to the single file's path
        TreeWalk treewalk = TreeWalk.forPath(reader, path, tree);

        if (treewalk != null) {
            // use the blob id to read the file's data
            byte[] data = reader.open(treewalk.getObjectId(0)).getBytes();
            return new String(data, "utf-8");
        } else {
            return "";
        }
    } finally {
        reader.close();
    }
}

repo是在其他答案中创建的存储库对象。


推荐