I want traverse my git repo but only the HEAD commit including the remote branches. I have only local master branch and a lot of remote branches. I can traverse my actually working directory like.

    Ref head = repository.getRef("HEAD");
    RevWalk walk = new RevWalk(repository);

    RevCommit commit = walk.parseCommit(head.getObjectId());
    RevTree tree = commit.getTree();

    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    while (treeWalk.next()) {
        System.out(treeWalk.getPathString())
    }
    repository.close();

But this code only traverse the actual working directory. Afterwards i want read the files in the head commit. How i perform the reading and traversing the branches?

有帮助吗?

解决方案

Use the RefDatabase#getRefs to walk through the existing refs:

RefDatabase refDatabase = repository.getRefDatabase();
Map<String, Ref> refs = refDatabase.getRefs(Constants.R_REMOTES);
for (Ref remoteRef : refs) {
    // ...
}

The argument to getRefs is a prefix to get only certain refs, you can also use RefDatabase.ALL for getting all refs.

For reading the file contents, walk the tree as in the code from the question. Then, with the TreeWalk object, the contents can be read. See this answer from the How to “cat” a file in JGit? question.

其他提示

Ok this code shows me all the content but not in the right order i want. It starts at a random remote branch.

for (Map.Entry<String, Ref> entry : refList.entrySet()) {
            Ref head = repository.getRef(entry.getValue().getName());
            RevWalk walk = new RevWalk(repository);
            RevCommit commit = walk.parseCommit(head.getObjectId());
            RevTree tree = commit.getTree();
            TreeWalk treeWalk = new TreeWalk(repository);
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                    ObjectId objectId = treeWalk.getObjectId(0);
                    ObjectLoader loader = repository.open(objectId);
                    loader.copyTo(System.out);
            }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top