【问题标题】:Disable a Checkstyle rule from a Gradle `build.gradle` file从 Gradle `build.gradle` 文件中禁用 Checkstyle 规则
【发布时间】:2022-12-09 08:51:41
【问题描述】:

可以从 Gradle 运行 Checkstyle linter,而无需编写配置 .xml 文件。这是一个例子:

/// Checkstyle linter
// Run by `gradle check`, which is run by `gradle build`
apply plugin: 'checkstyle'
ext.checkstyleVersion = '10.5.0'
configurations {
  checkstyleConfig
}
dependencies {
  checkstyleConfig("com.puppycrawl.tools:checkstyle:${checkstyleVersion}") { transitive = false }
}
checkstyle {
  toolVersion "${checkstyleVersion}"
  ignoreFailures = false
  config = resources.text.fromArchiveEntry(configurations.checkstyleConfig, 'google_checks.xml')
}

但是,我看不到如何禁用/抑制特定检查,仍然来自 build.gradle 文件。

我想禁用 LineLength 检查。这些都不起作用:

checkstyle {
  ...
  configProperties += ['LineLength.max': 140]
  configProperties += ['LineLength.enabled': false]
  configProperties += ['suppressions.suppress': 'LineLength']
}

如果有的话,什么是正确的调用?

【问题讨论】:

  • 您能否详细说明为什么要禁用 build.gradle 文件中的规则?为什么不将 checkstyle-suppressions.xml 文件添加到您的项目中?
  • 我有几十个项目在他们的 build.gradle 文件中启用了 checkstyle,我不希望在每个项目中创建一个 checkstyle-suppressions.xml 文件,然后尝试让它们保持同步。

标签: gradle checkstyle


【解决方案1】:

您的明显意图是从常用的 Checkstyle 配置开始并为您的项目自定义它。让我们编写一个 Gradle 脚本来转换 Checkstyle 配置。该脚本删除 LineLength 模块。

import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

def readCheckstyleConfig() {
  def xslt = '''
      <xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output
            doctype-public="-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
            doctype-system="https://checkstyle.org/dtds/configuration_1_3.dtd"/>

        <xsl:template match="node()|@*">
          <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
          </xsl:copy>
        </xsl:template>

        <xsl:template match="module[@name='LineLength']">
          <!-- Delete this module. -->
        </xsl:template>
      </xsl:transform>
      '''
  def transformer = TransformerFactory.newInstance()
      .newTransformer(new StreamSource(new StringReader(xslt)))
  def xml = resources.text.fromArchiveEntry(
      configurations.checkstyleConfig, 'google_checks.xml').asReader()
  def stringWriter = new StringWriter()
  transformer.transform(new StreamSource(xml), new StreamResult(stringWriter))
  return resources.text.fromString(stringWriter.toString())
}

checkstyle {
  toolVersion = checkstyleVersion
  config = readCheckstyleConfig()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多