每个开发都有自己的开发风格,在一个项目中开发风格混用,多人协作开发时,不光代码风格不好看,可读性差,而且很简单冲突。风格类的编程规范,要点在于保证代码的可读性和风格的一致性。例如,怎么运用空格、怎么命名、怎么运用大小写、是运用驼峰仍是下划线、怎么运用大括号,等等。编码风格是人为约好的,假如没有查看,很难得到落实。Checkstyle是一款能够规范Java代码的东西,首要关注代码风格的查看,默许提供了Sun/Google的代码风格规范装备文件。同时,Checkstyle也是高度可定制的,能够根据自己的需求进行装备。

CheckStyle工作流程

  1. 初始化。调用CheckStyle集成接口输入参数以及CheckStyle运用的装备文件,接着会创立Configuration对象,运用Configuration创立Checker实例,生成输入文件列表传递给Checker开端履行。
    用CheckStyle规范Java工程
  2. 履行。收到文件列表后,Checker模块会调用前面初始化的四种不同责任子模块完成对输入文件的代码风格查看。
    用CheckStyle规范Java工程

CheckStyle查看阶段最常用的模块是TreeWalker,他通过Antlr4将Java源文件转换成笼统语法树AST,选用Visitor模式遍历AST,完成风格的查看。下面是checkstyle-9.3-all.jar中的截图,能够很清楚的看到运用了g4语法文件,并生成了Visitor接口。

用CheckStyle规范Java工程

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

参阅资料

  • checkstyle overview
  • checkstyle 指令行
  • Google开发风格
  • 规范查看界说