Gradle plugin specifying default extension values

2019-09-08 11:43发布

I plan to write custom plugin wrapping several code quality gradle plugins. The logic is simple: using this custom quality I want to enforce "default" standards for all our projects. On the other hand, I want all the wrapped plugins still to be customizable (for example, I'd like to set PMD plugin with "basic" ruleset by default, but definitely I do not want to limit anyone to add addinitional rulesets).

What is the recommended strategy to cascade the extensions?

  • Should I do project.create({extension}) for all the plugins, check values if the values are set and default them (and how would I distinguish default from plugin extension and the default value set by the user?)
  • Should I create myOwnExtension and set the values of the wrapped plugins extensions from this custom one?
  • Is there any other way how to automatically do the cascade?

Thanks!

1条回答
祖国的老花朵
2楼-- · 2019-09-08 12:26

You could apply a plugin that uses project.afterEvaluate then look for the plugin programmatically and if it's applied then check for the pmd block and configure as needed. If the plugin is not applied then apply the plugin and set the defaults for the block.

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

Then you can see the result of the pmd plugin being configured

$ ./gradlew -b build_simple.gradle nothing -q
[java-basic]
[java-basic, basic, braces]
Now configured extension: [java-basic, basic, braces]
查看更多
登录 后发表回答