Increment version on project build

android, android-gradle-plugin, android-studio, build.gradle, gradle

Solution

Quoting from my book:

Since the `android:versionCode` is a monotonically increasing integer, one approach for automating it is to simply increment it on each build. While this may seem wasteful, two billion builds is a lot of builds, so a solo developer is unlikely to run out. Synchronizing such `versionCode` values across a team will get a bit more complex, but for an individual case (developer, build server, etc.), it is eminently doable using Groovy.

The `Gradle/HelloVersioning` sample project uses a `version.properties` file as the backing store for the version information:

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!")
}

First, we try to open a `version.properties` file and fail if it does not exist, requiring the developer to create a starter file manually:

VERSION_CODE=1

Of course, a more robust implementation of this script would handle this case and supply a starter value for the developer.

The script then uses the read-the-custom-properties logic illustrated in the preceding section [NOTE: of the book, not included here] to read the existing value... but it increments the old value by 1 to get the new code to use. The revised code is then written back to the properties file before it is applied in the `defaultConfig` block.

In this case, the script throws a `GradleException` to halt the build if the `version.properties` file could not be found or otherwise could not be read.

Problem

In Android Studio I have in `build.gradle` default info about application version: ``` android { defaultConfig { versionCode 24 versionName "0.1 beta" } } ``` How can I increment the `versionCode` automatilcally on each project compilation?

Original source