如何实现gradle代码版本自动增量?

Ros*_*iak 5 android gradle android-gradle-plugin

更具体地说,我有一些构建配置:

signingConfigs {
    debug {
        keyAlias ''
        keyPassword ''
        storeFile file('') 
    }
    release {
        keyAlias ''
        keyPassword ''
        storeFile file('')
        storePassword ''
    }
}
....
defaultConfig {
    applicationId ""
    minSdkVersion 21
    targetSdkVersion 23
    versionCode code
}
Run Code Online (Sandbox Code Playgroud)

我希望gradle在每次运行'release'时自动增加代码版本.

到目前为止我所拥有的:

def code = 1;

//Get all the gradle task names being run
List<String> runTasks = gradle.startParameter.getTaskNames();

for (String item : runTasks) {

    //Get the version.properties file. Its our custom file for storing a code version, please don't remove it
    def versionPropsFile = file('version.properties')

    def Properties versionProps = new Properties()

    //This will prevent the gradle from exploding when there's no file yet created
    if (versionPropsFile.exists())
        versionProps.load(new FileInputStream(versionPropsFile))

    //It will insert the "0" version in case the file does not exist
    code = (versionProps['VERSION_CODE'] ?: "0").toInteger()

    if (item.contains("release")) {
        // If we're building up on Jenkins, increment the version strings
        code++

        versionProps['VERSION_CODE'] = code.toString()

        //It will overwrite the file even if it doesn't exist
        versionProps.store(versionPropsFile.newWriter(), null)
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:

我似乎无法进入if (item.contains("release")).它总是假的,但我肯定看到gradle运行这个taks.我如何修复它或者至少在控制台中输出由gradle运行的所有任务(它们的名称)?

lao*_*omo -2

git 可以提供帮助,请点击此链接:使用 Git 标签和 Gradle 自动版本控制和增量

android {
    defaultConfig {
    ...
        // Fetch the version according to git latest tag and "how far are we from last tag"
        def longVersionName = "git -C ${rootDir} describe --tags --long".execute().text.trim()
        def (fullVersionTag, versionBuild, gitSha) = longVersionName.tokenize('-')
        def(versionMajor, versionMinor, versionPatch) = fullVersionTag.tokenize('.')

        // Set the version name
        versionName "$versionMajor.$versionMinor.$versionPatch($versionBuild)"

        // Turn the version name into a version code
        versionCode versionMajor.toInteger() * 100000 +
                versionMinor.toInteger() * 10000 +
                versionPatch.toInteger() * 1000 +
                versionBuild.toInteger()

        // Friendly print the version output to the Gradle console
        printf("\n--------" + "VERSION DATA--------" + "\n" + "- CODE: " + versionCode + "\n" + 
               "- NAME: " + versionName + "\n----------------------------\n")
    ...
    }
}
Run Code Online (Sandbox Code Playgroud)