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 =;
    Commit c = oldest.asCommit(rw); //oldest is null here, NPE

Does anyone know what I am doing wrong?

  • How do I check in files for building with git?
  • Git: Pushing multiple branches using wildcards
  • git cherry-pick does not just pick the diff of the commit
  • Verbose display of a git add
  • git cant resolve rebase conflicts as mergetool doesnt pop up
  • Problem pushing to Heroku with dm-migrations
  • How to integrate UML diagrams into GitLab or GitHub
  • Retrieve the list of child commits of an specific commit in Git
  • What do you do when you find a bug in other function when develop a function?
  • In git, is there a simple way of introducing an unrelated branch to a repository?
  • Is there a character for “current branch” in git?
  • Jenkins: Retrieving submodules with Git
  • 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);
         c =;
     } catch (IOException e) {
    Git Baby is a git and github fan, let's start git clone.