Apache Maven Checkstyle插件

x33g5p2x  于2022-10-14 转载在 Apache  
字(2.5k)|赞(0)|评价(0)|浏览(409)

1.概述

Checkstyle插件生成关于开发人员使用的代码样式的报告。

2.插件目标

Checkstyle插件有三个目标:

**checkstyle:checkstyle*是执行checkstyle分析并生成违规报告的报告目标。
**checkstyle:checkstyle聚合是一个报告目标,它执行checkstyle分析并生成关于多模块React器构建中违规的聚合HTML报告。
**checkstyle:check
是执行checkstyle分析并向控制台输出违规或违规计数的目标,可能会导致构建失败。它还可以配置为重复使用以前的分析。

3.使用

以下示例描述了Checkstyle插件的基本用法。

生成检查样式报告作为项目报告的一部分

要将Checkstyle报告作为ProjectReports的一部分生成,请在pom.xml的部分添加CheckstylePlugin。

<project>
  ...
   <reporting>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <version>3.0.0</version>
          <reportSets>
            <reportSet>
              <reports>
                <report>checkstyle</report>
              </reports>
            </reportSet>
          </reportSets>
        </plugin>
      </plugins>
    </reporting>
  ...
</project>

然后,执行站点阶段以生成报告。

mvn site

生成独立的检查样式报告

您还可以通过从命令行显式执行Checkstyle:Checkstyle目标来生成Checkstyle报告。您不需要在pom中指定Checkstyle插件。xml,除非您想使用特定的配置。

mvn checkstyle:checkstyle

作为生成的一部分检查冲突

如果要向控制台报告或生成失败,则必须将checkstyle::check的执行添加到元素中,并配置所需的任何选项。
在元素中设置的选项对元素中的执行没有任何影响。
请注意,checkstyle::check所绑定的阶段非常重要。如果绑定到验证阶段,它将在编译代码之前检查代码。如果代码无效,checkstyle报告的解析错误可能与javac编译器预期的错误不同。然而,它可以保证运行。另一个流行的选项是将其绑定到稍后运行的验证阶段(并允许javac编译器在checkstyle之前标记无效代码)。然而,如果开发人员通常只在推送更改之前使用“mvn测试”,那么checkstyle将不会在测试阶段之后进行验证时运行。
例如:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-checkstyle-plugin</artifactId>
   <version>3.0.0</version>
   <executions>
     <execution>
       <id>validate</id>
       <phase>validate</phase>
       <configuration>
         <configLocation>checkstyle.xml</configLocation>
         <encoding>UTF-8</encoding>
         <consoleOutput>true</consoleOutput>
         <failsOnError>true</failsOnError>
         <linkXRef>false</linkXRef>
       </configuration>
       <goals>
         <goal>check</goal>
       </goals>
     </execution>
   </executions>
 </plugin>

4.示例

使用自定义检查样式检查器配置示例

可以定义自定义Checker配置xml文件,然后通过URL、file或构建类路径资源引用引用该文件。
要引用自定义检查样式检查器配置,请使用configLocation参数。

<project>
  ...
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-checkstyle-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <configLocation>checkstyle.xml</configLocation>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
  ...
</project>

5.结论

在这个快速指南中,我们介绍了Checkstyle插件,并给出了使用和定制它的说明。我们还看到了不同的插件目标及其用法。
参考:https://maven.apache.org/plugins/maven-checkstyle-plugin/

相关文章