Skip to content

Instantly share code, notes, and snippets.

@JonasGroeger
Last active December 8, 2024 11:45
Show Gist options
  • Select an option

  • Save JonasGroeger/7620911 to your computer and use it in GitHub Desktop.

Select an option

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()
// ...
}
@tomqsm
Copy link
Copy Markdown

tomqsm commented Oct 19, 2015

@paul-eeoc
Copy link
Copy Markdown

That function is when you do not have git executable in your path. If you do have git in your path, you can use this instead:

def getCheckedOutGitCommitHash() {
  'git rev-parse --verify --short HEAD'.execute().text.trim()
}

Same functionality, no?

@nicolas-f
Copy link
Copy Markdown

After a while refs/heads/ folder is empty because git will pack them into packed-refs file. So this script work only for small unpacked git repository.

@jhyry-gcpud
Copy link
Copy Markdown

This is awesome, thanks so much for sharing!

@ikstewa
Copy link
Copy Markdown

ikstewa commented Aug 5, 2021

You can use grgit as a plugin to support packed-refs as mentioned:

plugins {
    id 'org.ajoberstar.grgit' version '4.1.0'
}

def getCheckedOutGitCommitHash() {
    grgit.head().abbreviatedId
}

// You can also use it somewhere else, not just in jar files.
jar {
    // ...
    classifier = getCheckedOutGitCommitHash()
    // ...
}

@stanio
Copy link
Copy Markdown

stanio commented Apr 14, 2023

Looks very nice. One detail one may need to account for is the exact location of the .git directory:

Higher level SCMs may provide and manage additional information in the $GIT_DIR.

Then there also could be a .git file vs. directory:

Note: Also you can have a plain text file .git at the root of your working tree, containing gitdir: <path> to point at the real directory that has the repository. This mechanism is often used for a working tree of a submodule checkout...

@MajoroMask
Copy link
Copy Markdown

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