Skip to content

Instantly share code, notes, and snippets.

@thynson
Last active August 29, 2015 14:20
Show Gist options
  • Save thynson/db615ad63a819841224e to your computer and use it in GitHub Desktop.
Save thynson/db615ad63a819841224e to your computer and use it in GitHub Desktop.
Automated Android version code & name
// Git tag must in format of vA.B.CrcD, e.g. v1.0 or v1.0.2rc4,
// where A, B, C, D is major version code, minor version code,
// fix version code and RC number respectively.
// Minor, fix and rc number are optional, and rc number is simply
// ignored when calculating version code
//
// In build.gradle:
//
// apply from: './path/to/version.gradle'
//
// android {
// ...
// defaultConfig {
// versionCode getVersionCodeFromGit()
// versionName getVersionNameFromGit()
// }
// ...
// }
import java.util.regex.Matcher
import java.util.regex.Pattern
ext {
getVersionCodeFromGit = { ->
try {
String versionName = getVersionNameFromGit()
Pattern p = Pattern.compile('^v([0-9]{1,2})(?:\\.([0-9]{1,2}))?(?:\\.([0-9]{1,2}))?(?:rc([0-9]{1,2}))?-.*');
Matcher m = p.matcher(versionName);
if (!m.matches()) return new RuntimeException("version format invalid");
int major = Integer.parseInt(m.group(1)), minor = 0, fix= 0;
if (m.group(2) != null) {
minor = Integer.parseInt(m.group(2))
if (m.group(3) != null) {
fix = Integer.parseInt(m.group(3))
}
}
return major * 10000 + minor * 100 + fix;
} catch(ignored) {
return Integer.MAX_VALUE;
}
}
getVersionNameFromGit = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags', '--dirty'
standardOutput = stdout
}
return stdout.toString().trim()
}
catch (ignored) {
return "undefined";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment