Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving oldest commit with JGit

Tags:

java

git

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?

like image 581
Georgios Gousios Avatar asked Aug 04 '10 16:08

Georgios Gousios


1 Answers

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();
 }
like image 189
Georgios Gousios Avatar answered Oct 14 '22 14:10

Georgios Gousios