How to “cat” a file in JGit?

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

    You can read the content of a given filepath as follows. Please be aware that the TreeWalk can be null if no path was found in the given tree. So it requires some specific handling.

    public String readFile(RevCommit commit, String filepath) throws IOException {
        try (TreeWalk walk = TreeWalk.forPath(repo, filepath, commit.getTree())) {
            if (walk != null) {
                byte[] bytes = repo.open(walk.getObjectId(0)).getBytes();
                return new String(bytes, StandardCharsets.UTF_8);
            } else {
                throw new IllegalArgumentException("No path found.");
            }
        }
    }
    

    For example:

    ObjectId head = repo.resolve(Constants.HEAD);
    RevCommit last = repo.parseCommit(head);
    readFile(last, "docs/README.md")
    

    This answer is written with JGit 4.8.0.

提交回复
热议问题