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'}