Automagically generate versionCode and versionName of an Android build

Today a colleague of mine pointed me to grgit (a wrapper over jGit) when asked about how to deal with Android versionCode. Version Your App is a critical component of your app upgrade and maintenance strategy. Doing so manually is error prone and cumbersome.

Moritz told me to have a look at build.gradle used to build Android Calendar Widget.

The essential parts are backed by grgit the library mentioned above:

buildscript {
  ...
  dependencies {
      classpath 'org.ajoberstar:grgit:1.9.2'
  }
}

Two convenient methods generate a monotonious increasing number and a short hash of the current commit:

static getVersionCodeInteger() {
  try {
    def git = org.ajoberstar.grgit.Grgit.open()
    def versionCode = git.log().size()
    git.close()
    return versionCode
  } catch (ignored) {
    return 1
  }
}

static getVersionNameExtension() {
  try {
    def git = org.ajoberstar.grgit.Grgit.open()
    def versionNameSuffix = "-${git.head().getAbbreviatedId(8)}"
    git.close()
    return versionNameSuffix
  } catch (ignored) {
    return ""
  }
}

This two functions are used within the defaultConfig of our Android app:

android {
  ...
  defaultConfig {
    versionName '0.4.4' + getVersionNameExtension()
    versionCode getVersionCodeInteger()
    ...
  }
}

We always have the commit hash coded into the versionName to identify every version available in the wild and an automagically generated versionCode.

Show Comments