如何在 Kotlin DSL 中有条件地接受 Gradle 构建扫描插件服务条款?

ssc*_*rth 8 gradle kotlin gradle-kotlin-dsl kotlin-dsl

这基本上将这个问题扩展到 Kotlin DSL 而不是 Groovy DSL:

如何在Groovy的DSL解决方案

if (hasProperty('buildScan')) {
    buildScan {
        termsOfServiceUrl = 'https://gradle.com/terms-of-service'
        termsOfServiceAgree = 'yes'
    }
}
Run Code Online (Sandbox Code Playgroud)

转换为 Kotlin DSL?

我正在运行的问题是“buildScan”扩展或com.gradle.scan.plugin.BuildScanExtension类不能静态使用,因为它们存在或不存在取决于--scan命令行参数是否提供给 Gradle。

我试过了

if (hasProperty("buildScan")) {
    extensions.configure("buildScan") {
        termsOfServiceUrl = "https://gradle.com/terms-of-service"
        termsOfServiceAgree = "yes"
    }
}
Run Code Online (Sandbox Code Playgroud)

但正如预期的那样termsOfServiceUrltermsOfServiceAgree没有解决,但是我不知道在这里使用什么语法。

esk*_*tos 5

Gradle Kotlin DSL 提供了一个withGroovyBuilder {}实用程序扩展,可将 Groovy 元编程语义附加到任何对象。请参阅官方文档

extensions.findByName("buildScan")?.withGroovyBuilder {
  setProperty("termsOfServiceUrl", "https://gradle.com/terms-of-service")
  setProperty("termsOfServiceAgree", "yes")
}
Run Code Online (Sandbox Code Playgroud)

这最终会进行反射,就像 Groovy 一样,但它使脚本更加整洁。