Checkstyle 代碼風格插件的配置和適用

Checkstyle是一款可以幫助開發人員編寫符合Java代碼編碼標準的開發工具; 它可以進行自動化檢查, 避免開發者陷入代碼規範這種繁瑣的事情之中; 使用它可以讓我們的工程保持統一的代碼規範;


常見自動化CI所採用的插件列表

在項目中配置使用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 report

Over!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章