Auto applying Gradle plugin from custom distribution

Hi

I would like to create my custom Gradle distribution that contains custom plugin. In the distribution, I would like to automatically apply the plugin. So the plugin would be applied by default.

I am trying to simulate this in /customDistribution in samples from gradle -all distribution. This is what I ended up with

// Make the plugin visible to all projects, by including it in the build script classpath.
rootProject {
    buildscript {
        dependencies {
            classpath fileTree(dir: "${initscript.sourceFile.parentFile}/libs", include: '*.jar')
        }
    }

}
gradle.beforeProject {
    plugins.apply 'greeting'
}

And it gives me

Plugin with id 'greeting' not found.

How can one automatically apply custom plugin inside init.d/custom.gradle script under Gradle custom distribution?

Thanks!

There’s a gotcha here. The delegate of this closure is the init script, not the project. Unfortunately improving this would be a breaking change.

Here’s the workaround, using named paramenter:

gradle.beforeProject { project ->
    project.plugins.apply 'greeting'
}

Hi Stefan

actually it was not helpful, still getting the same exception

Plugin with id ‘greeting’ not found.

Do you have any other ideas, please?

Many thanks

I am able to add the standard plugins like ‘maven-publish’, but not the ‘greetings’ plugin. When I apply it directly in build.gradle script, it works fine (and the plugin is taken from my custom distribution).

Looks like I am trying to apply the plugin too soon?

You’re right, for non-core plugins you need to use the class name instead.

gradle.beforeProject { project ->
    project.plugins.apply project.buildscript.classLoader.loadClass('org.example.GreetingPlugin')
}

This is a use case that we will improve in the future with the plugins DSL.

Thanks. Still not working though :confused: now getting

java.lang.ClassNotFoundException: org.example.GreetingPlugin

Any ideas?

‘org.example.Greeting’ was just an example. It needs to be the class name of the plugin you are trying to apply.

:slight_smile: I understood it ofcourse, just followed your example. I am using the right class.

Ah I see what’s happening here. At the point where the configuration hook is called, the project classpath is not yet set up. There is no good hook unfortunately to say “just after the classpath is set up”, so the best we can do here is using afterProject instead of beforeProject.

If you don’t care about the types of that plugin being visible to the project build scripts, then you could also use this alternative, which will resolve the plugin in the context of the init script instead.

initscript {
  dependencies {
    classpath fileTree(dir: "${initscript.sourceFile.parentFile}/libs", include: '*.jar')
  }
}
allprojects {
  apply plugin: org.gradle.GreetingPlugin
}