Can I create a Gradle plugin that adds a dependency or another plugin based on a Gradle extension value?

Viewed 51

Can I create a Gradle plugin that adds a dependency based on an extension value?

I have a convention plugin that I use for libraries various projects, which brings in various dependencies, takes care of boilerplate configuration, configures other plugins etc etc. I want to add an extension to the plugin that can tell the plugin whether or not to add a certain dependency, in this case it happens to be Spock, as not every library module needs the Spock dependency.

So far, my plugin looks like this

interface BasePluginExtension {
    Property<Boolean> getUseSpock()
}

class BasePlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        BasePluginExtension basePluginExtension = project.extensions.create('basePluginConfig', BasePluginExtension)

        // If a value was supplied, use it, otherwise assume we want Spock
        if (basePluginExtension?.useSpock?.get() ?: true) {

            // Printing for debugging purposes
            println "I'm using spock! ${basePluginExtension.useSpock.get()}"
            
            // Currently apply a plugin that applies Spock but could also just add a dependency
            project.plugins.apply("test-config")
        }
    }
}

Then in the build.gradle file that I want to pull my plugin into, I have

plugins {
   id 'base-plugin'
}

basePluginConfig {
    useSpock = true
}

I'm following the docs on configuring an extension but I am getting the following error:

Cannot query the value of extension 'basePluginConfig' property 'useSpock' because it has no value available.

I've also tried the method of making an abstract class for the extension but I want the ability to have multiple configurable parameters in the future.

Is adding a dependency after plugin extension values have been configured not allowed/out of order for how Gradle works? Or am I possibly missing something obvious?

0 Answers
Related