Skip to content

Instantly share code, notes, and snippets.

@StuStirling
Last active March 3, 2018 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StuStirling/21766d233d01c1d6fe5f1b9ade99fc30 to your computer and use it in GitHub Desktop.
Save StuStirling/21766d233d01c1d6fe5f1b9ade99fc30 to your computer and use it in GitHub Desktop.
Using GIT to Version the Android App
def getVersionName = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--match', "dev/[0-9]*.[0-9]*.[0-9]*", "--abbrev=0", 'HEAD'
standardOutput = stdout
}
return stdout.toString().replace("version/","").trim()
}
catch (ignored) {
return null
}
}
def computeVersionCode = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', 'HEAD', "--count"
standardOutput = stdout
}
return stdout.toString().trim().toInteger()
}
catch (ignored) {
return null
}
}
android {
//...
defaultConfig {
//...
versionCode 1
versionName getVersionName()
//...
}
applicationVariants.all { variant ->
def versionCode = variant.mergedFlavor.versionCode
variant.outputs.all { output ->
if (variant.buildType.name != "debug") {
versionCode = computeVersionCode()
output.setVersionCodeOverride(versionCode)
}
}
changeApkFileName(variant,versionCode)
}
//..
}
/**
* Changes the name of the APK after it has been built.
* */
static def changeApkFileName(variant,versionCode) {
variant.outputs.all { output ->
def flavor = ""
// input some flavor dependent string into the apk file name
if (variant.name.contains('prod'))
flavor = 'production'
else if (variant.name.contains('dev'))
flavor = 'development'
def newName = '{app_name}_v' + variant.versionName + '_' +
versionCode + '-' + flavor + "_" + variant.buildType.name + '.apk'
outputFileName = newName
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment