Skip to content

Instantly share code, notes, and snippets.

@JonasGroeger
Last active January 23, 2024 07:55
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save JonasGroeger/7620911 to your computer and use it in GitHub Desktop.
Save JonasGroeger/7620911 to your computer and use it in GitHub Desktop.
Gradle: Read git commit hash.
def getCheckedOutGitCommitHash() {
def gitFolder = "$projectDir/.git/"
def takeFromHash = 12
/*
* '.git/HEAD' contains either
* in case of detached head: the currently checked out commit hash
* otherwise: a reference to a file containing the current commit hash
*/
def head = new File(gitFolder + "HEAD").text.split(":") // .git/HEAD
def isCommit = head.length == 1 // e5a7c79edabbf7dd39888442df081b1c9d8e88fd
// def isRef = head.length > 1 // ref: refs/heads/master
if(isCommit) return head[0].trim().take(takeFromHash) // e5a7c79edabb
def refHead = new File(gitFolder + head[1].trim()) // .git/refs/heads/master
refHead.text.trim().take takeFromHash
}
// You can also use it somewhere else, not just in jar files.
jar {
// ...
classifier = getCheckedOutGitCommitHash()
// ...
}
@MajoroMask
Copy link

Googled to this beautiful script, thanks a lot @JonasGroeger!

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