Automation of unique version code in android apk file name

Its really been a very long time since I have written something here. Call it due to lack of time or whatever, but the end result was that it just got put on hold.

I have been working on Android lately (well for sometime now really) and some interesting technologies like RxJava to help me with some heavy-duty tasks, Retrofit libs to help me talk to the backend effectively and some Cupboard libraries helping me manage my local database. This combo has made it all the more interesting and has kept me occupied during most of my time.

But a very interesting issue that I bumped into and the solution that I thought would be optimum and the fact that it could help many more developers who are looking at some solution that I was looking for motivated me that I share it here.

I was looking at some way to make sure that I automate my version code and make it incremental and unique without having to bother to keep track of what I was doing. I also wanted to have some way to identify uniquely what release to customer was built on what code-base. Well all this made me think of many things. Most avenues led me to solve one part of the issue individually. But hey, what if we could just use the commit id and / or the commit count effectively. But I needed to find a way to integrate it in the gradle file. After quite sometime spent on searching around, this is what I came across.

Below is a sample of the build.gradle(Most initiated in the Android world would find this pretty self-explanatory, so am not going to bore you with it again).

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
def gitCommitCount = "git rev-list HEAD --count".execute().text.trim().toBigInteger()
project.ext.set("versionCode", gitCommitCount)
project.ext.set("versionNameSuffix", "(${gitCommitCount})")

defaultConfig {
applicationId ""
minSdkVersion 15
targetSdkVersion 25
versionCode project.versionCode
versionName "1.0"
versionNameSuffix project.versionNameSuffix
setProperty("archivesBaseName", "MyProject-$versionName")

signingConfigs {
config {

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
signingConfig signingConfigs.config

packagingOptions {
applicationVariants.all { variant ->
variant.outputs.each { output ->
output.outputFile = new File(
output.outputFile.parent,".apk", "-${variant.versionName}.apk"))

The good thing about this solution is that one can customize the above for other git commands too like the git commit id as the version name suffix.