Autoincrement Versioncode with Gradle Extra Properties

Autoincrement VersionCode with gradle extra properties

I would like to read the versionCode from an external file

I am sure that there are any number of possible solutions; here is one:

android {
compileSdkVersion 18
buildToolsVersion "18.1.0"

def versionPropsFile = file('version.properties')

if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()

versionProps.load(new FileInputStream(versionPropsFile))

def code = versionProps['VERSION_CODE'].toInteger() + 1

versionProps['VERSION_CODE']=code.toString()
versionProps.store(versionPropsFile.newWriter(), null)

defaultConfig {
versionCode code
versionName "1.1"
minSdkVersion 14
targetSdkVersion 18
}
}
else {
throw new GradleException("Could not read version.properties!")
}

// rest of android block goes here
}

This code expects an existing version.properties file, which you would create by hand before the first build to have VERSION_CODE=8.

This code simply bumps the version code on each build -- you would need to extend the technique to handle your per-flavor version code.

You can see the Versioning sample project that demonstrates this code.

How to autoincrement versionCode in Android Gradle

I have decided for second option - to parse AndroidManifest.xml. Here is working snippet.

task('increaseVersionCode') << {
def manifestFile = file("AndroidManifest.xml")
def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def versionCode = Integer.parseInt(matcher.group(1))
def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
if (task.name == 'generateReleaseBuildConfig') {
task.dependsOn 'increaseVersionCode'
}
}

versionCode is released for release builds in this case. To increase it for debug builds change task.name equation in task.whenTaskAdded callback.

Auto increment versioncode only on releases

You could try something like that

import java.util.regex.Pattern    
task('increaseVersionCode') << {

... // You could code in your increment system, for eg

// Using build.gradle (recommended)
def buildFile = file("build.gradle")
def pattern = Pattern.compile("versionCode\\s+(\\d+)")
def manifestText = buildFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def versionCode = Integer.parseInt(matcher.group(1))
def manifestContent = matcher.replaceAll("versionCode " + ++versionCode)
buildFile.write(manifestContent)

// Using manifest
def manifestFile = file('AndroidManifest.xml')
def matcher = Pattern.compile('versionCode=\"(\\d+)\"')
.matcher(manifestFile.getText())
matcher.find()
def manifestContent = matcher.replaceAll('versionCode=\"' +
++Integer.parseInt(matcher.group(1)) + '\"')
manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
if (task.name == 'assembleQaRelease') {
task.dependsOn 'increaseVersionCode'
}
}

You can adapt the 'assembleQaRelease' to increment version code to the wanted task.

Autoincrement VersionCode Gradle task not executing as expected

In groovy a division results in a BigDecimal if the operands are of type Integer, while in Java they are of the type int.

When fileVersionCode is 11, the result:

(fileVersionCode / 10) 

translates to 1 in Java but to 1.1 in Groovy. In order to fix this, just add a (int) cast to trim the unnecessary decimal part.

Version increment using gradle task

Here is an example task:

version='1.0.0'  //version we need to change

task increment<<{
def v=buildFile.getText().find(version) //get this build file's text and extract the version value
String minor=v.substring(v.lastIndexOf('.')+1) //get last digit
int m=minor.toInteger()+1 //increment
String major=v.substring(0,v.length()-1) //get the beginning
//println m
String s=buildFile.getText().replaceFirst("version='$version'","version='"+major+m+"'")
//println s
buildFile.setText(s) //replace the build file's text
}

Run this task several times and you should see the version change.

A variant:

version='1.0.0'

task incrementVersion<<{
String minor=version.substring(version.lastIndexOf('.')+1)
int m=minor.toInteger()+1
String major=version.substring(0,version.length()-1)
String s=buildFile.getText().replaceFirst("version='$version'","version='"+major+m+"'")
buildFile.setText(s)
}

Gradle Increment VersionCode for Release Build

Everything a task should do when it gets executed needs to go into a task action. A task action is added with doLast { /* code goes here */ }. Code outside a task action configures the task, and gets run on every build invocation as part of "parsing" the build script.

android studio gradle version increment

So after a few hours of trial and error I figured out a way this can be done.

android {
compileSdkVersion 19
buildToolsVersion "19.0.3"

def versionPropsFile = file('version.properties')

if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()

versionProps.load(new FileInputStream(versionPropsFile))

def value = 0

def runTasks = gradle.startParameter.taskNames
if ('assemble' in runTasks || 'assembleRelease' in runTasks || 'aR' in runTasks) {
value = 1;
}

def code = versionProps['VERSION_CODE'].toInteger() + value
def name = versionProps['VERSION_NAME'].toInteger() + 1

versionProps['VERSION_CODE']=code.toString()
versionProps['VERSION_NAME']=name.toString()
versionProps.store(versionPropsFile.newWriter(), null)

defaultConfig {
versionCode code
versionName "1.2." + name
minSdkVersion 14
targetSdkVersion 19
}
} else {
throw new GradleException("Could not read version.properties!")
}

signingConfigs {
debug {
...
}
releaseKey {
...
}
}

buildTypes {
debug {
...
}

release {
...
}
}

lintOptions {
abortOnError false
}
}

So what I'm doing is to check if I'm doing a assebleRelease task or not. If I am I increase the versionCode with +1.

Hope this helps anyone else.



Related Topics



Leave a reply



Submit