Automatically increasing versionCode with Gradle – Followup
Wednesday, February 12th, 2014This article is a followup to the original that can be found here.
As a normal use case the original article provides a good way not to worry about increasing the version number. The only drawback is that the number is really increased every time you compile the source code. This results in jumping versionCodes in the commit history. For instance lets say you checked out the App with the versionCode set to 3. After compiling the application for several times, until you deem it stable, you might check it in with a versionCode of 15. It would be more desirable to increase it just by one.
To achieve this we are going to base our new implementation on the committed state of the AndroidManifest.xml (here for the DriveNow project).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def getManifestVersionCodeFromGitHead() { def stdout = new ByteArrayOutputStream() exec{ commandLine 'git', 'show', 'HEAD:DriveNow/src/main/AndroidManifest.xml' standardOutput = stdout; } def manifestTextFromRepository = stdout.toString().trim() def pattern = java.util.regex.Pattern.compile("versionCode=\"(\\d+)\"") def matcher = pattern.matcher(manifestTextFromRepository) matcher.find() def version = Integer.parseInt(matcher.group(1)) println sprintf("Previous versionCode is %d", version) return version } |
To incorporate this into the normal build process, we can basically use the same methodology we used in the original version. If we want to go a step further and don’t increase the version if we are running on our integration server, we can also alter the task definition a little bit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
task increaseVersionCode << { def manifestFile = file("src/main/AndroidManifest.xml") def manifestText = manifestFile.getText() def pattern = java.util.regex.Pattern.compile("versionCode=\"(\\d+)\"") def matcher = pattern.matcher(manifestText) matcher.find() def versionCode = getManifestVersionCodeFromGitHead() def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"") manifestFile.write(manifestContent) println sprintf("Wrote version %d", versionCode) } tasks.whenTaskAdded { theTask -> if (!Boolean.getBoolean('buildConfig.keepVersionCode') && theTask.name == 'generateReleaseBuildConfig') { theTask.dependsOn 'increaseVersionCode' } } |
Running the build now with ./gradlew assemble -D buildConfig.keepVersionCode=true will build the project without increasing the versionCode.