如何在checkstyle.xml中为指定文件排除FileLength检查?
问题描述
运行pre-commit的checkstyle钩子时触发报错:
checkstyle...............................................................Failed - hook id: checkstyle - exit code: 4 Starting audit... [ERROR] /some_path/AnotherSomeFile.java:1: File length is 1,950 lines (max allowed is 1,000). [FileLength] [ERROR] /some_path/someFile.java:1: File length is 1,676 lines (max allowed is 1,000). [FileLength] Audit done. Checkstyle ends with 4 errors.
此前尝试在<module name="TreeWalker">内添加<module name="SuppressionCommentFilter"/>,并在目标文件顶部加// CHECKSTYLE:OFF来禁用检查,但因FileLength模块必须置于TreeWalker之外,该过滤规则对其无效。试过将FileLength移入TreeWalker、把SuppressionCommentFilter移至TreeWalker同级/父级,均不被允许。需求是在checkstyle.xml中为src/some_path/file_one.java、src/some_path/file_two.java等4个文件排除FileLength检查。
解决方法
方法1:直接在checkstyle.xml中配置抑制规则
在checkstyle.xml的根模块下(与TreeWalker同级)添加SuppressionFilter模块,指定要禁用的检查规则和目标文件:
<module name="SuppressionFilter"> <!-- 指定要禁用的检查规则为FileLength --> <property name="checks" value="FileLength"/> <!-- 用竖线分隔需要排除的文件路径,确保路径与checkstyle扫描路径一致 --> <property name="files" value="src/some_path/file_one.java|src/some_path/file_two.java|src/some_path/file_three.java|src/some_path/file_four.java"/> </module>
方法2:通过外部抑制文件配置(适合规则较多的场景)
- 在checkstyle.xml根模块下添加
SuppressionFilter,指定外部抑制文件路径:
<module name="SuppressionFilter"> <property name="file" value="config/suppressions.xml"/> </module>
- 创建
config/suppressions.xml文件,写入针对目标文件的抑制规则:
<?xml version="1.0"?> <!DOCTYPE suppressions PUBLIC "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "https://checkstyle.org/dtds/suppressions_1_2.dtd"> <suppressions> <suppress checks="FileLength" files="src/some_path/file_one.java"/> <suppress checks="FileLength" files="src/some_path/file_two.java"/> <suppress checks="FileLength" files="src/some_path/file_three.java"/> <suppress checks="FileLength" files="src/some_path/file_four.java"/> </suppressions>
这两种方式都能绕过TreeWalker的限制,直接针对特定文件禁用FileLength检查,无需修改原有FileLength模块的位置。
内容的提问来源于stack exchange,提问作者a.t.
相关产品推荐
相关产品推荐

