Override ext properties from applied script by ext properties in applying script?


(Wujek Srujek) #1

I would like to define a common parent script that sets some defaults: parent.gradle:

ext {
    javaVersion = JavaVersion.VERSION_1_6
    groovyVersion = '1.8.8'
}
apply plugin: 'java'
targetCompatibility = javaVersion
sourceCompatibility = javaVersion
dependencies.compile "org.codehaus.groovy:groovy-all:$groovyVersion"

Now, in another script, I would like to be able to override the javaVersion and the dependency version: build.gradle

apply from: 'parent.gradle'
ext {
    javaVersion = JavaVersion.VERSION_1_7
    groovyVersion = '2.1.5'
}

This doesn’t work - by the time the overriding ext properties are defined, the parent script has already been applied and the versions are set. I also tried a bit with afterEvaluate / beforeEvaluate, to no avail (it didn’t override the properties, but maybe I was doing it wrong).

I tinkered something of my own: parent.gradle:

ext {
    setDefault 'javaVersion', JavaVersion.VERSION_1_6
    setDefault 'groovyVersion', '1.8.8'
    setDefault 'junitVersion', '4.10'
}
apply plugin: 'groovy'
dependencies.compile "org.codehaus.groovy:groovy-all:$groovyVersion"
dependencies.compile "junit:junit-nodep:$junitVersion"
targetCompatibility = javaVersion
sourceCompatibility = javaVersion
  def setDefault(name, value) {
    if (!hasProperty(name)) {
        logger.info
">>> Setting default '$name' = '$value'."
        ext."$name" = value
    } else {
        logger.info ">>> Found '$name' = '${ext."$name"}', not setting default."
    }
}

build.gradle remains without change, and this works (i.e. source/targetCompatibility and groovy version are overridden, but junit does not), but it requires that the properties in build.gradle are set before the parent script is applied, so it is a bit fragile. I also don’t like the fact that I need custom groovy code for something like that. I bet Gradle has something along these lines built in. Can someone give me some pointers?

wujek