Reputation: 10867
I'd like to insert the hash of the last git commit inside my AndroidManifest (more specificaly the versionCode tag).
I am using gradle with Android Studio.
Upvotes: 4
Views: 3294
Reputation: 4976
To answer the OQ, add the following to the android section of the app's build.gradle
def getGitHash = { ->
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', 'HEAD'
standardOutput = stdout
}
return stdout.toString().trim()
}
Since versionCode is numeric, then change defaultConfig versionName to
versionName getGitHash()
Better Implementation
What I actually do with my own project is to inject the value into a BuildConfig variable and access it that way.
I use these methods in the android section:
def getGitHash = { ->
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', 'HEAD'
standardOutput = stdout
}
return "\"" + stdout.toString().trim() + "\""
}
def getGitBranch = { ->
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
standardOutput = stdout
}
return "\"" + stdout.toString().trim() + "\""
}
and add this to the BuildConfig section:
productFlavors {
dev {
...
buildConfigField "String", "GIT_HASH", getGitHash()
buildConfigField "String", "GIT_BRANCH", getGitBranch()
...
}
}
Then in source code, such as Application.java
Log.v(LOG_TAG, "git branch=" + BuildConfig.GIT_BRANCH);
Log.v(LOG_TAG, "git commit=" + BuildConfig.GIT_HASH);
Upvotes: 10
Reputation: 1422
From this post by Ryan Harter, tag your commit and add the following to your build.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()
}
Then change the versionName
in defaultConfig
to use getVersionName()
.
Upvotes: 5