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
badAuthor
. Why it cannot be
null
? And if statement will work like I want?

def authorEqual() {

def badAuthor = 'John'
Git git = Git.open(new 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()
if(commit.getAuthorIdent().getWhen().compareTo(
-----------^ <-- 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 }
        .reverse()
        .first()

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='4.8.0.201706111038-r')

Git git = Git.open(new 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 }
        .reverse()
        .first()

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

if (lastCommit.authorIdent.name == 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