Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jgit

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");
    }
like image 670
Interition Avatar asked Mar 04 '15 10:03

Interition


1 Answers

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);
like image 138
Rüdiger Herrmann Avatar answered Sep 18 '22 07:09

Rüdiger Herrmann