Search code examples
androidcurlandroid-gradle-pluginbuild.gradlebitrise

Is it possible to set android version code and name via a Gradle task?


I'm trying to automate build process on CI that I'm working with. I am able to call a curl and assign it some variables such as version code and names. Then CI (in my case Bitrise CI) catch it and starts Release build. However, before that I want to set version code and version name based on what has been passed by curl into build.gradle file and then build process starts.

So, I'm thinking I can write a plugin/task that gets version code/name from a command line and then inject it in build.gradle file. A command like ./gradlew setVersion 1 1.0.

Threefore, by running this command from an script that I'll write, I will be able to run this gradle task and everyone from anywhere in the glob is able to create a release build by curl. Quite interesting :)

I am able to write a task similar to following code an put it into my main build.gradle file.

task setVersion << {
    println versionCode
    println versionName
}

and pass it some parameters via command line:

./gradlew -PversionCode=483 -PversionName=v4.0.3 setVersion

This is my output:

:setVersion
483
v4.0.3

BUILD SUCCESSFUL

Total time: 6.346 secs

So far so good. My question is how to set it in build.gradle file?


Solution

  • You can create methods to update the versionCode and versionName from the command line:

    def getMyVersionCode = { ->
        def code = project.hasProperty('versionCode') ? versionCode.toInteger() : -1
        println "VersionCode is set to $code"
        return code
    }
    
    def getMyVersionName = { ->
        def name = project.hasProperty('versionName') ? versionName : "1.0"
        println "VersionName is set to $name"
        return name
    }
    

    Then in the android block:

    defaultConfig {
            applicationId "your.app.id"
            minSdkVersion 15
            targetSdkVersion 23
            versionCode getMyVersionCode()
            versionName getMyVersionName()
    
            archivesBaseName = "YourApp-${android.defaultConfig.versionName}"
        }
    

    Then you can just call any task really:

    ./gradlew assembleDebug -PversionCode=483 -PversionName=4.0.3
    

    Read more about it here: https://web.archive.org/web/20160119183929/https://robertomurray.co.uk/blog/2013/gradle-android-inject-version-code-from-command-line-parameter/