用CheckStyle规范Java工程
每个开发都有自己的开发风格,在一个项目中开发风格混用,多人协作开发时,不但代码风格不好看,可读性差,而且很容易冲突。风格类的编程规范,重点在于保证代码的可读性和风格的一致性。例如,如何使用空格、如何命名、如何使用大小写、是使用驼峰还是下划线、如何使用大括号,等等。编码风格是人为约定的,如果没有检查,很难得到落实。Checkstyle是一款能够规范Java代码的工具,主要关注代码风格的检查,默认提供了Sun/Google的代码风格规范配置文件。同时,Checkstyle也是高度可定制的,可以根据自己的需要进行配置。
CheckStyle工作流程
- 初始化。调用CheckStyle集成接口输入参数以及CheckStyle使用的配置文件,接着会创建Configuration对象,使用Configuration创建Checker实例,生成输入文件列表传递给Checker开始执行。
- 执行。收到文件列表后,Checker模块会调用前面初始化的四种不同职责子模块完成对输入文件的代码风格检查。
CheckStyle检查阶段最常用的模块是TreeWalker,他通过Antlr4将Java源文件转换成抽象语法树AST,采用Visitor模式遍历AST,完成风格的检查。下面是checkstyle-9.3-all.jar中的截图,可以很清楚的看到使用了g4语法文件,并生成了Visitor接口。
TreeWalker的核心代码如下,可以去研究下,在这段代码中我们看到了JavaParser.parse(contents)调用,将文本转换成了AST,调用了walk(rootAST, contents, AstState.ORDINARY)方法实现了遍历,一旦检查到违规节点,将会记录违规事件,并最终输出。
protected void processFiltered(File file, FileText fileText) throws CheckstyleException {
// check if already checked and passed the file
if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) {
final FileContents contents = getFileContents();
final DetailAST rootAST = JavaParser.parse(contents);
if (!ordinaryChecks.isEmpty()) {
walk(rootAST, contents, AstState.ORDINARY);
}
if (!commentChecks.isEmpty()) {
final DetailAST astWithComments = JavaParser.appendHiddenCommentNodes(rootAST);
walk(astWithComments, contents, AstState.WITH_COMMENTS);
}
if (filters.isEmpty()) {
addViolations(violations);
}
else {
final SortedSet<Violation> filteredViolations =
getFilteredViolations(file.getAbsolutePath(), contents, rootAST);
addViolations(filteredViolations);
}
violations.clear();
}
}
以空catch为例,EmptyCatchBlockCheck#visitToken方法会检查当前节点是否为catch节点,内容是否为空,如果是则记录一条违规事件。
public void visitToken(DetailAST ast) {
visitCatchBlock(ast);
}
/**
* Visits catch ast node, if it is empty catch block - checks it according to
* Check's options. If exception's variable name or comment inside block are matching
* specified regexp - skips from consideration, else - puts violation.
*
* @param catchAst {@link TokenTypes#LITERAL_CATCH LITERAL_CATCH}
*/
private void visitCatchBlock(DetailAST catchAst) {
if (isEmptyCatchBlock(catchAst)) {
final String commentContent = getCommentFirstLine(catchAst);
if (isVerifiable(catchAst, commentContent)) {
log(catchAst.findFirstToken(TokenTypes.SLIST), MSG_KEY_CATCH_BLOCK_EMPTY);
}
}
}
检查规则配置文件
CheckStyle检查规则的配置文件一定要和检查Jar匹配,否则在执行检查时会报错。检查规则都可以从检查Jar中获取,以checkstyle-9.3.jar为例,解压后的内容如下,可以看到jar中自带了2个规则文件,分别为google_checks.xml和sun_checks.xml,也即Google和Sun的开发风格。如果要自定义自己的规则,可以直接拷贝出来修改,相关规则描述参考Google开发规则及标准检查定义。
.
├── META-INF
│ ├── MANIFEST.MF
│ └── maven
│ └── com.puppycrawl.tools
│ └── checkstyle
│ ├── pom.properties
│ └── pom.xml
├── com
│ └── puppycrawl
│ └── tools
│ └── ...
├── google_checks.xml
└── sun_checks.xml
下面是从Jar中提取出的Google风格的检查规则并做了一些修改,可以根据自己工程需要进行调整。
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!--
Checkstyle configuration that checks the Google coding conventions from Google Java Style
that can be found at https://google.github.io/styleguide/javaguide.html
Checkstyle is very configurable. Be sure to read the documentation at
http://checkstyle.org (or in your downloaded distribution).
To completely disable a check, just comment it out or delete it from the file.
To suppress certain violations please review suppression filters.
Authors: Max Vetrenko, Ruslan Diachenko, Roman Ivanov.
-->
<module name = "Checker">
<property name="charset" value="UTF-8"/>
<!-- 规则等级,error、warning、info,此处针对所有规则生效,规则单独配置需要加到规则module中 -->
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module-info.java$"/>
</module>
<!-- 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>
<!-- Checks for whitespace -->
<!-- See http://checkstyle.org/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<!-- 优化,每行不允许超过130个字符 -->
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<property name="max" value="130"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format"
value="\u00(09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message"
value="Consider using special escape sequence instead of octal value or Unicode escaped value."/>
</module>
<module name="AvoidEscapedUnicodeCharacters">
<property name="allowEscapesForControlCharacters" value="true"/>
<property name="allowByTailComment" value="true"/>
<property name="allowNonPrintableEscapes" value="true"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap">
<property name="tokens" value="PACKAGE_DEF, IMPORT, STATIC_IMPORT"/>
</module>
<module name="EmptyBlock">
<property name="option" value="TEXT"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
</module>
<module name="NeedBraces">
<property name="tokens"
value="LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE"/>
</module>
<module name="LeftCurly">
<property name="tokens"
value="ANNOTATION_DEF, CLASS_DEF, CTOR_DEF, ENUM_CONSTANT_DEF, ENUM_DEF,
INTERFACE_DEF, LAMBDA, LITERAL_CASE, LITERAL_CATCH, LITERAL_DEFAULT,
LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF,
LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, METHOD_DEF,
OBJBLOCK, STATIC_INIT, RECORD_DEF, COMPACT_CTOR_DEF"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlySame"/>
<property name="tokens"
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE,
LITERAL_DO"/>
</module>
<module name="RightCurly">
<property name="id" value="RightCurlyAlone"/>
<property name="option" value="alone"/>
<property name="tokens"
value="CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, STATIC_INIT,
INSTANCE_INIT, ANNOTATION_DEF, ENUM_DEF, INTERFACE_DEF, RECORD_DEF,
COMPACT_CTOR_DEF"/>
</module>
<module name="SuppressionXpathSingleFilter">
<!-- suppresion is required till https://github.com/checkstyle/checkstyle/issues/7541 -->
<property name="id" value="RightCurlyAlone"/>
<property name="query" value="//RCURLY[parent::SLIST[count(./*)=1]
or preceding-sibling::*[last()][self::LCURLY]]"/>
</module>
<module name="WhitespaceAfter">
<property name="tokens"
value="COMMA, SEMI, TYPECAST, LITERAL_IF, LITERAL_ELSE,
LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, DO_WHILE"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<property name="ignoreEnhancedForColon" value="false"/>
<property name="tokens"
value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR,
BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, DO_WHILE, EQUAL, GE, GT, LAMBDA, LAND,
LCURLY, LE, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY,
LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SWITCH, LITERAL_SYNCHRONIZED,
LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN,
NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, RCURLY, SL, SLIST, SL_ASSIGN, SR,
SR_ASSIGN, STAR, STAR_ASSIGN, LITERAL_ASSERT, TYPE_EXTENSION_AND"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="MultipleVariableDeclarations"/>
<module name="ArrayTypeStyle"/>
<module name="MissingSwitchDefault"/>
<module name="FallThrough"/>
<!-- Long型常量后缀 -->
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<!-- 空行规则 -->
<module name="EmptyLineSeparator">
<property name="tokens"
value="PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF,
STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF, RECORD_DEF,
COMPACT_CTOR_DEF"/>
<property name="allowNoEmptyLineBetweenFields" value="true"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapDot"/>
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapComma"/>
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ELLIPSIS is EOL until https://github.com/google/styleguide/issues/259 -->
<property name="id" value="SeparatorWrapEllipsis"/>
<property name="tokens" value="ELLIPSIS"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<!-- ARRAY_DECLARATOR is EOL until https://github.com/google/styleguide/issues/258 -->
<property name="id" value="SeparatorWrapArrayDeclarator"/>
<property name="tokens" value="ARRAY_DECLARATOR"/>
<property name="option" value="EOL"/>
</module>
<module name="SeparatorWrap">
<property name="id" value="SeparatorWrapMethodRef"/>
<property name="tokens" value="METHOD_REF"/>
<property name="option" value="nl"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF,
ANNOTATION_DEF, RECORD_DEF"/>
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LambdaParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Catch parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="PatternVariableName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Pattern variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="RecordComponentName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<message key="name.invalidPattern"
value="Record component name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="RecordTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Record type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="InterfaceTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Interface type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<!-- 缩进规则 -->
<module name="Indentation">
<property name="basicOffset" value="2"/>
<property name="braceAdjustment" value="2"/>
<property name="caseIndent" value="2"/>
<property name="throwsIndent" value="4"/>
<property name="lineWrappingIndentation" value="4"/>
<property name="arrayInitIndent" value="2"/>
</module>
<!-- 标识符驼峰规则 -->
<module name="AbbreviationAsWordInName">
<property name="ignoreFinal" value="false"/>
<property name="allowedAbbreviationLength" value="5"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, ANNOTATION_DEF, ANNOTATION_FIELD_DEF,
PARAMETER_DEF, VARIABLE_DEF, METHOD_DEF, PATTERN_VARIABLE_DEF, RECORD_DEF,
RECORD_COMPONENT_DEF"/>
</module>
<module name="NoWhitespaceBeforeCaseDefaultColon"/>
<!-- 重载方法不能被其他方法间隔开 -->
<module name="OverloadMethodsDeclarationOrder"/>
<!-- 局部变量的声明与使用默认3行 -->
<module name="VariableDeclarationUsageDistance"/>
<!-- import规则咋不做调整 -->
<module name="CustomImportOrder">
<property name="sortImportsInGroupAlphabetically" value="true"/>
<property name="separateLineBetweenGroups" value="true"/>
<property name="customImportOrderRules" value="STATIC###THIRD_PARTY_PACKAGE"/>
<property name="tokens" value="IMPORT, STATIC_IMPORT, PACKAGE_DEF"/>
</module>
<module name="MethodParamPad">
<property name="tokens"
value="CTOR_DEF, LITERAL_NEW, METHOD_CALL, METHOD_DEF,
SUPER_CTOR_CALL, ENUM_CONSTANT_DEF, RECORD_DEF"/>
</module>
<module name="NoWhitespaceBefore">
<property name="tokens"
value="COMMA, SEMI, POST_INC, POST_DEC, DOT,
LABELED_STAT, METHOD_REF"/>
<property name="allowLineBreaks" value="true"/>
</module>
<module name="ParenPad">
<property name="tokens"
value="ANNOTATION, ANNOTATION_FIELD_DEF, CTOR_CALL, CTOR_DEF, DOT, ENUM_CONSTANT_DEF,
EXPR, LITERAL_CATCH, LITERAL_DO, LITERAL_FOR, LITERAL_IF, LITERAL_NEW,
LITERAL_SWITCH, LITERAL_SYNCHRONIZED, LITERAL_WHILE, METHOD_CALL,
METHOD_DEF, QUESTION, RESOURCE_SPECIFICATION, SUPER_CTOR_CALL, LAMBDA,
RECORD_DEF"/>
</module>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens"
value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR,
LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF,
TYPE_EXTENSION_AND "/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationMostCases"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF,
RECORD_DEF, COMPACT_CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="id" value="AnnotationLocationVariables"/>
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<!-- @param, @return, @throws, @deprecated等不允许为空 -->
<module name="NonEmptyAtclauseDescription"/>
<module name="InvalidJavadocPosition"/>
<module name="JavadocTagContinuationIndentation"/>
<!-- 第一句注释结尾必须有标点,@return不允许有文字 -->
<!--
<module name="SummaryJavadoc">
<property name="forbiddenSummaryFragments"
value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/>
</module>
-->
<module name="JavadocParagraph"/>
<module name="RequireEmptyLineBeforeBlockTagGroup"/>
<module name="AtclauseOrder">
<property name="tagOrder" value="@param, @return, @throws, @deprecated"/>
<property name="target"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/>
</module>
<!-- 方法注释 -->
<module name="JavadocMethod">
<property name="accessModifiers" value="public"/>
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF, COMPACT_CTOR_DEF"/>
</module>
<module name="MissingJavadocMethod">
<property name="scope" value="public"/>
<property name="minLineCount" value="2"/>
<property name="allowedAnnotations" value="Override, Test"/>
<property name="tokens" value="METHOD_DEF, CTOR_DEF, ANNOTATION_FIELD_DEF,
COMPACT_CTOR_DEF"/>
</module>
<module name="MissingJavadocType">
<property name="scope" value="protected"/>
<property name="tokens"
value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF,
RECORD_DEF, ANNOTATION_DEF"/>
<property name="excludeScope" value="nothing"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="SingleLineJavadoc"/>
<module name="EmptyCatchBlock">
<property name="exceptionVariableName" value="expected"/>
</module>
<module name="CommentsIndentation">
<property name="tokens" value="SINGLE_LINE_COMMENT, BLOCK_COMMENT_BEGIN"/>
</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>
</module>
</module>
Maven集成
Pom配置
在pom中增加maven-checkstyle-plugin插件,具体如下:
<!-- CheckStyle report -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.2.2</version>
<configuration>
<configLocation>check-style/google-check-style.xml</configLocation>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<consoleOutput>true</consoleOutput>
<violationSeverity>warning</violationSeverity>
<outputEncoding>UTF-8</outputEncoding>
<failOnViolation>true</failOnViolation>
<failsOnError>true</failsOnError>
<!-- 排除不检查的代码,多个以逗号分割 -->
<excludes>**/antlr4/**/*</excludes>
</configuration>
<dependencies>
<!-- checkstyle真正执行的jar,与检查规则文件需要匹配,否则会报错 -->
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>9.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
其中,一些关键配置项如下:
- configLocation:用于指定检查规则文件,用户可以自己指定规则文件,也可以使用插件自带的规则文件。如果用户自定义检查规则文件,一定要确保两者匹配,否则会报错。插件自带的规则文件在上文已经介绍过了,这里多提一句,默认使用的风格为Sun。
- includes:要检查的文件列表,多个以逗号分割。
- excludes:要排除的文件列表,多个以逗号分割。
- includeTestSourceDirectory:是否包含测试文件。
- consoleOutput:是否在控制台输出。
- violationSeverity: Maven Checkstyle插件认为代码违规的最低严重级别,值包括error、warning、info。检查规则文件中severity标明的是每个检查项的严重程度。比如检查文件中配置的是warning,而Maven插件中配置的是error,则Maven插件不会认为是违规。
- failOnViolation:代码检查出现违规,是否视为构建失败,默认为true,即出现违规则构建失败,用于代码违规的配置。
- failsOnError:检查出现错误,是否视为构建失败,默认为true,即出现错误则构建失败,检查工具本身错误的配置。
- 依赖:如果使用插件自带的检查规则配置,不需要配置checkstyle依赖,插件jar与检查规则配置本身就匹配。如果使用自定义检查规则,需要注意自定义检查规则与插件jar是否匹配,不匹配会报错。
- 与Maven执行阶段绑定:上述配置中就与Maven的validate阶段绑定。
执行命令
- checkstyle:check: 执行 Checkstyle 分析并将违规或违规数量输出到控制台,可能会导致构建失败。
- checkstyle:checkstyle: 一个报告任务,执行 Checkstyle 分析并在 Checkstyle 发现违规时生成 HTML 报告。
与Maven阶段绑定后,可以调用Maven命令来触发检查,上述绑定的为validate阶段,可以使用mvn validate命令,后续在编译、打包时,都会触发风格检查。当然,与Maven集成的检查方式,每次检查时都会检查全量文件,工程文件较多时,检查会比较慢。
Git集成实现提交时检查
上面提到的与Maven集成,需要在打包或者开发者主动执行才会触发检查,如果开发者不触发检查,还是会将不符合规范的代码提交到仓库中。这时候可以利用Git Hook来实现代码再提交时的自动检查。
Git仓库的目录.git下, 有一个hooks文件夹, 其中放置了Git各阶段的钩子, 可以在执行相应的命令的时候被自动执行。如果想要在执行git commit时自动进行代码风格检查,可以在.git/hooks目录中创建一个pre-commit文件,文件内容如下:
#!/bin/bash
mvn validate
exit $?
在提交代码时,会自动触发代码风格检查,检查失败将会阻断commit流程。当然,如果在紧急时需要提交,可以加上--no-verify命令,跳过检查。
当然,上述检查还有一个明显不足,上面也有提到,那就是每次提交都会触发全量代码扫描,没有必要且比较耗时,我们只需要关注增量修改的代码的检查。为此,我可以利用CheckStyle命令行模式,每次只检查有修改的文件,下面给出一段检查脚本。
#!/bin/bash
# cp ./check-style/pre-commit.sh ./.git/hooks/
echo -e "\033[34m[style check]\033[0m start..."
wd=`pwd`
check_jar_path="$wd/check-style/checkstyle-9.3-all.jar"
check_xml_path="$wd/check-style/google-check-style.xml"
rm -f temp
files=`git status --porcelain | sed s/^...// | grep '.java$' | tr '\n' ' '`
java -jar $check_jar_path -c $check_xml_path $files > temp 2>&1
cat temp
error=`cat temp | grep -E '[(WARN|ERROR)]'`
rm -rf temp
if [ -n "$error" ]
then
echo -e "\033[31m[style check] failed! Please modify it before submitting it!\033[0m"
exit 1
fi
echo -e "\033[34m[style check]\033[0m done."
exit 0
参考资料
转载自:https://juejin.cn/post/7246777426666143781