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

↘锁芯ラ 提交于 2021-01-27 04:23:34

问题


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.

    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");
    }

回答1:


Your second approach is right. commit.getParents() returns incomplete RevCommits. While their ID attribute is set, all other attributes (tree, message, author, committer, etc.) are not. Hence the NullPointerException. In order to actually use the parent commit you need to first parse the commit header, either with parseCommit like you did

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

or with parseHeaders

revWalk.parseHeaders(parentCommit);


来源:https://stackoverflow.com/questions/28852698/how-do-i-get-the-tree-from-parent-commits-using-the-jgit-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!