Simple buildSrc plugin issue

Hi,

I’m trying to write a plugin in buildSrc and apply it to the root project. When trying to apply it, I get plugin not found.

Project structure

   build.gradle
+  buildSrc
     build.gradle
   + src
      + main
         + groovy
            CustomPlugin.groovy

Root build.gradle

apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'customplugin'

depedencies {
    testCompile 'junit:junit:4.12'
}

buildSrc build.gradle

apply plugin: "groovy"
apply plugin: "java"

dependencies {
    compile localGroovy()
    compile gradleApi()
}

Plugin code

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

class CustomPlugin implements Plugin<Project>
{
    @Override
    void apply(Project target)
    {
        println 'Applying CustomPlugin'
    }
}

gradle clean build gives Plugin with id ‘customplugin’ not found.

Any hints?

Thank you

You forgot to add the properties file that tells Gradle about the mapping from plugin ID to implementation class. Have a look at the user guide about plugins.

Thanks for your reply, but isn’t that required only for standalone projects? Being in buildSrc, I thought the there’s no need for an extra mapping.

https://docs.gradle.org/current/userguide/custom_plugins.html#sec:custom_plugins_standalone_project

You always need a mapping, how else is Gradle going to know what ID your plugin should have?

Thanks a lot for the help

If you want to implement a plugin into your buildscript, then you have two options.

Option 1
apply plugin: YourCustomPluginClassName

Option 2
plugins { id 'your.custom.plugin.id' }

apply plugin: is used when specifying your plugin by its class name (ex. apply plugin: JavaPlugin)
plugins { } is used when specifying your plugin by its id (ex. plugins { id 'java' })
See Gradle Plugins by tutorialspoint for reference

If you choose Option 1, then your custom plugin will need to be brought into your build script by 1 of 3 ways.

  1. You can code it directly within your Gradle build script.
  2. You can put it under buildSrc (ex. buildSrc/src/main/groovy/MyCustomPlugin).
  3. You can import your custom plugin as a jar in your buildscript method.
    See Gradle Goodness by Mr. Haki for information about the buildscript method.

If you choose Option 2, then you need to create a plugin id. Create the following file buildSrc/src/main/resources/META-INF/gradle-plugins/[desired.plugin.id].properties. Copy and paste implementation-class=desired.plugin.id into your newly created .properties file. Replace ‘desired.plugin.id’ with your desired plugin id.
See Custom Plugins by Gradle for more info.