Search code examples
kotlingradlegroovygradle-plugingradle-kotlin-dsl

Groovy extension input syntax in Kotlin DSL


I have a Gradle plugin which is in groovy which takes input via PluginExtension

class PluginExtension implements GroovyInterceptable {

    private final Project project
    private Map<String, ?> staticTokens
    private Map<String, DynamicToken> dynamicTokens
    private Map<String, Closure> derivedTokens
    private final Closure<Object> propertyGetter

    PluginExtension(Project project) {
        this.project = project
        propertyGetter = findDeploymentProperty.curry(project)
    }

    void setStaticTokens(Map<String, ?> staticTokens) {
        this.staticTokens = staticTokens
    }

    void setDynamicTokens(Map<String, ?> dynamicTokens) {
        this.dynamicTokens = dynamicTokens
                .collectEntries { k, v ->
                    [(k): [refId: { v.refId }, defaultValue: { v.defaultValue }, transform: {
                                v.transform ?: {
                                    it
                                }
                            }]]
                }
                .collectEntries { k, v ->
                    [(k): v as DynamicToken]
                } as Map<String, DynamicToken>
    }
}

In build.gradle I used to pass an input to the plugin as

deployPreparation {
    staticTokens = [
        appName      : project.name,
        version      : project.version,
        gradleVersion: project.gradle.gradleVersion
    ]
    dynamicTokens = [
        deployName             : [refId: "deploy.name", defaultValue: project.name.toLowerCase().replaceAll("[-]", ""), transform: {
                it.length() > 20 ? it.substring(0, 20) : it
            }],
        jvmAllowedMemory       : [refId: "jvm.allowed.memory", defaultValue: "1024m"],
        jvmActiveProcessors    : [refId: "jvm.active.processors", defaultValue: "2"],

    ]
derivedTokens = [
        cloudServerGroup: { "${deployName}-${cloudEnvironment}".toString() },
    ]
    
}

However, I cannot figure out what should be the equivalent of this in Kotlin DSL? (i.e. build.gradle.kts)

I tried with below but with no luck:

configure<com.company.search.deploy.prepare.plugin.PluginExtension> {

    staticTokens=mapOf(
            appName to project.name,
            version to project.version,
            gradleVersion to project.gradle.gradleVersion
        ) as Map<String,Any>
}

It complains about:

Cannot access 'staticTokens': it is private in 'PluginExtension'

Which is fair, but how can I set it alternatively?


Solution

  • Try using the method setter:

    configure<com.company.search.deploy.prepare.plugin.PluginExtension> {
      setStaticTokens(mapOf(
        appName to project.name,
        version to project.version,
        gradleVersion to project.gradle.gradleVersion
      ) as Map<String,Any>)
    }
    

    As it's the exposed interface form your PluginExtension.