As some light research I was looking at how to determine a Git repository’s current branch name in a Groovy script.
In the Git CLI this would be shown with:
C:\temp\git\SdWf\project>git branch d12345-validation-fails d54321-login-box f52123-error-report * master
The current branch is shown with a leading asterisk.
Invoke Git
One method is to just invoke the Git executable:
gitExe = "serversGitbingit.exe" currentBranch = '' matcher = ~/* (.*)s/ process = "${gitExe} branch".execute() process.in.eachLine{ line -> println line m = line =~ /*s+(.*)s?/ if(m){ currentBranch = m[0][1] return } } println "current: '$currentBranch'"
Use JGit library
Another is to use a Java based Git library like JGit:
@GrabResolver( name='jgit-repository', root='http://download.eclipse.org/jgit/maven' ) @Grab( group='org.eclipse.jgit', module='org.eclipse.jgit', version='1.1.0.201109151100-r' ) import org.eclipse.jgit.* import org.eclipse.jgit.lib.* import org.eclipse.jgit.util.* directory = new File(args[0]) Repository repository = RepositoryCache.open( RepositoryCache.FileKey.lenient(directory,FS.DETECTED), true) println(repository.getFullBranch())
This would be run as:
groovy test\Git.groovy temp\git\SdWf\depot\project.git
refs/heads/master
One problem with the JGit approach is that, afaik, this won’t work if the repo is represented by a ‘pointer’ file, i.e., created with the –separate-git-dir option. Also, unlike the Git branch command, you must open the target git repo at it’s root level, not a nested subdirectory of the repo.
Environment
— Windows 7 64bit Professional
— git version 1.7.6.msysgit.0
— Groovy Version: 1.8.2 JVM: 1.6.0_25
References