How do you use a Settings plugin from a buildSrc dir?

How do you use a Settings plugin directly from buildSrc dir?

We can use our Settings plugin if placing it within our Maven repo,
but not if it is located as a groovy script within a buildSrc
directory (project plugins below buildSrc seem to work OK though)

Here is an example using a GreetingPlugin from
Developing Custom Gradle Plugins and an
example Settings plugin. GreetingPlugin works OK but SettingsPlugin
results in the build error:

Plugin [id: 'com.example.settings'] was not found in any of the following sources:
  • build.gradle
plugins {
    id 'com.example.greeting'
}

apply plugin: 'com.example.greeting'
<...snip...>
  • settings.gradle
plugins {
    id 'com.example.settings'
}
<...snip...>
//apply plugin: 'com.example.settings'                                                                                                                                                                               
  • buildSrc/build.gradle
plugins {
    id 'groovy'
    id 'java-gradle-plugin'
}

gradlePlugin {
    plugins {
        greetingPlugin {
            id = 'com.example.greeting'
            implementationClass = 'com.example.GreetingPlugin'
        }

        settingsPlugin {
            id = 'com.example.settings'
            implementationClass = 'com.example.SettingsPlugin'
        }
    }
}
  • buildSrc/settings.gradle
<empty>
  • buildSrc/src/main/groovy/com/example/GreetingPlugin.groovy
package com.example

import org.gradle.api.Plugin
import org.gradle.api.Project

class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.task('hello') {
            doLast {
                println 'Hello from the GreetingPlugin'
            }
        }
    }
}
  • buildSrc/src/main/groovy/com/example/SettingsPlugin.groovy
package com.example

import org.gradle.api.Plugin
import org.gradle.api.initialization.Settings

class SettingsPlugin implements Plugin<Settings> {
    @Override
    void apply (Settings settings) {
        println settings
    }
}

Thanks for any help

1 Like

buildSrc is built after the settings script is evaluated for quite a long time already, so you simply cannot.
If you however would switch to an included build instead of buildSrc, you could include it in pluginManagement { ... } and use the settings plugin from there.

2 Likes

OK, will look into that. Thank you

I don’t unstand it, can you show me the example?

https://docs.gradle.org/current/userguide/composite_builds.html#included_plugin_builds

What @Vampire means is to put your plugins in a separate directory and include it in the pluginManagement

// settings.gradle.kts

pluginManagement {
    includeBuild("my-plugins")
}

plugins {
    id("your-plugin")
}

That’s not only what I meant, but exactly what I said. :smiley: