Retrieving oldest commit with JGit

I am experimenting with JGit for a project and while it mostly works, retrieving the oldest (first) commit does not. Here is the code:

    RevWalk rw = new RevWalk(new Repository(
           new File("/path/to/git")));
    RevCommit oldest;
    Iterator<RevCommit> i = rw.iterator();
    if (i.hasNext())
        oldest = i.next();
    Commit c = oldest.asCommit(rw); //oldest is null here, NPE

Does anyone know what I am doing wrong?

  • Can EGit (Eclipse git plugin) use an SSH key instead of a username and password?
  • Git pull not pulling everything
  • create branch with N-last commits
  • Fixing up a git repo that is slowed because of big binary files
  • git rebase: “error: cannot stat 'file': Permission denied”
  • Is there a way to do “git checkout” and *force* the argument to be interpreted as a branch name?
  • How can you remove and then restore non index changes using the stash without ever having merge conflicts in git?
  • GitHub: A tag but not a release
  • Git Giving “fetch first” error when trying to push
  • Reverting an interactive git rebase
  • git fetch shows nothing on console
  • Git - Automatically track all files in a directory
  • One Solution collect form web for “Retrieving oldest commit with JGit”

    I think I found it. You have to reverse the commit log and set a starting point in order to make it start going through the revisions. The following extract does what I was looking for, but I somehow doubt how optimal it is.

     RevWalk rw = new RevWalk(new Repository(
           new File("/path/to/git")));
     RevCommit c = null;
     AnyObjectId headId;
     try {
         headId = git.resolve(Constants.HEAD);
         RevCommit root = rw.parseCommit(headId);
         rw.sort(RevSort.REVERSE);
         rw.markStart(root);
         c = rw.next();
     } catch (IOException e) {
         e.printStackTrace();
     }
    
    Git Baby is a git and github fan, let's start git clone.