Skip to content
Advertisement

Get the latest commit in a repository with 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?

Advertisement

Answer

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 (...)
Advertisement