How to “cat” a file in JGit?

后端 未结 7 601
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 04:25

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. How

7条回答
  •  [愿得一人]
    2020-12-01 05:12

    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.

提交回复
热议问题