buildSrc 中的简单 gradle 插件

如何为 gradle 项目创建自定义插件和 DSL 的简单示例。
此示例使用创建插件的三种可能方法之一。
这三种方式是:

  • 排队
  • buildSrc
  • 独立插件

此示例显示了从 buildSrc 文件夹创建插件。

此示例将创建五个文件

// 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 /主/常规/ SO /文档/ gradle 这个/插件/ 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 /主/常规/ SO /文档/ gradle 这个/插件/ 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 目录/主/资源/ META-INF / gradle 这个 -插件/ sample.properties

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

使用此设置,我们可以看到 DSL 块中调用者提供的值

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