setting properties for Gradle subproject

I have a multi-project Gradle build. In each subproject I have a properties.gradle file like the following:

def usefulMethod() {
    return 'foo'
}

ext {
    foo = 'bar'
    usefulMethod = this.&usefulMethod
}

And then I import it into the subproject build.gradle using apply from: './properties.gradle'.

However, if two subprojects import a variable with the same name, I get this error:

Cannot add extension with name 'foo', as there is an extension already registered with that name.

It seems that adding to ext affects the entire project instead of just the subproject like I wanted. What is the correct way to import properties and variables from an external file in a subproject without leaking them into the entire project build?

1 answer

  • answered 2018-07-12 19:23 Nate Glenn

    The plain ext is the extension for ENTIRE project, the root project and all subprojects. To avoid polluting the root namespace whenever you include a file via apply from..., you should instead use project.ext. project refers to the current project or subproject being built. For example, the below file could be apply from'd to add a downloadFile function to the current project:

    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'de.undercouch:gradle-download-task:3.4.3'
        }
    }
    
    project.ext {
        apply plugin: de.undercouch.gradle.tasks.download.DownloadTaskPlugin
    
        downloadFile = { String url, File destination ->
            if (destination.exists()) {
                println "Skipping download because ${destination} already exists"
            } else {
                download {
                    src url
                    dest destination
                }
            }
        }
    }