How to conditionally accept Gradle build scan plugin terms of service in Kotlin DSL?

牧云@^-^@ 提交于 2019-12-24 00:38:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!