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 grgit library in your Gradle script. Add the following to your project-level build script:
buildscript {
dependencies {
classpath "org.ajoberstar.grgit:grgit-core:3.1.1"
}
}
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}"'
}
You can also add this field as a meta-data in the app manifest. This is useful to easily retrieve the git versions from a compiled APK, by simply reading the manifest.
defaultConfig {
manifestPlaceholders = [gitRevision: gitRevision]
}
<manifest>
<application>
<meta-data
android:name="${applicationId}.git_revision"
android:value="${gitRevision}"/>
</application>
</manifest>