A more proper and lean way to achieve the result which gained traction lately would be to use gradle git integration via Groovy JGit bindings. As it uses JGit it doesn't even require git to be installed to work.
Here's a basic example showing a similar (but with some additional information in gitVersionName string) solution:
buildscript {
dependencies {
classpath 'org.ajoberstar:grgit:1.4.+'
}
}
ext {
git = org.ajoberstar.grgit.Grgit.open()
gitVersionCode = git.tag.list().size()
gitVersionName = "${git.describe()}"
}
android {
defaultConfig {
versionCode gitVersionCode
versionName gitVersionName
}
}
[...]
As you can see in Grgit API documentation the describe operation provides additional information other than most recent tag reachable in history:
Find the most recent tag that is reachable from HEAD. If the tag points to the commit, then only the tag is shown. Otherwise, it suffixes the tag name with the number of additional commits on top of the tagged object and the abbreviated object name of the most recent commit.
Anyhow, it won't tell if the state is dirty or not. This information can be easily added by looking at the clean status of the repo, and appending a string if it's not clean.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…