简体   繁体   English

如何使用 JGit API 从父提交中获取树?

[英]How do I get the tree from parent commits using the JGit API?

For a given commit I want to get the parent(s) commit tree so I can go on to compare the changes.对于给定的提交,我想获取父提交树,以便我可以继续比较更改。 I am finding that getTree() on the parent RevCommit objects always returns null.我发现父 RevCommit 对象上的 getTree() 总是返回 null。

    ObjectId lastCommitId = repository.resolve(Constants.HEAD);

    RevWalk revWalk = new RevWalk(repository);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    List<RevCommit> parents = new ArrayList<>();
    for(RevCommit parent : commit.getParents()) {
        parents.add(parent);
    }

    if ( parents.get(0).getTree() == null ) {
        System.out.println("first parent tree was null");
    }

Am i going about this the wrong way?我会以错误的方式解决这个问题吗? Are the parent objects a shallow copy and I have to do something to populate the tree property?父对象是浅拷贝,我必须做一些事情来填充树属性吗?

I did get it to work as follows but would still like to know if this is the right way to do it.我确实让它按如下方式工作,但仍然想知道这是否是正确的方法。

    ObjectId lastCommitId = repository.resolve(Constants.HEAD);

    RevWalk revWalk = new RevWalk(repository);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    List<RevCommit> parents = new ArrayList<>();
    for(RevCommit parent : commit.getParents()) {

        RevCommit deepCopy = revWalk.parseCommit(parent.getId());

        parents.add(deepCopy);

    }

    if ( parents.get(0).getTree() != null ) {
        System.out.println(parents.get(0).getTree().toString());
    } else {
        System.out.println("first parent tree was null");
    }

Your second approach is right.你的第二种方法是正确的。 commit.getParents() returns incomplete RevCommit s. commit.getParents()返回不完整的RevCommit s。 While their ID attribute is set, all other attributes (tree, message, author, committer, etc.) are not.虽然设置了它们的 ID 属性,但所有其他属性(树、消息、作者、提交者等)都没有设置。 Hence the NullPointerException .因此NullPointerException In order to actually use the parent commit you need to first parse the commit header, either with parseCommit like you did为了实际使用父提交,您需要首先解析提交标头,或者像您一样使用parseCommit

parentCommit = revWalk.parseCommit(parentCommit.getId());

or with parseHeaders或使用parseHeaders

revWalk.parseHeaders(parentCommit);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM