Skip to content

Instantly share code, notes, and snippets.

@Trogious
Last active August 6, 2024 06:29
Show Gist options
  • Save Trogious/fbf69afee2ff049951ac6930de7bd0da to your computer and use it in GitHub Desktop.
Save Trogious/fbf69afee2ff049951ac6930de7bd0da to your computer and use it in GitHub Desktop.
How to get latest git tag or commit ID (gradle)

How to get latest git tag or commit ID (gradle)

The following will give you the latest git tag name (if the HEAD is tagged) or latest commit ID otherwise. The getAppVersion function returns the end value.

Why is this useful?

I use it to name packages of my builds and other versioning purposes in my Android projects.

The code:

def getAppVersion = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = stdout
    }
    def commitId = stdout.toString().replace("\n", "").replace("\r", "").trim()
    stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'tag', '--points-at', commitId
        standardOutput = stdout
    }
    def tagName = stdout.toString().replace("\n", "").replace("\r", "").trim()
    def versionName = 'git-' + commitId
    if (tagName != null && "" != tagName) {
        versionName = tagName
    }
    return versionName
}
@4shutosh
Copy link

4shutosh commented Aug 6, 2024

A KTS version

fun getGitTag(): String {
  val stdout = ByteArrayOutputStream()
  val stdout2 = ByteArrayOutputStream()
  exec {
    workingDir("change directory to root")
    commandLine("git", "rev-parse", "--short", "HEAD")
    standardOutput = stdout
  }
  val commitId = stdout.toString().replace("\n", "").replace("\r", "").trim()
  exec {
    workingDir("change directory to root")
    commandLine("git", "tag", "--points-at", commitId)
    standardOutput = stdout2
  }
  val tagName = stdout2.toString().replace("\n", "").replace("\r", "").trim()
  var versionName = commitId
  if (tagName.isNotEmpty()) {
    versionName = tagName
  }
  return versionName
}

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