SourceSets in multi projects

Given this gradle.build as root project

apply plugin: 'java'
  allprojects {
    task bla() {
  println project.name
  println project.sourceSets.main.allSource.srcDirs
  println sourceSets.main.allSource.srcDirs
 }
}

with this settings.gradle:

include 'subproj'

and this gradle.build for the subproject:

apply plugin: 'java'

When i execute “gradle bla” I would expect to get the different locations of the projects as output. Instead I get:

gradlemulti [D:\Daten\gradlemulti\src\main\resources, D:\Daten\gradlemulti\src\main\java] [D:\Daten\gradlemulti\src\main\resources, D:\Daten\gradlemulti\src\main\java] subproj [D:\Daten\gradlemulti\src\main\resources, D:\Daten\gradlemulti\src\main\java] [D:\Daten\gradlemulti\src\main\resources, D:\Daten\gradlemulti\src\main\java]

If I copy the code of the bla task in each build.gradle everything works as expected. This of course robs me of the nice allprojects feature. How can I fix this and still use the allprojects script block?

You are printing the information too early, before ‘subproj/build.gradle’ has been evaluated and its ‘java’ plugin applied. The subproject will get configured eventually, and the correct information will be used at task execution time (which is what you’d get if you wrapped the ‘printlns’ with ‘doLast { … }’).

It seems that my simplified example was too simple. What I wanted to achieve was to create a sources jar for each subproject.

allprojects {
   task sourcesJar(type: Jar, dependsOn: classes) {
  classifier = 'sources'
  from sourceSets.main.allSource
 }
}

This does not work as it creates the same files in each jar. All the files are from the root project. Which puzzles me here now is that I depend on classes. Maybe it always referes to the root classes task. My attempts to refer to the classes task of the subproject did not work so far.

It needs to be ‘allprojects { apply plugin: ‘java’; task sourcesJar(…) {…} }’.

1 Like

Perfect.