前阵子我在找embeddable distributed version control system in Java
我想我在JGit中找到了它,它是git的纯Java实现。
但是,示例代码或教程的方式并不多。

如何使用JGit检索某个文件的HEAD版本(就像谁可以做的svn cathg cat一样)?

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

最佳答案

不幸的是,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)

我希望它更简单。

09-04 03:54