Rolf ツ
Rolf ツ

Reputation: 8781

Jenkins read Android app version from build.gradle file to environment variable

I want to push version tags to my git repository automatically when Jenkins creates a build. But in order to do this I need the version name and version code for the created build artifact.

I'm currently using the following setup to achieve this (it works fine):

  1. Create a Gradle task in the build.
  2. Run a Gradle task that creates a properties file with the version name and version code in it;
  3. Using the EnvInject plugin read/inject the properties file, so that the environment variables are available to use in the current Jenkins job;

The code to generate the version.properties file looks like this:

android.applicationVariants.all { variant ->
    def taskName = "createVersionFile" + variant.flavorName.capitalize();
    if (tasks.findByPath(taskName) == null) {
        tasks.create(name: taskName) {
            doLast {
                def prop = new Properties()
                def propFile = new File("$buildDir/outputs/version.properties");
                prop.setProperty('versionname', variant.versionName + '-' + variant.versionCode)
                propFile.createNewFile();
                prop.store(propFile.newWriter(), null);
            }
        }
    }
}

This works (as mentioned before) but it's a quite unwieldy method, I'm forced to modify the build.gradle file in order for Jenkins to do it's work.

Is there an easier method, possibly without modifying the build.gradle file? Maybe by generating a second build.gradle file which includes the "version.properties" task?

Upvotes: 4

Views: 2115

Answers (1)

Eugen Martynov
Eugen Martynov

Reputation: 20130

My build philosophy is that everything should be available by gradle. No matter what automation you want to do with your project. That gives you flexibility to repeat it in any environment and easily setup any CI that just supports command line runs.

So I would add gradle git plugin to your build to manipulate with git (or do it via command line).

Take a look to gradle.properties file. You can define version code and name there. You don't need extra code to get these values in your Android gradle script and git manipulations as parameters. So you can inject them in defaultConfig.

Upvotes: 2

Related Questions