Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 528
sschuberth Avatar asked Apr 17 '19 10:04

sschuberth


2 Answers

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.

like image 122
eskatos Avatar answered Oct 08 '22 03:10

eskatos


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")
    }
}
like image 38
sschuberth Avatar answered Oct 08 '22 04:10

sschuberth