【问题标题】:Kotlin Gradle Plugin: How to access `Project` extensions such as `sourceSets`?Kotlin Gradle 插件:如何访问 `Project` 扩展,例如`sourceSets`?
【发布时间】:2021-11-14 12:43:35
【问题描述】:

在常规构建脚本中,您可以轻松地在 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 插件中访问这些扩展?

【问题讨论】:

    标签: java kotlin gradle gradle-plugin gradle-kotlin-dsl


    【解决方案1】:
    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 等)将需要通过一个方法调用,该方法调用“检索” ' 那个范围或对象。在链接的下方还有一个如何获取其他插件创建的任务的示例:

    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 版测试

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 1970-01-01
      • 2016-08-11
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多