5

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!

Community
  • 1
  • 1
u6f6o
  • 2,050
  • 3
  • 29
  • 54

2 Answers2

4

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
        }
    }
}
Benjamin Muschko
  • 32,442
  • 9
  • 61
  • 82
  • Strangely this does not work for me. When I print the `plugins` object of each subproject all I get is `org.gradle.plugins.ide.idea.IdeaPlugin`, which is also strange because I'm not using that plugin anywhere. – Nate Glenn Jul 22 '18 at 09:43
1

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
            }
        }
    })
}
Nate Glenn
  • 6,455
  • 8
  • 52
  • 95