Gradle and nested extensions

1.7k views Asked by At

I'm trying to achieve the following dsl as a Gradle Plugin :

plugin {
   pluginA {
      property1 ""
      property2 ""
   }
   pluginB {
      property3 ""
   }
}

pluginA and pluginB are nothing alike, I don't want to use a NamedDomainObjectContainer. With the previous dsl everything was ok :

pluginA {
   property1 ""
   property2 ""
}
pluginB {
   property3 ""
}

project.pluginA.extensions.create('pluginA', PluginAExtension)
project.pluginB.extensions.create('pluginB', PluginBExtension)

And I could check if the user has defined those extensions :

if(project.pluginA != null) {
    //Configure task
}

But since a use my main plugin, if I declare the sub-extensions like that :

project.extensions.create("plugin", PluginExtension)
project.plugin.extensions.create('pluginA', PluginAExtension)
project.plugin.extensions.create('pluginB', PluginBExtension)

If the user does that :

project {

}

if(project.plugin.pluginA != null) returns true

I tried without the plugin.extensions.create(), and use directly in extensions class :

class PluginExtension {
    PluginAExtension pluginA
    PluginBExtension pluginB
}

but now I get pluginA() == null always. I now I can declare everything as properties with closure but that's a lot of works for something that was working before. I just want to add an enclosing plugin

1

There are 1 answers

3
lance-java On BEST ANSWER

I think you want

import org.gradle.util.ConfigureUtil;

class PluginExtension {
    PluginAExtension pluginA
    ...

    PluginAExtension pluginA(Closure closure) {
        return pluginA(ConfigureUtil.configureUsing(closure))
    }

    void pluginA(Action<? super PluginAExtension> action) {
        if (pluginA == null) pluginA = new PluginAExtension()
        action.execute(pluginA)
    }

    ...
}

See DefaultProject.copySpec(Closure) for similar functionality