74

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?

6 Answers 6

169

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.

4
  • HI, i'am getting this Error:CreateProcess error=2, The system cannot find the file specified,,any leads my co debase is on GitLabs
    – Haroon
    Jun 1, 2016 at 11:12
  • @Haroon: Check to make sure the path to git is in your PATH environment variable. Check this by opening a new command prompt/terminal and typing "git --version"
    – Paul
    Jun 2, 2016 at 14:59
  • Thanks @Paul exactly what you have written i did , just made the git available to environment variable
    – Haroon
    Jun 6, 2016 at 8:33
  • The problem with this is that after making a commit git the whole app needs to be rebuilt. Mar 25, 2021 at 11:58
23

One ideal solution could be grabbing the version from the git status of the project. This way the versioning does not rely on you remembering to increase a variable, or change any text in the gradle or config files. Another advantage is the traceability of the version name and code to one specific code status.

You can find one descriptive example in http://ryanharter.com/blog/2013/07/30/automatic-versioning-with-git-and-gradle/

The idea is getting the git info with the getVersionName function, and use that function in the gradle script:

/*
 * Gets the version name from the latest Git tag
 */
def getVersionName = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

kts:

val gitDescribe: String by lazy {
    val stdout = ByteArrayOutputStream()
    rootProject.exec {
        commandLine("git", "describe", "--tags")
        standardOutput = stdout
    }
    stdout.toString().trim()
    /* 'g' doesn't belong to the commit id and stands for 'git'
       v0.1.9-1-g3a259e0 -> v0.1.9-1-3a259e0
       if you like this to be removed then */
    //.replace("-g", "-") 
}

Of course, you need to have command line git available (as the command git describe --tags will be executed to generate the information).

Another approach (based also in getting the version info from git) could be externalizing that logic to a gradle plugin - such as:

The one to use will depend on which kind of versioning policy you want to apply.

1
  • 2
    Very nice idea, I'll add the kotlin counterpart for comfortability
    – elect
    Mar 11, 2021 at 7:35
20

add following code to your build.gradle

def gitCommitHash = 'git rev-parse --verify --short HEAD'.execute().text.trim()
defaultConfig{
    ... otherConfigs
    buildConfigField("String", "GIT_HASH", "\"${gitCommitHash}\"")
}

now you can get git hash by BuildConfig.GIT_HASH

have fun

2
  • Appreciate how concise this answer is. Thanks :)
    – Victor Ude
    Jan 27, 2021 at 18:54
  • Appreciate. Shortest and most direct answer, thus most fitting in my case. Jan 22, 2023 at 13:12
10

I created a Gradle plugin to do this for you. The project and full instructions are at https://github.com/lessthanoptimal/gversion-plugin

To use it add the following to your build.gradle file

plugins {
  id "com.peterabeles.gversion" version "1.2.4"
}

gversion {
  srcDir = "src/main/java/"
  classPackage = "com.your.package"
  className = "MyVersion"                   // optional. If not specified GVersion is used
  dateFormat   = "yyyy-MM-dd'T'HH:mm:ss'Z'" // optional. This is the default
  timeZone     = "UTC"                      // optional. UTC is default
}

Now you just need to run the gradle task 'createVersionFile' to create the file. You might want to consider adding the following line to your gradle project project.compileJava.dependsOn(createVersionFile) This will cause it to generate the file every time Gradle builds the project. See the website above for Android instructions.

Here's what the file looks like

/**
 * Automatically generated file containing build version information.
 */
public class MyVersion {
    public static final String MAVEN_GROUP = "com.your";
    public static final String MAVEN_NAME = "project_name";
    public static final String VERSION = "1.0-SNAPSHOT";
    public static final int GIT_REVISION = 56;
    public static final String GIT_SHA = "a0e41dd1a068d184009227083fa6ae276ef1846a";
    public static final String BUILD_DATE = "2018-04-11T12:19:03Z";
    public static final long BUILD_UNIX_TIME = 1523449143116L;
}

You might also want to add the version file to your .gitignore since it is autogenerated and you don't want it in git.

1
  • Awesome! I used the reflection to avoid visual warnings and errors, but that's just my preference. I'd also love it if this had git short rev out of the box and also a resource file generation instead of a class.
    – edin-m
    Feb 4, 2020 at 15:24
3

Also worth looking at grgit - Groovy/Gradle Git, which can help simplify extraction of information, including Git commit-hashes, in a Gradle script.

1
  • This worked quite help, but there were memory issues this plugin was used in a mono repository and the transitive jgit dependency conflicted with another project.
    – 030
    Dec 12, 2018 at 22:32
1

This is a solution for Kotlin DSL (build.gradle.kts) derived from Charlie Lee's answer:

task<Exec>("MyTask") {
    doLast {
        commandLine("git")
            .args("rev-parse", "--verify", "--short", "HEAD")
            .workingDir(rootProject.projectDir)
    }
}

Another approach using the Java standard ProcessBuilder API:

tasks.create("MyTask") {
    val command = "git rev-parse --verify --short HEAD"
    doLast {
        val process = ProcessBuilder()
            .command(command.split(" "))
            .directory(rootProject.projectDir)
            .redirectOutput(Redirect.INHERIT)
            .redirectError(Redirect.INHERIT)
            .start()
        process.waitFor(60, TimeUnit.SECONDS)
        val result = process.inputStream.bufferedReader().readText()
        println(result)
    }
}

For more information see:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.