How to “cat” a file in JGit?

后端 未结 7 632
爱一瞬间的悲伤
爱一瞬间的悲伤 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:00

    I followed @Thilo's and @morisil's answer to get this, compatible with JGit 1.2.0:

    File repoDir = new File("test-git/.git");
    // open the repository
    Repository repo = new Repository(repoDir);
    // find the HEAD
    Commit head = repo.mapCommit(Constants.HEAD);
    // retrieve the tree in HEAD
    Tree tree = head.getTree();
    
    // 1.2.0 api version here
    // find a file (as a TreeEntry, which contains the blob object id)
    TreeWalk treewalk = TreeWalk.forPath(repo, "b/test.txt", tree);
    // use the blob id to read the file's data
    byte[] data = repo.open(treewalk.getObjectId(0)).getBytes();
    

    I didn't test the Java version but it should work. It translates from

    (.getBytes (.open repo (.getObjectId (TreeWalk/forPath repo "b/test.txt" tree) 0)))
    

    in clojure (following the same setup as the top section), which does work.

提交回复
热议问题