Kotlin Gradle 插件:如何访问 `sourceSets` 等 `Project` 扩展?

Kotlin Gradle Plugin: How to access `Project` extensions such as `sourceSets`?

在常规构建脚本中,您可以轻松地在 Project 上使用扩展,例如 Project.sourceSets,例如 build.gradle.kts:

sourceSets {
    main {
        ...
    }
}

但是当我在我的 buildSrc 模块中开发一个 Gradle 插件时,我无法访问这些。例如:

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.*

class ExamplePlugin : Plugin<Project> {
    override fun apply(target: Project) {
        target.sourceSets { // error because `sourceSets` can't be resolved.
        }
    }
}

尽管在我的 buildSrc 依赖项中包含 kotlin-gradle-plugin 模块,但仍会发生这种情况:

plugins {
    `kotlin-dsl`
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31")
}

那么,如何从我的 Gradle 插件中访问这些扩展?

class ExamplePlugin : Plugin<Project> {
    override fun apply(target: Project) {
        target.configure<JavaPluginExtension> {
            sourceSets {
                println(names)
            }
        }
    }
}

在此处查看附加说明:https://docs.gradle.org/current/userguide/kotlin_dsl.html#project_extensions_and_conventions

基本上对于插件,或者其他不知道应用的插件时,其他插件添加的扩展的访问器(sourceSetsconfigurations等)需要通过一个方法调用哪种 'retrieves' 范围或对象。在 link 的下方还有一个如何获取其他插件创建的任务的示例:

val test by target.tasks.existing(Test::class)
test.configure { useJUnitPlatform() }
// or
val test by target.tasks.existing(Test::class) { 
    useJUnitPlatform()
}

注意如果项目中不存在'sourceSet'对象(因为没有应用java插件),会抛出异常。 使用 gradle 版本 7.2,kotlin-dsl 版本 2.1.6

进行测试