Created
April 19, 2016 13:08
-
-
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().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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' | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To invoke this in your build.gradle:
"${GitFunctions.headCommitAndStatus(project)}"
.