Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the latest commit in a repository with JGit

Tags:

java

git

jgit

I want to get the last commit metadata (the youngest one by date) in a repository using JGit.

I know that I can get the commit metadata using:

try (RevWalk walk = new RevWalk(repository))
{
    RevCommit commit = walk.parseCommit(repository.resolve(commitHash));
}

But how to get the latest commit hash?

Is there any other way to get the youngest by date RevCommit in a repository directly?

like image 263
Master Mind Avatar asked Mar 15 '17 20:03

Master Mind


3 Answers

You could make use of git log and set it to only return the top most commit:

RevCommit latestCommit = new Git(repository).
   log().
   setMaxCount(1).
   call().
   iterator().
   next();

String latestCommitHash = latestCommit.getName();
like image 122
jet457 Avatar answered Nov 10 '22 13:11

jet457


Compare by dates of last commits in all branches. ListMode.ALL can be changed to ListMode.REMOTE to compare only remote branches. Or... the fluent setter .setListMode(whatever) can be omitted to read from the local repository.

RevCommit youngestCommit = null;
Git git = new Git(repository);
List<Ref> branches = git.branchList().setListMode(ListMode.ALL).call();
try {
    RevWalk walk = new RevWalk(git.getRepository());
    for(Ref branch : branches) {
        RevCommit commit = walk.parseCommit(branch.getObjectId());
        if(youngestCommit == null || commit.getAuthorIdent().getWhen().compareTo(
           youngestCommit.getAuthorIdent().getWhen()) > 0)
           youngestCommit = commit;
    }
} catch (...)
like image 25
Grzegorz Górkiewicz Avatar answered Nov 10 '22 12:11

Grzegorz Górkiewicz


To find the newest commit within a repository, configure a RevWalk to start from all known refs and sort it descending by commit date. For example:

Repository repo = ...
try( RevWalk revWalk = new RevWalk( repo ) ) {
  revWalk.sort( RevSort.COMMIT_TIME_DESC );
  Map<String, Ref> allRefs = repo.getRefDatabase().getRefs( RefDatabase.ALL );
  for( Ref ref : allRefs.values() ) {
    RevCommit commit = revWalk.parseCommit( ref.getLeaf().getObjectId() );
    revWalk.markStart( commit );
  }
  RevCommit newestCommit = revWalk.next();
}

Depending on your use case, you may also want to mark start points from refs from repo.getRefDatabase().getAdditionalRefs() which includes refs like FETCH_RESULT, ORIG_HEAD, etc. If you find that there are still untracked refs, use repo.getRefDatabase().getRef().

like image 2
Rüdiger Herrmann Avatar answered Nov 10 '22 13:11

Rüdiger Herrmann