-
-
Save saucaca/0a239a67c7b4ac97abf474e520728900 to your computer and use it in GitHub Desktop.
Smart versionName and versionCode for android Gradle build evaluation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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