Override ext property in subprojects

I’m hoping this is a fairly easy issue for you all. I have a three level multiproject build and I want to override an extended property defined in the root project. The project layout is something like the following:

root/
    build.gradle
    projectA/
    projectB/
        build.gradle
        projectC/
        projectD/

What I really would like is to have the extended property from the root project overridden in all subprojects of “projectB”, but for some reason I can’t get the following to work (all the subprojects of B still use the root project property value).

Root project build.gradle:

ext.configDirName = "etc"

allprojects {
    task copyConfig(type: Copy) {
        from "src/main/config"
        into "$installDir/$configDirName"
    }
}

ProjectB build.gradle:

subprojects {
   ext.configDirName = "config"
}

Is there something obvious here that I’m not doing correctly?

It’s the order of evaluation.

The root script runs first, including allprojects {}. This means the copyConfig task gets configured with the value of configDirName at the time.

Then the subprojects build scripts run, eventually getting to B’s subprojects {}. Changing the value of configDirName at this point doesn’t change anything because copyConfig has already seen the previous value.

“Global” values like this is a bit of a smell. I would try to keep the extra properties close to what’s using it (so put configDirName on copyConfig instead). You can defer evaluation of configDirName by passing a Closure to into().

I’ve sprinkled some println’s in here so you can see the order of evaluation. Something like:

allprojects {
	println "In root for $project.name"
	task copyConfig(type: Copy) {
		ext.configDirName = "etc"
		from "src/main/config"		
		into { 
			println "Destination for $project.name is $configDirName"
			configDirName 
		}
	}
}

Then in B’s build.gradle:

println "In B for $project.name"

subprojects {
	println "In B.subprojects for $project.name"
	copyConfig.configDirName = "custom"
}

HTH