Skip to content

Instantly share code, notes, and snippets.

@andrewvmail
Forked from tprochazka/build.gradle
Created July 3, 2019 01:14
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 andrewvmail/c106773f1ee0400d2d80a94977d0d385 to your computer and use it in GitHub Desktop.
Save andrewvmail/c106773f1ee0400d2d80a94977d0d385 to your computer and use it in GitHub Desktop.
Smart versionName and versionCode for android Gradle build evaluation
/**
* Will return version from properties file and replace -SNAPSHOT by GIT commit hash
* to recognize origin commit for the every build.
*/
project.ext.evalVersionName = {
def ideBuild = project.properties['android.injected.invoked.from.ide']
if (ideBuild) {
logger.info("IDE build");
return "dev"
} else if (project.VERSION.toUpperCase().contains("SNAPSHOT")) {
logger.info("SNAPSHOT build");
if (checkUncommitedChanges()) {
logger.warn("You have uncommited changes!")
}
return project.VERSION.toUpperCase().replace("SNAPSHOT", getGitHash())
}
if (checkUncommitedChanges()) {
logger.error("You have uncommited changes!")
}
return project.VERSION;
}
/**
* Creates versionCode from number of commits in GIT
*/
project.ext.evalVersionCode = {
// number of commits from HEAD to oldest one, useful for releasing from one branch only
// def p = Runtime.getRuntime().exec("git rev-list HEAD --count")
// number of commit in all branches together (also dead one)
def p = Runtime.getRuntime().exec("git rev-list --all --count")
def result = p.waitFor()
if (result != 0) {
return 0 // no git revisions
}
return p.getInputStream().readLines().get(0).toInteger()
}
/**
* Renames APK name to contain version, build number and commit hash.
*/
project.ext.renameApk = { variant ->
def file = variant.outputFile
def gitHash = getGitHash()
def name = project.parent.name + "-" + project.name + "-" +
variant.mergedFlavor.versionName + "-" +
variant.mergedFlavor.versionCode + "-" +
gitHash + "-" + variant.mergedFlavor.name + "," + variant.buildType.name
variant.outputFile = new File(file.parent, name + ".apk")
}
/**
* Return last commit git hash string.
*/
project.ext.getGitHash = {
// git hash
def command = Runtime.getRuntime().exec("git rev-parse --short HEAD")
def result = command.waitFor()
return (result == 0) ? command.inputStream.text.trim() : "nogit"
}
/**
* Check if project has uncommited changes
*/
project.ext.checkUncommitedChanges = {
def command = Runtime.getRuntime().exec("git diff-index --quiet HEAD")
return command.waitFor() == 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment