Overwriting in subprojects

In my build logic, 80% of my sub modules share a common logic. Therefore, I defined a task in the root build.gradle using something like:

subprojects {
    apply plugin: 'java'

    task export(type: Copy) {
        from jar
        into 'export/'
    }
}

Unfortunately, a few of the submodules behave slightly differently. In the example above, they would need to export to outgoing/ instead of export/. Of course in reality, the requirement is more complex.

I can’t figure out a way to either:

  • have a property per subproject defining the “outputDirectory”
  • or overwrite the “export” task in subprojects where needed

Is there any kind of overwrite support in gradle, which I could rely on for such a use-case? As it stands now, my only option is copy&paste of the export task in each submodule and change it where needed. But my software engineering heart crys telling me I’m violating the DRY principle :cry:

No need to repeat anything, just specify what is different in the individual subproject’s build.gradle.

export {
  into 'outgoing/'
}
2 Likes

Wow, I was not aware of that! Does this mechanism has a name I can read up on? It seems I can overwrite things like into, but not a custom definition like def outputDirectory, correct?

The Groovy def keyword creates a local variable, which is local to that particular script. If you want to create a property that can be overridden you should use extra properties.

build.gradle

subprojects {
  ext {
    outputDirectory = 'foo'
  }
}

subproject.gradle

 outputDirectory = 'bar'

Also, I’m assuming here that ‘outputDirectory’ is different than ‘buildDir’?

1 Like

Ok, thank you, I will try that on Monday when I’m back at work :grinning:

Yes, outputDirectory is different and as I said in the beginning, the actual use-case is way more complex, but didn’t want to bother anyone here with the nasty details.