End

代码检测工具 Checkstyle 插件

本文地址


目录

代码检测工具 Checkstyle 插件

CheckStyle 能够帮助程序员检查代码是否符合制定的规范。通过将 CheckStyle 的检查引入到项目构建中,可以强制让项目中的所有的开发者遵循制定规范,而不是仅仅停留在纸面上。比如类名未以大写开头、单个方法超过了指定行数、甚至单个方法抛出了3个以上的异常等。

这些检查是基于源码的,不需要编译,执行速度快。

简介

Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard 符合编码标准. It automates the process 使...过程自动化 of checking Java code to spare 使...免于 humans of this boring (but important) task. This makes it ideal 理想 for projects that want to enforce 实施 a coding standard.

Checkstyle is highly configurable and can be made to support almost any coding standard. An example configuration files are supplied supporting the Sun Code Conventions, Google Java Style.

Checkstyle can check many aspects 方面 of your source code. It can find class design problems, method design problems. It also has the ability to check code layout and formatting issues.

检查规则

参考规则

规则说明:

配置文件:

Google's style 里面详细介绍了 Google 的样式标准,可以有条理的查看每一项 Google 样式标准所对应的 Checkstyle 规则,以及每一项的具体配置及对应的测试用例,非常适合用来学习及修改。

图例说明:

  • "--" - There is no rule in this paragraph. (Google 对此的样式标准没有对应的 Checkstyle 规则)
  • "↓" - This paragraph is the high-level point of some group. (此段是某些小组的高级 point)
  • - Existing Check covers all requirements from Google. 完全覆盖
  • - Existing Check covers some part of requirements from Google. 部分覆盖
  • - Requirements are not possible to check by Checkstyle at all. 完全没法检测

Suppressions

在定制好的 checkStyle.xml 文件中,添加一个名为SuppressionFilter的 moudle,在过滤规则文件suppressions.xml中添加相应的过滤规。

可以通过 suppressions.xml 对某个java文件某个包下的所有java文件,过滤某项或多项规则检查。

<!-- https://checkstyle.org/config_filters.html#SuppressionFilter -->
<module name="SuppressionFilter">
    <property name="file" 
        value="${org.checkstyle.google.suppressionfilter.config}"
        default="checkstyle-suppressions.xml" />
    <property name="optional" value="true"/>
</module>
<!-- https://checkstyle.org/config_filters.html#SuppressionXpathFilter -->
<module name="SuppressionXpathFilter">
    <property name="file" 
        value="${org.checkstyle.google.suppressionxpathfilter.config}"
        default="checkstyle-xpath-suppressions.xml" />
    <property name="optional" value="true"/>
</module>

定制 CheckStyle 规则

定制规则思路:对 Google 提供的检查规则进行修改

CheckStyle 检查规则是基于 XML 配置文件的,主要通过 XML 文件中的 module 对检查规则进行配置。

XML 中主要由 module 、property、message 节点构成:

  • module:检查项,如 MethodName 用于检查方法命名;module中有两个比较重要的节点,它们分别是 Checker 和 TreeWalker
    • Checker:配置文件的根节点,必须存在
    • TreeWalker:树遍历器,TreeWalker 会自动去检查指定范围内的每一个 java 源文件,TreeWalker 内部会定义很多 module。
  • property:对应 module 检查项中具体检查属性,如果使用默认值,property 节点可以省略;被指定的 module 都将被对应规则检查
  • message:打印检查出来 message 消息,message 节点可以省略

定制 IDEA Code Style 规则

这里指的是如何定制与 checkStyle.xml 中规则一致的 IDEA 配置。

路径:File -> Settings -> Editor -> Code Style -> Java

IDEA Code Style Jva 主要包括以下几个部分:

  • Tabs and Indents 缩进:使用默认就可以
  • Spaces 空格:主要包括圆括号、操作符、关键字、大括号等左右空格问题,使用默认配置即可
  • Wrapping and Braces 大括号及其包裹内容:支持自动换行、if/while 等关键字format时自动带上大括号、builder模式自动对齐等配置
  • Blank Lines 空行:使用默认配置
  • Java Doc 文档:使用默认配置
  • Imports 导包:根据需要,调整 Imports 顺序
  • Arrangement 排序规则:指定例如 public static final 这些关键字的顺序,建议勾选将get/set方法、override方法放在一起选项
  • Code Generation 代码生成:强烈建议在 Field 前面添加 m 前缀 ,在 static field 前面添加 s 前缀

其他设置项:

  • File -> Settings -> Editor -> Code Style -> Hard wrap at:勾选 wrap on typing:超出最大行宽时自动换行
  • Java -> Method metrics -> Overly long method:方法过长提示,可以修改提示对应的 Severty 级别和范围
  • File -> Settings -> Editor -> General -> Auto Import:勾选自动导包、自动清除无用导包

AS 插件:CheckStyle-IDEA

This plugin provides both real-time and on-demand scanning of Java files with CheckStyle from within IDEA.

Please note this is not an official part of Checkstyle - they neither endorse 认可 nor bear responsibility 负责 for this plugin.

设置:

  • File -> Settings -> Tools -> Checkstyle
  • 可以选择使用内置的规则(内置了 Google 的规则和 Sun 的规则)
  • 也可以点击添加自定义的规则,规则格式和gradle插件中指定的格式一致

使用方式:

  • 在文件右击执行Check Current File
  • CheckStyle面板可以指定使用的规则
  • CheckStyle面板可以指定扫描范围:
    • Check Current File:当前文件
    • Check Module:当前模块
    • Check Project:当前项目
    • Check All Modified Files:所有修改的文件
    • Check Files in the Current Change List:所有在版本管理中修改的文件

gradle 插件

The Checkstyle plugin performs quality checks on your project’s Java source files using Checkstyle and generates reports from these checks.

相关文档:

插件源码

插件相关源码:

Tips:

  • gradle 中使用的 checkstyle 插件实际定义在 plugins/quality 包中
  • 当前 gradle 使用的默认 checkstyle 版本为:8.37

配置选项

gradle 中的 Checkstyle 插件可以使用的配置选项有:

  • configconfigDir(废弃)configDirectoryconfigFileconfigProperties:指定要使用的自定义规则集
  • ignoreFailures:有警告时是否允许构建继续进行
  • maxErrorsmaxWarnings:停止构建之前允许的最大失败数/警告数,默认值为0/Integer.MAX_VALUE
  • showViolations:是否将结果写入标准输出中,设为true时可以通过点击链接快速定位到问题代码位置
  • classpath:包含要使用的 Checkstyle 库的类路径
  • checkstyleClasspath:包含要分析的 compiled classes 的类路径
  • reports:生成的报告文件存放位置
    • reports.html.enabled:生成xml还是html,只能有一个为true
    • reports.xml.enabled
    • reports.html.destination:对应的输出地址
    • reports.xml.destination

从父类继承过来的选项有:

  • source:需要进行代码检测的源码路径
  • include:需要检查的文件。可以多次调用此方法以追加新的规范
  • exclude:忽略检查的文件。可以多次调用此方法以追加新的规范

最佳集成案例

在 app 的build.gradle增加如下代码:

plugins {
    id 'com.android.application'
    id 'checkstyle'
}

checkstyle {
    toolVersion = "8.37" //使用指定的checkstyle版本,当前 gradle 使用的默认版本为 8.37
}
def ruleFilePath = "${project.rootDir}/codeCheck/" //检查规则文件路径
def sourcePath = "${project.rootDir}/app/src"  //需要进行代码检测的源码路径
def reportFilePath = "${project.rootDir}/codeCheck/reports/" //生成的报告文件存放位置

task checkstyle(type: Checkstyle, group: "codeCheck") {
    configFile = file(ruleFilePath + "checkstyle_rule.xml") //使用自定义规则集文件
    ignoreFailures = true //有警告时是否允许构建继续进行
    showViolations = true //是否将结果写入标准输出中,设为true时可以通过点击链接快速定位到问题代码位置
    source = files(sourcePath) //需要进行代码检测的源码路径
    classpath = files() //包含要使用的 Checkstyle 库的类路径
    include '**/*.java' //需要检查的文件
    exclude '**/*.xml' //忽略检查的文件

    reports {
        xml.enabled = false //生成xml还是html,只能有一个为true
        html.enabled = true
        xml.destination = file(reportFilePath + "checkstyle_result.xml") //对应的生成的报告文件存放位置
        html.destination = file(reportFilePath + "checkstyle_result.html")
    }
}

检测结果案例

[ant:checkstyle] [WARN] SecondActivity.java:7:1: 导入组之前的额外空行 'androidx.annotation.Nullable'。 [CustomImportOrder]
[ant:checkstyle] [WARN] SecondActivity.java:9: 缺少摘要javadoc。 [SummaryJavadoc]
[ant:checkstyle] [WARN] SecondActivity.java:16:50: Parameter name 'SS' must match pattern '^[a-z]([a-z0-9][a-zA-Z0-9]*)?$'. [ParameterName]
[ant:checkstyle] [WARN] SecondActivity.java:16:50: 名称 'SS' 中不能出现超过 '1' 个连续大写字母。 [AbbreviationAsWordInName]

如果认为某项检测结果不合自己项目的要求,可以在配置文件中搜索后面的关键字,将相应项改成你期望的配置即可,非常方便。

Jenkins 插件

Jenkins 上有两款支持 Checkstyle 的插件:

  • Report Info:同时支持 Surefire, PMD, Findbugs and Checkstyle
  • Violations:下载量最大,但是因不再维护(5年没有更新了)所以不建议使用

This plugin allows you to see in a view some information from Surefire, PMD, Findbugs and Checkstyle reports.

Usage

In the jobs you want in the report info view, add Generated report info Post-build action.

You can add some folders to exclude.

Create a new Report Info view

Add the projects you want to see in the view

Now you need the rebuild the job to see the report information.

2017-05-03

posted @ 2017-05-03 17:25  白乾涛  阅读(2260)  评论(0编辑  收藏  举报