17/10/2019

[Maven] checkstyle during build

If you use autoformatting (and you should) for your code, you might also want to check for formatting violations as part of a build to ensure the style is consistent after every push. We will take a look at how to configure Google style, but this procedure works for any pair of files properly written.


You will need two files for this, a codestyle and a checkstyle. These links are simply a suggestion, the important thing is your autoformat rules and check rules match, so be sure to pick the correct file version for both.

Once you have them, you can place them in your project wherever you like and you can configure your IDE to use the codestyle file when autoformatting.

You can then configure your build to perform the checkstyle which will generate a report listing all the found violations. I would suggest NOT to fail the build when a violation is spotted, but to produce a warning and store the report somewhere, you should enable this feature only when you are confident enough that your setup is stable and won't annoy people too much.

To execute the style checks during a build, use the Maven checkstyle plugin and configure it as such:

 <plugin>  
  <groupId>org.apache.maven.plugins</groupId>  
  <artifactId>maven-checkstyle-plugin</artifactId>  
  <version>3.1.0</version>  
  <configuration>  
   <configLocation>${project.basedir}/google-checks.xml</configLocation>  
   <encoding>UTF-8</encoding>  
   <consoleOutput>true</consoleOutput>  
   <failsOnError>true</failsOnError>  
   <linkXRef>false</linkXRef> 
   <outputDirectory>${project.build.directory}/site/checkstyle</outputDirectory>  
  </configuration>  
  <executions>  
   <execution>  
    <id>validate</id>  
    <phase>validate</phase>  
    <goals>  
     <goal>check</goal>  
    </goals>  
   </execution>  
  </executions>  
 </plugin>  


Now it will run as part of the validate phase, which is normally executed during the default lifecycle builds, generating the report in folder target/site/checkstyle. You can however run it independently by executing the checkstyle:check goal.

Sometimes, you cannot abide by the enforced rules for whatever reasons, therefore you might want to exclude some parts of your code from the check, either entire packages and classes or just code lines; you can do this by adding the excludes section under the configuration element:

 <excludes>FOLDER/**,PATH/TO/PACKAGE/**</excludes>  


or by encapsulating the lines of code to be ignored in:

//CHECKSTYLE:OFF
your code
//CHECKSTYLE:ON

Remember to always turn it back on!

For this last part to work, you need to modify the checkstyle file to include this line under the TreeWalker node:

 <module name="SuppressionCommentFilter" />  



No comments:

Post a Comment

With great power comes great responsibility