如何“猫” JGit中的文件? [英] How to "cat" a file in JGit?

查看:75
本文介绍了如何“猫” JGit中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前一段时间,我在Java中寻找一个嵌入式分布式版本控制系统
,我想我已经在 JGit 中找到了,它是一个纯粹的Java实现git。
但是,示例代码或教程没有多少内容。

A while back I was looking for an embeddable distributed version control system in Java, and I think I have found it in JGit, which is a pure Java implementation of git. However, there is not much in the way of sample code or tutorials.

如何使用JGit来检索某个文件的HEAD版本例如 svn cat hg cat 要做)?

How can I use JGit to retrieve the HEAD version of a certain file (just like svn cat or hg cat whould do)?

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

I suppose this involves some rev-tree-walking and am looking for a code sample.

推荐答案

不幸的是,Thilo的答案不适用于最新的JGit API。这里是我找到的解决方案:

Unfortunately Thilo's answer does not work with the latest JGit API. Here is the solution I found:

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)

我希望它更简单。

这篇关于如何“猫” JGit中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆