Skip to content

Instantly share code, notes, and snippets.

@danielgallegovico
Last active March 28, 2019 16:22
Show Gist options
  • Save danielgallegovico/d7c2d8e3b33d843b5454dfe2ed363d40 to your computer and use it in GitHub Desktop.
Save danielgallegovico/d7c2d8e3b33d843b5454dfe2ed363d40 to your computer and use it in GitHub Desktop.
Utility methods for automated generation of versionName & versionCode in Android apps using semantic versioning tags
/**
* Get the version name from the latest Git tag.
* e.g. last tag v3.0.1 -> versionName 3.0.1
*/
def computeVersionName() {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', "--git-dir=${rootProject.rootDir}/.git", "--work-tree=${rootProject.rootDir}", 'describe', '--abbrev=0', '--tags'
standardOutput = stdout
}
return stdout.toString().trim().replaceAll("v", "")
}
/**
* Generate the version code by combining in integer format [targetSDKVersion][versionName].
* [VersionName] follows the pattern: XYYZZ taking into account that
* when minor/patch is only a one digit number, we complete the pattern with zeros.
*
* e.g. targetSdkVersion 25 and versionName 3.1.3 -> versionCode 2530103
*
* NOTE: the maximum versionCode allowed by Google Play is 2100000000
*/
def computeVersionCode() {
def versionArray = computeVersionName().split("\\.")
String major = versionArray[0]
String minor = versionArray[1].length() < 2 ? "0" + versionArray[1] : versionArray[1]
String patch = versionArray[2].length() < 2 ? "0" + versionArray[2] : versionArray[2]
String versionCode = "$project.properties.target_sdk_version" + major + minor + patch
return versionCode.toInteger()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment