简体   繁体   中英

Update Android Application version (stored in build.gradle) with gradle

It is possible to update the Android or library version versionCode and versionName when executing some task in gradle ? The versionCode/Name is placed in my android/build.gradle

I'm searching for a complete gradle script, not a shell one.

It's different from How to autoincrement versionCode in Android Gradle because the versionCode and versioName is stored in the build.gradle not in the manifest

In your build.gradle you want to update, I've changed a script to edit the current build.gradle and incrementing the versionCode and versionName.

Add this task to your gradle :

task incrementVersionCode << {
    println("Incrementing Version Code...")
    def manifestFile = file("build.gradle")
    def patternVersionCode = Pattern.compile("versionCode (\\d+)")
    def manifestText = manifestFile.getText()
    def matcherVersionCode = patternVersionCode.matcher(manifestText)
    matcherVersionCode.find()
    def mVersionCode = Integer.parseInt(matcherVersionCode.group(1))
    def mNextVersionCode = mVersionCode + 1
    def manifestContent = matcherVersionCode.replaceAll("versionCode " + mNextVersionCode)
    println("> Set versionCode(" + mVersionCode + ") to " + mNextVersionCode);
    manifestFile.write(manifestContent)
}

task incrementVersionName << {
    println("Incrementing Version Name...")
    def manifestFile = file("build.gradle")
    def patternVersionNumber = Pattern.compile("versionName \"(\\d+)\\.(\\d+)\\.(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcherVersionNumber = patternVersionNumber.matcher(manifestText)
    matcherVersionNumber.find()
    def majorVersion = Integer.parseInt(matcherVersionNumber.group(1))
    def minorVersion = Integer.parseInt(matcherVersionNumber.group(2))
    def pointVersion = Integer.parseInt(matcherVersionNumber.group(3))
    def mVersionName = majorVersion + "." + minorVersion + "." + pointVersion
    def mNextVersionName = majorVersion + "." + minorVersion + "." + (pointVersion + 1)
    def manifestContent = matcherVersionNumber.replaceAll("versionName \"" + mNextVersionName + "\"")
    println("> Set versionName(" + mVersionName + ") to " + mNextVersionName);
    manifestFile.write(manifestContent)
}

Usage

If you want to update version when running ./gradlew bintrayUpload (for eg, mut it can be the task you want) add this :

bintrayUpload.dependsOn incrementVersionCode
bintrayUpload.dependsOn incrementVersionName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM