Git integration for Android Gradle projects

PUBLISHED ON MARCH 16, 2017 — ANDROID, GIT, GRADLE

For an Android Gradle project, it is useful to embed in the app the git revisions that were used to produce a build. For a project composed of multiple modules that are versioned independently, such as a main module and several library modules, such string should describe the git revision of all the projects.

To build it, you can use the gradle-git groovy library in your Gradle script. Add the following to your project-level build script:

buildscript {
    dependencies {
        classpath 'org.ajoberstar:gradle-git:1.6.0'
    }
}

Then, in your app main module, add the following:

def gitRevisionsProjects = ["app", "module1", "module2"] // list here the module names
def gitRevisions = gitRevisionsProjects.collect { project ->
    def p = rootProject.allprojects.find { it.name == project }
    def git = Grgit.open(currentDir: p.projectDir)
    try {
        def revision = git.head().abbreviatedId
        revision
    } catch (Exception ignore) {
        "?"
    }
}.join('-')

This block will iterate the modules listed in the gitRevisionsProjects array, in the given order, and output in the gitRevisions variable the abbreviated commit ids of the modules, separated by -.

You can include this field in your BuildConfig file:

defaultConfig {
    buildConfigField 'String', 'GIT_REVISIONS', '"${gitRevisions}"'
}

TAGS: ANDROID, GIT, GRADLE
comments powered by Disqus