Search code examples
gradlegradle-kotlin-dsl

How to lazy applying plugin to sub projects in Gradle using Kotlin DSL?


I am trying to apply the checkerframework plugin (But I assume it can be any plugin) lazily to my java sub projects. The subproject have several projects of which more than 1 are java projects.

My build.gradle.kts file:

plugins {
    alias(buildscript.plugins.sonarqube)
    id("org.checkerframework") version "0.6.36"
}

subprojects {

    if (file("src/main/java").isDirectory) {
        apply(plugin = "org.checkerframework")
        checkerFramework {
            checkers = listOf("org.checkerframework.checker.nullness.NullnessChecker")
        }
    }
  ....
}

If I run a .\gradlew.bat build --scan command I can see that the checkerframework tasks are not created lazily. I can see 8 tasks is created. enter image description here

I tried to change this to the below:

plugins {
    id("org.checkerframework") version "0.6.36"
}

subprojects {

    tasks.withType<JavaCompile>().configureEach {
        apply(plugin = "org.checkerframework")
        checkerFramework {
            checkers = listOf("org.checkerframework.checker.nullness.NullnessChecker")
        }
    }
    
    ...
}

But it gives me errors in subprojects

Could not determine the dependencies of task ':mysubproject1:jar'.
> Could not create task ':mysubproject1:compileJava'.
   > Failed to apply plugin 'org.checkerframework'.
      > DefaultTaskCollection#configureEach(Action) on task set cannot be executed in the current context.

What is the correct way to apply tasks lazily?


Solution

  • By applying "lazily", I think you mean: "how do I only apply a plugin in subprojects which are Java subprojects?"

    The answer to that is to write:

    subprojects {
       pluginManager.withPlugin("java-base") {
          // Apply Java-dependent plugin
       }
    }