Chesire

Chesite

A tech blog for any technologies that take my fancy.

2-Minute Read

Updating your version name on Android is easy and probably takes you less than 5 minutes, but we write software, so why manually do it when we can automate it?

Using git tags we can easily automate it, so every time you tag, it will update your version name to match.

The Code

Ok, heres what you came for.

First we are going to write a Gradle closure to get our version name. Add this somewhere your module build.gradle can access, usually I will put it within the projects build.gradle.

ext.retrieveVersionName = {
}

Next we need to tell the closure to run the git command to get the tag data. Add an exec block to execute git describe --tags --always (more information here) on the command line, with the standard output going into the stdout variable.

    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags', '--always'
        standardOutput = stdout
    }

Lastly we need to do a bit of manipulation on the value that comes back, as using git describe will give you more information than we need.

Do any manipulation required (here i’ve just substringed up to the first -), and return the result.

    def fullTag = stdout.toString().trim()
    return fullTag.contains('-') ? fullTag.substring(0, fullTag.indexOf('-')) : fullTag

Finally put it all together and you have this

ext.retrieveVersionName = {
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags', '--always'
        standardOutput = stdout
    }

    def fullTag = stdout.toString().trim()
    return fullTag.contains('-') ? fullTag.substring(0, fullTag.indexOf('-')) : fullTag
}

Then within your modules build.gradle you can call this closure we have created to set the versionName.

versionName "${retrieveVersionName()}"

Other Uses

Outside of just updating the version name, we can update the versionCode using a very similar style, if you do weekly releases to the play store and find remembering to update your versionCode each time a pain this is for you.

How you parse the returned tag is defined by how you do your versioning, but if you do something such as semver, given the version 1.2.0.40 you could use the below.

    def fullTag = stdout.toString().trim()
    if (!fullTag.contains('.')) {
        return 1
    } else if (fullTag.contains('-')) {
        return fullTag.substring(fullTag.lastIndexOf('.') + 1, fullTag.indexOf('-')).toInteger()
    } else {
        return fullTag.substring(fullTag.lastIndexOf('.') + 1, fullTag.length()).toInteger()
    }
versionCode retrieveVersionCode()

A complete code example of everything explained can be found on GitHub.

Say Something

Comments

Recent Posts

categories