8

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");
    }
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
Interition
  • 381
  • 2
  • 15

1 Answers1

10

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);
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79