Gradle script to autoversion and include the commit hash in Android

Shatazone picture Shatazone · Feb 13, 2015 · Viewed 22.7k times · Source

I need to write a gradle script to auto version my application on every commit. I need to also include the commit hash as a reference in the application for testers.

I am confused how auto versioning usually work. Can someone explain the autoversioning process?

Answer

Paul picture Paul · Jan 27, 2016

I encountered a similar problem, but did not want to modify the versionName to include the git hash. We wanted to keep that as something like 1.2.2, but still have the possibility of displaying the git hash in the UI.

I modified the code from the other answer here to use the buildConfigField task to generate a BuildConfig.GitHash value that can be referenced in the Java code.

Add this above the android section of your module's build.gradle file:

def getGitHash = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

Then add the following line to the defaultConfig section of the android section of the build.gradle, i.e. below versionName:

buildConfigField "String", "GitHash", "\"${getGitHash()}\""

This generates the following line in the auto-generated BuildConfig.java file:

// Fields from default config.
public static final String GitHash = "e61af97";

Now you can get the git hash in your Java code with BuildConfig.GitHash.