Get the latest commit in a repository with JGit

jgit get current branch name
jgit '' create remote repository
jgit check if repository exists
how to connect git repository using java
jgit get all commits
jgit get list of branches
jgit pull example
jgit maven

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?

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

JGit - Tutorial, We get them from the Git object by calling git.add() and git.commit() You can get the current branch of your repository using this: repo. to get a better string for IDs like. v2.0-40-gdc25d60 Here, ‘v2.0′ is the latest tag. ’40’ is the number of commits after the ‘v2.0’ tag and ‘gdc25d60’ is the first 8 digits of the commit sha-1 hash ID.

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 =;

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

JGit by Example, Learn the basics of using JGit - a Git version control written in Java. Please visit the Maven Central repository for the newest version of JGit. Once this Please visit Eclipse JGit to get the necessary information how to integrate this library. The RevCommit represents a commit in the Git object model. 2.1. Cloning a Git repository with JGit; 2.2. Opening a local repository with JGit; 2.3. Checking out a specific commit; 2.4. Searching and accessing a file; 2.5. Example for using JGit; 3. Example usage of JGit

Below you can find a Java 8 Stream API solution:

final List<Ref> branches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
final RevWalk revWalk = new RevWalk(git.getRepository());
        .map(branch -> {
            try {
                return revWalk.parseCommit(branch.getObjectId());
            } catch (IOException e) {
                throw new RuntimeException(e);
        .sorted(Comparator.comparing((RevCommit commit) -> commit.getAuthorIdent().getWhen()).reversed())
        .ifPresent(commit -> {
            System.out.printf("%s: %s (%s)%n", commit.getAuthorIdent().getWhen(), commit.getShortMessage(), commit.getAuthorIdent().getName());

It iterates over all branches and picks recent commits in those branches, then it sorts list of commits by date in descendant order and picks the first one. If it exists it prints to console output something like this:

Wed Aug 30 09:49:42 CEST 2017: test file added (Szymon Stepniak)

Of course the behavior on last commit existence is exemplary and it can be easily replaced with any additional business logic. I hope it helps.

A Guide to JGit, The starting point for most JGit sessions is the Repository class, and the first getRef("master"); // Get the object the reference points to ObjectId masterTip = master. so you can ask if the tag is “peeled,” meaning that it points to the final target of a common goals, like adding a file to the index, or making a new commit. Get the last commit date: You want the "repository wide last commit date for a given git user and git project, for a given branch. The date you're after is the latest date shown when you visit your repo and go to commits -> master for example:

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();

JGit, In this repository, you find JGit code examples and snippets for every commit() creates a new commit with the current contents of the index� By default, with no arguments, git log lists the commits made in that repository in reverse chronological order; that is, the most recent commits show up first. As you can see, this command lists each commit with its SHA-1 checksum, the author’s name and email, the date written, and the commit message.

Git with JGit, setRepository(gitRepo); diffFormatter.format(earlierCommit.getId() e ) { throw new MojoExecutionException( "Error trying to get the last git commit uuid", e ); } }. This works well, except if new commit is a merged commit with two or more parents. If I use this code with multiple parents then I get all diffs up to merge base commit. Any idea how to get diffs of a merge commit (mostly they are none, but sometimes there is some file changed) without including all diffs up to merge base?

org.eclipse.jgit.revwalk.RevCommit.getId java code examples, Repository repo;String revstr;repo.resolve(revstr); Smart code suggestions by new MojoExecutionException( "Error trying to get the last git commit uuid", e ); } }. The JGit framework is rich and diverse, it has two layers, a low-level api and a higher-level set of porcelain commands. This can be a bit intimidating at first as there are lots of classes, some of which are not relevant for most tasks

org.eclipse.jgit.lib.ObjectId.getName java code examples, Open the Git repository in the current directory. def git = org.ajoberstar.grgit.Grgit. open(file('..')) // Get commit id of HEAD. date= git.head(). Alas, JGit rewrites filter=blob:none to filter=blob:limit=0, so if the repository contains an empty file then the empty blob gets transferred. Fix it by teaching JGit about filters based on object type to complement the existing filters based on object size.

  • Can you clarify what latest means exactly? Do you mean the youngest by date? From all branches?
  • Do you mean the commit that HEAD ultimately points to?
  • Yes Exactly, the yougest by date from all the branches. is it Important to look up for him for all the branches, because I thought that I can look up for him relatively to a repo regardless of the branches?
  • Would it return the youngest commit by date in the whole repo regardless of the branches?
  • No, it will return the commit to which HEAD points to (usually the current branch).
  • The snippet assumes that the newest commit is among the branch heads, which may, at least in theory, not be the case. Or am I missing something? Another issue is that the author timestamp is compared. Use getCommiterIdent().getWhen() instead.
  • the most compact code, and it works fine. Thanks (y)