Skip to content

Instantly share code, notes, and snippets.

@mrolcsi
Last active June 21, 2020 13:44
Show Gist options
  • Save mrolcsi/588d5dd7a309fab501fc to your computer and use it in GitHub Desktop.
Save mrolcsi/588d5dd7a309fab501fc to your computer and use it in GitHub Desktop.
Version code and name generation using Gradle
ext.makeVersionCode = { ->
try {
def code = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', 'HEAD', '--count'
standardOutput = code
}
return Integer.parseInt(code.toString().trim())
}
catch (ignored) {
logger.error(ignored.printStackTrace())
return -1
}
}
ext.makeVersionNameRelease = { ->
try {
def lastTag = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', '--tags', '--no-walk', '--max-count=1'
standardOutput = lastTag
}
def lastCommits = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', lastTag.toString().trim() + '..HEAD', '--count'
standardOutput = lastCommits
}
def versionName = new ByteArrayOutputStream()
exec {
commandLine 'git', 'describe', '--tags', '--abbrev=0'
standardOutput = versionName
}
return versionName.toString().trim() + '.' + lastCommits.toString().trim()
}
catch (ignored) {
logger.error(ignored.printStackTrace())
return null
}
}
ext.currentBranch = { ->
try {
def currentBranch = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
standardOutput = currentBranch
}
return currentBranch.toString().trim()
}
catch (ignored) {
logger.error(ignored.printStackTrace())
return null
}
}
ext.makeVersionNameDebug = { ->
return versionName + '/' + currentBranch
}
@mrolcsi
Copy link
Author

mrolcsi commented Jun 15, 2016

Usage:

apply from: 'URL_TO_RAW'

android {
    defaultConfig {
        versionCode makeVersionCode()
        versionName makeVersionNameRelease()
    }
}

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