如何使用Gradle脚本插件创建自己的配置块?

时间:2017-09-06 21:53:08

标签: gradle gradle-plugin

我们公司有一个Gradle脚本插件,其中包含许多任务。例如,它包含来自this answer的Jacoco afterEvaluate块:

def pathsToExclude = ["**/*Example*"]

jacocoTestReport {
    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it, exclude: pathsToExclude)
        })
    }
}

我们想要获取pathsToExclude变量并在我们的build.gradle文件中定义它,并在脚本插件中使用其余逻辑(让我们称之为company-script-plugin.gradle。例如:

apply from: http://example.com/company-script-plugin.gradle

companyConfiguration {
    pathsToExclude = ["**/*Example*"]
}

我们最初的想法是在构建脚本中添加一个任务,以便我们可以获得companyConfiguration

task companyConfiguration {
    ext.pathsToExclude = []
}

但是,我们认为这是一个hacky变通方法,因为运行任务不会做任何事情。创建自己的配置块的正确方法是什么?

我们希望它尽可能简单,如果可能的话,成为一个脚本插件(而不是二进制插件)。

1 个答案:

答案 0 :(得分:0)

这里有一个如何完成的例子:

apply plugin: CompanyPlugin

companyConfiguration {
  pathsToExclude = ['a', 'b', 'c']
}

class CompanyPlugin implements Plugin<Project> {

  void apply(Project p) {
    println "Plugin ${getClass().simpleName} applied"
    p.extensions.create('companyConfiguration', CompanyConfigurationExtension, p)
  }

}

class CompanyConfigurationExtension {
  List<String> pathsToExclude

  CompanyConfigurationExtension(Project p) {
  }

}

task printCompanyConfiguration {
  doLast {
    println "Path to exclide $companyConfiguration.pathsToExclude"
  }
}

另外,请查看docs

相关问题