【发布时间】:2018-05-25 16:40:50
【问题描述】:
有没有办法通过类名模式从 PMD 规则中排除类?
我正在寻找类似的东西:
<rule ref="rulesets/java/coupling.xml/ExcessiveImports">
<exclude-pattern>.*Test\.class</exclude-pattern>
</rule>
我知道违规抑制XPath 方法,但我觉得它太丑/太复杂了。
谢谢!
【问题讨论】:
有没有办法通过类名模式从 PMD 规则中排除类?
我正在寻找类似的东西:
<rule ref="rulesets/java/coupling.xml/ExcessiveImports">
<exclude-pattern>.*Test\.class</exclude-pattern>
</rule>
我知道违规抑制XPath 方法,但我觉得它太丑/太复杂了。
谢谢!
【问题讨论】:
如果类名以DTO 结尾,则此规则将忽略特定规则:
<rule ref="category/java/bestpractices.xml/UnusedPrivateField">
<properties>
<!--Ignore UnusedPrivateField on classes where the class name ends with DTO-->
<property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration['.*DTO']"/>
</properties>
</rule>
【讨论】:
Note the use of . to refer to the context node. Using // at the start of the expression should be avoided, as it would test all nodes in the file, and suppress more violations than expected. 有关更多信息,请参阅 here。
恐怕没有。您目前可以使用 <exclude-pattern> 从分析中完全忽略文件,但不适用于特定规则。
这背后的基本原理是,在您的代码库上执行规则集时,您应该尽可能保持一致。这样做时,很少考虑例外情况:
您的示例似乎指向第一个场景的方向。如果您想要一套更宽松的测试类规则,您应该创建一个单独的配置并让 PMD 运行两个单独的分析。
然而,这超出了 PMD 本身的范围,而是取决于您如何运行它。在 Gradle / Ant / CLI 上,这很容易实现。不幸的是,在 Maven 上,它目前不受支持(可以找到功能请求并投票 here)
如果您认为您还有其他场景,前两个未涵盖,请考虑在https://github.com/pmd/pmd/issues 上发布功能请求
【讨论】:
main 和 test 设置不同规则集的痛点,同时还解释了 Maven 没有目前不支持这种情况。 FWIW,我发现 exclude-pattern 当前行为的基本原理是 PMD 插件过于规范的立场。良好的默认值是一件好事,但是这种程度的不灵活会降低工具的功能而没有补偿性增益。