Warm tip: This article is reproduced from serverfault.com, please click

java-如何在JGit中“捕获”文件?

(java - How to "cat" a file in JGit?)

发布于 2009-11-06 03:28:38

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

如何使用JGit检索某个文件的HEAD版本(就像svn cat或应该hg cat做的那样)?

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

Questioner
Thilo
Viewed
11
3 2012-07-05 01:58:34

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

我希望它更简单。