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

Viewed 5597

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?

2 Answers

I found a clean way that is compatible with CI tools (without edit your code):

./gradlew assembleDebug -Pandroid.injected.version.code=1234 -Pandroid.injected.version.name=1.2.3.4

there are more params here for other things like signing:

https://www.javadoc.io/static/com.android.tools.build/builder-model/2.5.0-alpha-preview-02/constant-values.html


For GitLab CI:

I use this command for a debug version:

./gradlew assembleDebug -Pandroid.injected.version.code=$CI_PIPELINE_IID -Pandroid.injected.version.name=$CI_COMMIT_SHORT_SHA

You can echo $CI_PIPELINE_IID if you want to know its number. It increases every time you run a new pipeline for your project.

And for a release version:

./gradlew assembleRelease -Pandroid.injected.signing.store.file=$SIGNING_STORE_FILE -Pandroid.injected.signing.store.password=$SIGNING_STORE_PASSWORD -Pandroid.injected.signing.key.alias=$SIGNING_KEY_ALIAS -Pandroid.injected.signing.key.password=$SIGNING_KEY_PASSWORD -Pandroid.injected.signing.v1-enabled=true -Pandroid.injected.signing.v2-enabled=true -Pandroid.injected.version.code=$CI_PIPELINE_IID -Pandroid.injected.version.name=$CI_COMMIT_TAG

Note: first 4 env vars are set in my project variables and are not internal gitlab ci variables!

Related