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.
How can I use JGit to retrieve the HEAD version of a certain file (just like svn cat
or hg cat
whould do)?
I suppose this involves some rev-tree-walking and am looking for a code sample.
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)
I wish it was simpler.
Who in the world designed this API?
Do you know what the nth value from treeWalk.getObjectId(nth) does? (i.e. what are the cases where we pass a value to treeWalk.getObjectId bigger than 0 ?)
@DinisCruz
TreeWalk
can walk over more than one tree (by callingaddTree
multiple times). In that case, you can usegetObjectId(N)
to get the object ID from tree N (which might the the same or different, depending on the trees).See creinig's answer for how to simplify this a bit by using
TreeWalk.forPath
.How can I save the output of
loader
into a variable?