John Doe John Doe - 3 years ago 139
Groovy Question

Jgit Author last commit

I've found similar question and base on it, but I got error

Cannot invoke method getAuthorIdent() on null object
. I try to get last commit, check if it's equal to
. Why it cannot be
? And if statement will work like I want?

def authorEqual() {

def badAuthor = 'John'
Git git = File(".git"))
RevCommit lastCommit = null --> ERROR FROM HERE
List<Ref> branches = new Git(git.repository).branchList().setListMode(ListMode.ALL).call();
try {
RevWalk walk = new RevWalk(git.repository)
for(Ref branch : branches){
RevCommit commit = walk.parseCommit(branch.getObjectId());
PersonIdent aAuthor = commit.getAuthorIdent()
-----------^ <-- HERE ERROR
lastCommit.getAuthorIdent().getWhen().equals(badAuthor)) > 0)

lastCommit = commit;
println commit

Answer Source

Consider Groovy way of finding last commit:

RevCommit lastCommit = branches.collect { branch -> revWalk.parseCommit(branch.objectId) }
        .sort { commit -> commit.authorIdent.when }

What it does it collects last commits from all branches, then it sorts them by date in descendant order and gets the most recent one. Having last commit you can easily check who was the author of it and execute any additional logic. Below you can find Groovy script example:

import org.eclipse.jgit.api.Git
import org.eclipse.jgit.api.ListBranchCommand
import org.eclipse.jgit.lib.Ref
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.revwalk.RevWalk

@Grab(group='org.eclipse.jgit', module='org.eclipse.jgit', version='')

Git git = File("."))
List<Ref> branches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()
RevWalk revWalk = new RevWalk(git.repository)
String excludeAuthorsCommit = 'Joe Doe'

RevCommit lastCommit = branches.collect { branch -> revWalk.parseCommit(branch.objectId) }
        .sort { commit -> commit.authorIdent.when }

println "${lastCommit.authorIdent.when}: ${lastCommit.shortMessage} (${})"

if ( == excludeAuthorsCommit) {
    // Do what you want

I've tested it in project with 5 branches. It returned recent commit from test branch I did couple minutes ago. I hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download