PMD Gradle 插件中的两层规则集

Two-tiered rulesets in PMD Gradle plugin

我想在我的 gradle 项目中设置 PMD 以具有两个规则集,一个是强制性的并且中断构建,另一个只报告但允许构建继续。这可能吗?

绝对有可能!

默认情况下,PMD 插件将为每个源集设置 1 个任务 运行。您可以为您的 2 个规则测试之一配置它:

pmd {
  ignoreFailures = false
  ruleSets = [] // Remove defaults
  ruleSetFiles = files("path/to/mandaroty/ruleset.xml")
}

然后,我们需要为 non-mandatory 规则设置一组新的独立任务,大致如下……

def sourceSets = convention.getPlugin(org.gradle.api.plugins.JavaPluginConvention).sourceSets
sourceSets.all { ss ->
  def taskName = ss.getTaskName('optionalPmd', null)
  project.tasks.register(taskName) { task ->
    task.description = "Run OPTIONAL PMD analysis for " + ss.name + " classes"
    task.source = ss.allJava
    task.conventionMapping.map("classpath", () -> ss.output.plus(ss.compileClasspath))
    task.ignoreFailures = true // override the value previously set
    task.ruleSetFiles = files("path/to/optional/ruleset.xml") // override the value previously set
  }

  // Have the optional analysis run during "check" phase
  project.tasks.named(org.gradle.api.plugins.JavaBasePlugin.CHECK_TASK_NAME) { checkTask ->
    checkTask.dependsOn taskName
  }
}

我是用心写的,所以可能需要做一些调整……