Define a sourceset for all java sub-projects

7.3k views Asked by At

I wonder if it is possible to define a source set in gradle (e.g. integrationTests) that can be applied to all sub-projects that use the 'java' plugin?

Something like

sourceSets {
    integTest {
        java.srcDir file('src/integration-test/java')
        resources.srcDir file('src/integration-test/resources')
        compileClasspath = sourceSets.main.output + configurations.integTest
        runtimeClasspath = output + compileClasspath
    }
}

as mentioned here applied to all java sub-projects?

Thanks for useful hints!

2

There are 2 answers

1
Benjamin Muschko On BEST ANSWER

You can filter the subprojects of your build by applied plugin. In your example this would look like this:

def javaProjects() {
    subprojects.findAll { project -> 
        project.plugins.hasPlugin('java') 
    }
}

configure(javaProjects()) {
    sourceSets {
        integTest {
            java.srcDir file('src/integration-test/java')
            resources.srcDir file('src/integration-test/resources')
            compileClasspath = sourceSets.main.output + configurations.integTest
            runtimeClasspath = output + compileClasspath
        }
    }
}
0
Nate Glenn On

Because the root project's build script is evaluated before the subprojects' build scripts, subprojects.findAll{project -> project.plugins.hasPlugin('java')} does not work (at least in Gradle 4.8.1, which I am using).

Instead, you can register a callback in the root project which will be called each time a plugin is applied in a subproject:

subprojects {
    plugins.withId('java', { _ ->
        sourceSets {
            integTest {
                java.srcDir file('src/integration-test/java')
                resources.srcDir file('src/integration-test/resources')
                compileClasspath = sourceSets.main.output + configurations.integTest
                runtimeClasspath = output + compileClasspath
            }
        }
    })
}