0

This is kind of a follow-up question to this one.

I want to "know" from which branch may Android app was built during the execution of the Gradle build.gradle file and add the branch name to the versionName of my app.

This is my naive approach:

apply plugin: 'android'

def branch ="test";

android {
    compileSdkVersion 22
    buildToolsVersion '22.0.0'

    // ..

    buildTypes {

        debug {
            minifyEnabled false;
            applicationIdSuffix ".debug"
            versionNameSuffix " branch: " + "$branch"
            debuggable true
            signingConfig signingConfigs.debug
        }

    }

}

task setArgs << {

   branch =  "$word1"

}

task showArgs << {
    println "$branch"
}

When I execute:

gradlew setArgs -Pword1=mybranch showArgs

the branch variable is set and "mybranch" is logged in the console on execution of showArgs.

But when I execute

gradlew setArgs -Pword1=mybranch build

the branch variable is still the default String "test" and therefore useless in the versionNameSuffix.

What's the best way to get this working?

Community
  • 1
  • 1
fweigl
  • 21,278
  • 20
  • 114
  • 205

2 Answers2

2

That's because the line

versionNameSuffix " branch: " + "$branch"

is executed during the configuration phase, when all the tasks are configured.

Then, when this phase is done and gradle knows all the tasks and their dependencies, setArgs is executed, and the following line is executed:

branch =  "$word1"

You could simply remove the setArgs task and do

versionNameSuffix " branch: $word1"

or, if you want the default value of the branch to be "test" when no property word1 is passed:

versionNameSuffix(' branch: ' + (project.hasProperty('word1') ? project.property('word1') : 'test'))
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

I think a better approach to this would be to use a gradle.properties file to store the branch name - this way you don't have to provide it whenever you invoke Gradle.

build.gradle:

apply plugin: 'android'

android {
    compileSdkVersion 22
    buildToolsVersion '22.0.0'

    // ..
    buildTypes {
        debug {
            minifyEnabled false;
            applicationIdSuffix ".debug"
            versionNameSuffix " branch: " + "$branch"
            debuggable true
            signingConfig signingConfigs.debug
        }
    }
}

gradle.properties

branch=mybranch
Raniz
  • 10,882
  • 1
  • 32
  • 64
  • But that would mean I would have to 'statically' put the branch name into the properties file, right? – fweigl Jun 12 '15 at 06:25
  • Ideall, yes - but since it's a branch you can have a different `gradle.properties` per branch. You can, however, also provide it with `-Pbranch=mybranch` – Raniz Jun 12 '15 at 06:27