Checkstyle 代码风格插件的配置和适用

Checkstyle是一款可以帮助开发人员编写符合Java代码编码标准的开发工具; 它可以进行自动化检查, 避免开发者陷入代码规范这种繁琐的事情之中; 使用它可以让我们的工程保持统一的代码规范;


常见自动化CI所采用的插件列表

  • Spotless
  • Checkstyle
  • FindBugs
  • Jacoco
  • Liquibase

在项目中配置使用Checkstyle

在Gradle项目中, 配置使用Checkstyle

gradle构建脚本使用groovy

  1. 首先在build.gradle中引入Checkstyle插件
// 以外部文件的方式引入gradle插件脚本, 方便对build管理, 不至于膨胀过快
apply from: 'gradle/checkstyle.gradle'
  1. 看一下checkstyle.gradle文件里面的内容
/**
 * The Checkstyle Plugin
 *
 * Gradle plugin that performs quality checks on your project's Java source files using Checkstyle
 * and generates reports from these checks.
 *
 * Tasks:
 * Run Checkstyle against {rootDir}/src/main/java: ./gradlew checkstyleMain
 * Run Checkstyle against {rootDir}/src/test/java: ./gradlew checkstyleTest
 *
 * Reports:
 * Checkstyle reports can be found in {project.buildDir}/build/reports/checkstyle
 *
 * Configuration:
 * Checkstyle is very configurable. The configuration file is located at {rootDir}/config/checkstyle/checkstyle.xml
 *
 * Additional Documentation:
 * https://docs.gradle.org/current/userguide/checkstyle_plugin.html
 */

apply plugin: 'checkstyle'

checkstyle {
    // The version of the code quality tool to be used.
    // The most recent version of Checkstyle can be found at https://github.com/checkstyle/checkstyle/releases
    toolVersion = "8.21"

    // The source sets to be analyzed as part of the check and build tasks.
    // Use 'sourceSets = []' to remove Checkstyle from the check and build tasks.
    // sourceSets = [project.sourceSets.main, project.sourceSets.test]

    // Whether or not to allow the build to continue if there are warnings.
    ignoreFailures = false

    // Whether or not rule violations are to be displayed on the console.
    showViolations = true

    // The Checkstyle configuration file to use.
    configFile = rootProject.file('config/checkstyle/checkstyle.xml')

}

// main-->java
checkstyleMain {
     // 代码检查跳过一些我们认为不需要检查的package
    exclude 'me/gavincook/moon/mybatis/**'
    exclude 'me/gavincook/moon/infrastructure/**'
    /*reports {
        // html形式的检查报告生成路径
        html.destination rootProject.file("build/reports/checkstyle/main.html")
    }*/
}

// test-->java
checkstyleTest {
    /*reports {
        html.destination rootProject.file("build/reports/checkstyle/test.html")
    }*/
}
  1. 上面的config/checkstyle/checkstyle.xml就是checkstyle 所要应用检查的规则文件
    文件具体内容可以参考: checkstyle_checks.xml

  2. 在命令行终端执行以下命令对插件进行使用

// 对main-->java包中的java类做检测
gradlew checkstyleMain
// 对test-->java包中的java类做检测
gradlew checkstyleTest

在git管理的项目中, 通过hook执行checkstyle verify

在项目的根目录下的.git文件夹下面添加pre-commit文件, 这个hook就会在本地进行git commit前执行

#!/bin/sh
#set -x
# From gist at https://gist.github.com/chadmaughan/5889802

# run the tests with the gradle wrapper
./gradlew checkstyleMain

# store the last exit code in a variable
RESULT=$?

# return the './gradlew checkstyleMain' exit code
exit $RESULT

初始化本地的hook

因为hook是放在.git文件夹下的, 而这个文件夹的内容不会被提交到远程仓库, 为了所有开发者都能以安装的方式初始化所有hook, 那我们弄个统一的脚本在每个人的本地初始化hook

  1. 在项目根目录下面建一个boot文件(windows下面就是boot.bat)

boot

#/bin/bash

case "$1" in
  "checkstyle")
  open build/reports/checkstyle/main.html
  ;;
  "init-hook")
   cp hook/pre-commit .git/hooks/pre-commit
   chmod a+x .git/hooks/pre-commit
  ;;
esac

boot.bat

@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  boot.bat for windows
@rem
@rem ##########################################################################

set OPTION=%1%
set DIRNAME=%~dp0

if "%OPTION%" == "checkstyle" (
  start %DIRNAME%build\reports\checkstyle\main.html
)

if "%OPTION%" == "init-hook" (
  copy "hook\pre-commit" ".git\hooks\pre-commit"
  echo init-hook execute success
)
  1. 执行脚本初始化方法
// linux
boot init-hook
// windows
boot.bat init-hook

本地进行git commit时会自动执行pre-commit里面的内容

检测通过, 没有输出相关成功提示, 这里只看下检测不通过的错误提示; 这里我们专门写一个style-bugs(方法中的缩进配置的4空格, 但是代码里只有2空格)

 git commit -m "xxx"
[ant:checkstyle] [ERROR] E:\project\gavin\moon-boot\src\main\java\me\gavincook\moon\user\UserService.java:32: Javadoc的第一句缺少一个结束时期。 [SummaryJavadoc]

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
See https://docs.gradle.org/4.8.1/userguide/command_line_interface.html#sec:command_line_warnings
3 actionable tasks: 2 executed, 1 up-to-date

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':checkstyleMain'.
> Checkstyle rule violations were found. See the report at: file:///E:/project/gavin/moon-boot/build/reports/checkstyle/checkstyle.html
  Checkstyle files with violations: 1
  Checkstyle violations by severity: [error:1]


* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

报告如图
Checkstyle 代码风格插件的配置和适用_第1张图片

Over!

你可能感兴趣的:(Plugins,Tool,CI与CD的实践)