我计划编写包含多个代码质量gradle插件的自定义插件。逻辑很简单:使用这种自定义质量我想强制执行"默认"我们所有项目的标准。另一方面,我希望所有包装的插件仍然可以自定义(例如,我希望在默认情况下使用"基本"规则集设置PMD插件,但我绝对不想限制任何人都要添加addinitional规则集。)
级联扩展的推荐策略是什么?
谢谢!
答案 0 :(得分:2)
您可以应用使用project.afterEvaluate
的插件,然后以编程方式查找插件,如果已应用,则检查pmd
块并根据需要进行配置。如果未应用插件,则应用插件并设置块的默认值。
apply plugin: "groovy"
group = 'com.jbirdvegas.q41683529'
version = '0.1'
repositories {
jcenter()
}
class PmdWrapper implements Plugin<Project> {
@Override
void apply(Project target) {
target.afterEvaluate {
def pmdPlugin = target.plugins.findPlugin(PmdPlugin)
// check if the plugin is already applied if not apply it
if (!pmdPlugin) {
target.plugins.apply(PmdPlugin)
}
// get a reference to the extension and use it to manipulate the values
println target.pmd.ruleSets
setValues(target.pmd as PmdExtension)
println target.pmd.ruleSets
println "Now configured ruleSets: ${(target.pmd as PmdExtension).ruleSets}"
}
}
static setValues(PmdExtension pmd) {
// here you can set the values or add or manipulate as needed
if (!pmd.ruleSets.contains('basic') || !pmd.ruleSets.contains('braces')) {
pmd.ruleSets << "basic" << "braces"
}
// blah for other values
}
}
apply plugin: PmdWrapper
task nothing {}
然后你可以看到正在配置的pmd插件的结果
$ ./gradlew -b build_simple.gradle nothing -q
[java-basic]
[java-basic, basic, braces]
Now configured extension: [java-basic, basic, braces]