Skip to content

Instantly share code, notes, and snippets.

@barend
Created April 19, 2016 13:08
Show Gist options
  • Save barend/f9e75496eb972dae0623fe443ec70b98 to your computer and use it in GitHub Desktop.
Save barend/f9e75496eb972dae0623fe443ec70b98 to your computer and use it in GitHub Desktop.
Obtain a git hash in gradle, using JGit. Useful in environments where people frown on just putting a shell exec in your gradle file like so: "git log -1 --pretty=%H".execute().
// In buildSrc/
apply plugin: 'groovy'
repositories {
jcenter()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
compile gradleApi()
compile localGroovy()
compile 'org.eclipse.jgit:org.eclipse.jgit:4.1.1.201511131810-r'
}
// In buildSrc/src/main/groovy/
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.RepositoryBuilder
import org.gradle.api.Project
class GitFunctions {
public static String headCommitAndStatus(Project project) {
def repo = new RepositoryBuilder()
.setGitDir(new File(project.rootDir, '/.git'))
.readEnvironment()
.build()
def version = repo.getRef('HEAD').getObjectId().name
def isClean = Git.wrap(repo).status().call().isClean()
return version + (isClean ? '' : '.dirty')
}
}
@barend
Copy link
Author

barend commented Apr 19, 2016

To invoke this in your build.gradle: "${GitFunctions.headCommitAndStatus(project)}".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment