AshokDev AshokDev - 25 days ago 20
Git Question

Get latest committed branch(name) details in JGit

How to determine the latest committed branch in the Git repository?
I want to clone only the recently updated branch instead of cloning all the branches despite of whether it is merged to master (default branch) or not.

LsRemoteCommand remoteCommand = Git.lsRemoteRepository();
Collection <Ref> refs = remoteCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password))

for (Ref ref : refs) {
System.out.println("Ref: " + ref.getName());

//cloning the repo
CloneCommand cloneCommand = Git.cloneRepository();
result = cloneCommand.setURI(uri.trim())
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName,password)).call();

Can anyone help me on this?


I am afraid you will have to clone the entire repository with all its branches to find out the newest branch.

The LsRemoteCommand lists branch names and the id's of the commits they point to, but not the timestamp of the commit.

Git's 'everything is local' design requires you to clone a repository before examining its contents. Note: using Git/JGit's low-level commands/APIs it is possible to fetch the head commit of a branch for examination, but that contradicts its design.

Once you have cloned the repository (without an initial checkout) you can iterate over all branches, load the respective head commit and see which one is the newest.

The example below clone a repository with all its branches and then lists all branches to find out at which time their respective head commits where made:

Git git = Git.cloneRepository().setURI( ... ).setNoCheckout( true ).setCloneAllBranches( true ).call();
List<Ref> branches = git.branchList().setListMode( ListMode.REMOTE ).call();
try( RevWalk walk = new RevWalk( git.getRepository() ) ) {
  for( Ref branch : branches ) {
    RevCommit commit = walk.parseCommit( branch.getObjectId() );
    System.out.println( "Time committed: " + commit.getCommitterIdent().getWhen() );
    System.out.println( "Time authored: " + commit.getAuthorIdent().getWhen() );

Now that you know the newest branch, you can checkout this branch.