Auto-increment versionCode in build.gradle file

Starting from this blog post by Bryan Rosenbaum, here is a gradle task to auto increment versionCode inside your build.gradle file.

import java.util.regex.Pattern


task incrementVersionCode << {
    println(":incrementVersionCode - Incrementing Version Code...")
    def buildGradleFile = file("build.gradle")
    def patternVersionCode = Pattern.compile("versionCode (\\d+)")
    def buildGradleFileText = buildGradleFile.getText()
    def matcherVersionCode = patternVersionCode.matcher(buildGradleFileText)
    def mVersionCode = Integer.parseInt(
    def mNextVersionCode = mVersionCode + 1
    def manifestContent = matcherVersionCode.replaceAll("versionCode " + mNextVersionCode)
    println(":incrementVersionCode - current versionCode=" + mVersionCode);
    println(":incrementVersionCode - next versionCode=" + mNextVersionCode);

Now run gradle incrementVersionCode and your build.gradle will be automatically updated.


Related Posts