Published on

How to Get a Projects Git Hash with Gradle

Authors

Today I wanted to configure my app so that it could log out the Git hash of the current code that is being run. This hash should only be output on startup. This approach is really useful as it makes it very easy to tie a piece of running code back to a particular commit.

To set this up I had to make some changes to my build.gradle file:

buildscript {
    // ...
    repositories {
        mavenCentral()
        gradlePluginPortal()
    }
    dependencies {
        // ...
        classpath("gradle.plugin.de.fuerstenau:BuildConfigPlugin:1.1.4")
    }
}

// ...

apply plugin: 'de.fuerstenau.buildconfig'

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




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

sourceSets.main.java.srcDirs += "build/gen/buildconfig/src/main"

This will generate a class called BuildConfig.java which will be under build/gen/buildConfig/src/main/de/fuerstenau/buildconfig/BuildConfig.java

I then updated a @PostContruct method I have in my spring bean configuration which outputs an info log when the app starts:

// ...

@Configuration
class AppConfig {

    // ... my bean configs here

    @PostConstruct
    fun init() {
        logger.info("==================================================================================")
        logger.info("Version hash: [${BuildConfig.GitHash}]")
        // ... any other info you want to logout on startup
        logger.info("==================================================================================")
    }
}

The Github repo for this plugin which includes documentation on it can be found here.