Izbassar Tolegen
Izbassar Tolegen

Reputation: 2152

How to lazily get main sourceSets in Gradle

I need to configure sources jar for all of my subprojects. I have the following subprojects configuration defined:

subprojects {
    apply(plugin = "java-library")

    val sourcesJar = tasks.registering(Jar::class) {
        archiveClassifier.set("sources")
        from(the<SourceSetContainer>().named("main").get().allJava)
    }
    tasks.named("assemble") {
        dependsOn(sourcesJar)
    }
}

When I try to run ./gradlew tasks I receive an exception in my subproject saying that:

Extension of type 'SourceSetContainer' does not exist. Currently registered extension types: [ExtraPropertiesExtension]

My assumption is that the access to get() method of the extension causes problems but without that I cannot refer to the allJava sources that I need. So how to achieve desired result by using configuration avoidance API?

Running on Gradle 5.2.1 with Kotlin DSL.

Upvotes: 2

Views: 785

Answers (1)

Izbassar Tolegen
Izbassar Tolegen

Reputation: 2152

I found working solution. The problem is that when you call the<T>() function it is taken from the Task type which is why it complains about absent extension. The solution is to call the<T>() function on project instance like this:

subprojects {
  apply {
    plugin<JavaLibraryPlugin>()
  }
  val sourcesJar by tasks.registering(Jar::class) {
    archiveClassifier.set("sources")
    from(
      // take extension from project instance
      project.the<SourceSetContainer>().named("main").get().allJava
    )
  }
}

Upvotes: 4

Related Questions