Version Name&Code
我们经常会在android中以硬编码的方式来配置versionName&versionCode。
defaultConfig{
...
versionCode 1
versionName "1.0.0"
}
上面的方法有一些弊端:
- 你永远不知道哪一次的提交代表一个特定的版本
- 每当你需要增加versionCode和修改versionName的时候,你都必须要修改
build.gradle
文件。
如果你使用git作为你的源码控制系统的话,他也可以帮助你生成android versionName和versionCode,这是一个常见的做法,使用git标签来作为新版本的发布。

Version Name
对于version name,我们可以使用git describe
命令
- 使用这个命令可以查看最近提交的标记
- 如果tag指向提交,那么只显示tag
Example(a-b)

- 标记一次特定的commit为tag1.0
2.检出这次提交
3.输入命令git describe
4.输出:1.0
正如你看到的,如果你在提交的使用用tag的话,那么在你输入git describe命令的时候,就会输出这个tag。
Example(a-c)

- 标记一次commit为tag 1.0
- 添加更多的commits
- 输入命令git describe
- 将会输出 1.0-2-gdca226a


Version Code
对于versionCode,我们可以使用tag的总数,因为每一次的git tag指向一个版本,versionCode总是会比之前的那个版本大。

在上面的示例中,我们有3个tags,这个值将会被用作versioncode.
但是,我们不会为每一个中间版本创建一个tag,因此对于dev build,我们可以使用head提交的时间戳。

Groovy的方式使用git
要使用git,我建议使用一个grgit
库,创建具有以下内容的脚本:
buildscript{
repositories{
jcenter()
}
dependencies{
classpath 'org.ajoberstar:grgit:1.5.0'
}
}
import org.ajoberstar:grgit
ext{
git = Grgit.open(currentDir: projectDir)
gitVersionName = git.describe()
gitVersionCode = git.tag.list().size()
gitVersionCodeTime = git.head().time
}
task printVersion(){
println("Version name: $gitVersionName")
println("Version Code: $gitVersionCode")
println("Version Code Time: $gitVersionCodeTime")
}
把这些应用到你自己的build.gradle
文件中:
apply plugin: 'com.android.application'
apply from: "$project.rootDir/tools/script-git-version-gradle"
检查一下version name和code是否生成正确,使用./gradlew printVersion
命令,输出如下:
Version Name: 1.0-2-gdca226a
Version Code: 2
Version Code Time: 1484407970
最后在你的build.gradle中使用gitVersionName,gitVersionCode和gitVersionCodeTime变量:
productFlavors{
dev{
versionCode gitVersionCodeTime
versionName gitVersionName
}
prod{
versionCode gitVersionCodeTime
versionName gitVersionName
}
}
运行程序验证app version

这种方法的优点:
- 不需要修改build.gradle文件中的versionCode和versionName,可以自动生成。
- 可以轻松知道这次构建是从哪次提交生成的。
网友评论