Gradle 自动版本号以及自定义apk包名 - MrWu94/AndroidNote GitHub Wiki

1 自动版本号

昨天 2016.03.02 刚发现的好东西,更优雅的 Android 发布自动版本号方案

这里简单总结下,配合 git 获取软件版本号和版本名

版本号 versionCode 使用 Git 中 commit 的数量来作为版本号——versionCode

def cmd = 'git rev-list HEAD --first-parent --count'  
def gitVersion = cmd.execute().text.trim().toInteger()

android {  
  defaultConfig {
    versionCode gitVersion
  }
}

版本名 versionName 使用 git describe,获取从当期 commit 到距离它最近的 tag 的描述。默认都是 annoted tag,如果要指所有的类型的 tag 的话,就加 –tags 参数。

def cmd = 'git describe --tags'  
def version = cmd.execute().text.trim()

android {  
  defaultConfig {
    versionName version
  }
}

2 自定义apk包名

gradle脚本大法好:

def releaseTime() {
    return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
}

def gitVersionCode() {
    def cmd = 'git rev-list HEAD --first-parent --count'
    cmd.execute().text.trim().toInteger()
}

def gitVersionTag() {
    def cmd = 'git describe --tags'
    def version = cmd.execute().text.trim()

    def pattern = "-(\\d+)-g"
    def matcher = version =~ pattern

    if (matcher) {
        version = version.substring(0, matcher.start()) + "." + matcher[0][1]
    } else {
        version = version + ".0"
    }

    return version
}
    
    
    
//自定义apk安装包名
applicationVariants.all { variant ->
    variant.mergedFlavor.versionCode = gitVersionCode()
    variant.mergedFlavor.versionName = gitVersionTag()
    variant.outputs.each { output ->
        output.outputFile = new File(
                output.outputFile.parent + "/${variant.buildType.name}",
                "HelloWord-${variant.buildType.name}-v${variant.versionName}-${variant.productFlavors[0].name}-${releaseTime()}.apk".toLowerCase())
    }
}

参考资料:http://jp1017.github.io/2015/12/27/Android-Studio-%E5%A4%9A%E6%B8%A0%E9%81%93%E6%89%93%E5%8C%85%E5%8F%8A-gradlew-%E5%91%BD%E4%BB%A4%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/#