Skip to content

Instantly share code, notes, and snippets.

@thomasleveil
Last active March 15, 2016 15:04
Show Gist options
  • Save thomasleveil/889c5761214e8dcf3625 to your computer and use it in GitHub Desktop.
Save thomasleveil/889c5761214e8dcf3625 to your computer and use it in GitHub Desktop.
Android Gradle auto version

Android projet auto-version update

This gradle snippet setup auto management of versionCode and versionName using tags found on your git repository.

  • When building an apk from a commit tagged v1.4.2, then versionName will be v1.4.2
  • When building an apk from a commit abcd123 which is the 3rd one after tag v1.5.7, then versionName will be v1.5.7-3-gabcd123
  • versionCode is automatically handled given versionName value

How to bump up the version number?

Just add a tag in your git repository name like v1.4.2.

// ... ususal stuff
/**
* Compute versionCode from a version name.
*
* Expected version format:
* - v1.2.4
* - v1.2.4-45
* - v1.2.4-45-*
*
* Test regular expression at https://regex101.com/r/tJ3hE2/2
*
* @param version name
* @return versionCode value as an integer
*/
def buildVersionCode(version) {
def m = version =~ /^v([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9]+).*)?/
assert m.matches()
def major = m.group(1).toInteger()
def minor = m.group(2).toInteger()
def patch = m.group(3).toInteger()
def nbCommits = m.group(4) == null ? 0 : m.group(4).toInteger()
(major * 100000000) + (minor * 1000000) + (patch * 1000) + nbCommits
}
/*
* Gets the version name from the latest Git tag.
*
* Assumes tags start with `v` followed with 3 numbers as in {major}.{minor}.{patch}.
*
* Returns the commit description provided by the `git describe --tag` command. I.E.: the 8th
* commit after tag `v1.3.0`, having hash `6648e7b8c89b2d0b7fcfaaff25ab40ab610eb2a7` will produce:
* `v1.3.0-8-g6648e7b`
*
* See https://git-scm.com/docs/git-describe#_examples
*/
def getVersionName = { ->
def stdout = new ByteArrayOutputStream()
exec {
commandLine "git describe --tag --match v[0-9]*.*.*".tokenize(' ')
standardOutput = stdout
}
return stdout.toString().trim()
}
android {
// ...
defaultConfig {
// ...
versionName = getVersionName()
versionCode = buildVersionCode(versionName)
}
// ...
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment