gradle Gradle Plugins Simple gradle plugin from `buildSrc`


Example

Simple example of how to create a custom plugin and DSL for your gradle project.
This sample uses one of the three possible ways of creating plugins.
The three ways are:

  • inline
  • buildSrc
  • standalone plugins

This example shows creating a plugin from the buildSrc folder.

This sample will create five files

// project's build.gradle
build.gradle
// build.gradle to build the `buildSrc` module
buildSrc/build.gradle
// file name will be the plugin name used in the `apply plugin: $name`
// where name would be `sample` in this example
buildSrc/src/main/resources/META-INF/gradle-plugins/sample.properties
// our DSL (Domain Specific Language) model
buildSrc/src/main/groovy/so/docs/gradle/plugin/SampleModel.groovy
// our actual plugin that will read the values from the DSL
buildSrc/src/main/groovy/so/docs/gradle/plugin/SamplePlugin.groovy

build.gradle:

group 'so.docs.gradle'
version '1.0-SNAPSHOT'

apply plugin: 'groovy'
// apply our plugin... calls SamplePlugin#apply(Project)
apply plugin: 'sample'

repositories {
    mavenCentral()
}

dependencies {
    compile localGroovy()
}

// caller populates the extension model applied above
sample {
    product = 'abc'
    customer = 'zyx'
}

// dummy task to limit console output for example
task doNothing <<{}

buildSrc/build.gradle

apply plugin: 'groovy'

repositories {
    mavenCentral()
}

dependencies {
    compile localGroovy()
}

buildSrc/src/main/groovy/so/docs/gradle/plugin/SamplePlugin.groovy:

package so.docs.gradle.plugin

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

class SamplePlugin implements Plugin<Project> {
    @Override
    void apply(Project target) {
        // create our extension on the project for our model
        target.extensions.create('sample', SampleModel)
        // once the script has been evaluated the values are available
        target.afterEvaluate {
            // here we can do whatever we need to with our values
            println "populated model: $target.extensions.sample"
        }
    }
}

buildSrc/src/main/groovy/so/docs/gradle/plugin/SampleModel.groovy:

package so.docs.gradle.plugin

// define our DSL model
class SampleModel {
    public String product;
    public String customer;

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("SampleModel{");
        sb.append("product='").append(product).append('\'');
        sb.append(", customer='").append(customer).append('\'');
        sb.append('}');
        return sb.toString();
    }
}

buildSrc/src/main/resources/META-INF/gradle-plugins/sample.properties

implementation-class=so.docs.gradle.plugin.SamplePlugin

Using this setup we can see the values supplied by the caller in your DSL block

 $ ./gradlew -q doNothing
SampleModel{product='abc', customer='zyx'}