问题
This basically extends this question to Kotlin DSL instead of Groovy DSL:
How does the Groovy DSL solution of
if (hasProperty('buildScan')) {
buildScan {
termsOfServiceUrl = 'https://gradle.com/terms-of-service'
termsOfServiceAgree = 'yes'
}
}
translate to Kotlin DSL?
The problem I'm running is that the "buildScan" extension or the com.gradle.scan.plugin.BuildScanExtension
class cannot statically be used as they are either present or not present depending on whether the --scan
command line argument was provided to Gradle or not.
I've tried
if (hasProperty("buildScan")) {
extensions.configure("buildScan") {
termsOfServiceUrl = "https://gradle.com/terms-of-service"
termsOfServiceAgree = "yes"
}
}
but as expected termsOfServiceUrl
and termsOfServiceAgree
do not resolve, however I'm clueless what syntax to use here.
回答1:
The Gradle Kotlin DSL provides a withGroovyBuilder {}
utility extension that attaches the Groovy metaprogramming semantics to any object. See the official documentation.
extensions.findByName("buildScan")?.withGroovyBuilder {
setProperty("termsOfServiceUrl", "https://gradle.com/terms-of-service")
setProperty("termsOfServiceAgree", "yes")
}
This ends up doing reflection, just like Groovy, but it keeps the script a bit more tidy.
回答2:
It's not exactly nice, but using reflection it works:
if (hasProperty("buildScan")) {
extensions.configure("buildScan") {
val setTermsOfServiceUrl = javaClass.getMethod("setTermsOfServiceUrl", String::class.java)
setTermsOfServiceUrl.invoke(this, "https://gradle.com/terms-of-service")
val setTermsOfServiceAgree = javaClass.getMethod("setTermsOfServiceAgree", String::class.java)
setTermsOfServiceAgree.invoke(this, "yes")
}
}
来源:https://stackoverflow.com/questions/55725574/how-to-conditionally-accept-gradle-build-scan-plugin-terms-of-service-in-kotlin