项目配置
对于Spring Boot项目使用Maven作为构建工具,采用类似的方式配置Git的pre-commit
钩子来运行Checkstyle。以下是一个基本的步骤:
- 配置Checkstyle插件:
在Maven的pom.xml
文件中,添加Checkstyle插件的配置。确保配置文件checkstyle.xml
中定义了你期望的代码规范。示例插件配置如下:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.2</version> <!-- 使用最新版本 -->
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.44</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<configLocation>config/checkstyle.xml</configLocation>
<consoleOutput>true</consoleOutput>
<!-- 随机返回非零的数 -->
<failsOnError>true</failsOnError>
<!-- 警告阻塞 -->
<failOnViolation>true</failOnViolation>
</configuration>
</plugin>
</plugins>
</build>
这将在validate
阶段执行Checkstyle检查。
- 创建pre-commit脚本:
在项目的.git/hooks
目录下创建一个名为pre-commit
的文件,其中包含运行Maven Checkstyle插件的命令。
#!/bin/bash
# Run Checkstyle before committing
clean checkstyle:check
# Get the exit code of the Checkstyle task
MVN_RESULT=$?
echo "MVN_RESULT: $MVN_RESULT"
# Check if Maven Checkstyle fails or has warnings, prevent the commit
if [ $MVN_RESULT -ne 0 ]; then
echo "Maven Checkstyle failed. Commit aborted."
echo "MVN_RESULT: $MVN_RESULT"
exit 1
fi
请注意,这里使用的是mvn validate
,因为Maven的validate
阶段包含了checkstyle:check
目标。
- 赋予执行权限:
确保pre-commit
文件有执行权限。可以使用以下命令:
chmod +x .git/hooks/pre-commit
- 测试:
在提交代码之前,进行一次测试。如果Checkstyle检查不通过,提交将被阻止。
这样配置后,每次在提交代码时,Git将运行pre-commit
钩子,它将触发Maven Checkstyle插件,以确保代码符合规范。
完成的项目代码大家可以参考 https://github.com/yanghaiji/checkstyle-githooks
Checkstyle.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<!-- 字符集位utf8 -->
<property name="charset" value="UTF-8"/>
<!-- 设置违规问题的默认严重程度为“警告” error | warning | info -->
<property name="severity" value="warning"/>
<!-- 指定要由Checkstyle处理的文件扩展名(Java、properties和XML文件) -->
<property name="fileExtensions" value="java, properties, xml , yaml , yml"/>
<!-- 排除所有'module-info.java'文件 -->
<!-- See https://checkstyle.org/config_filefilters.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- 检查空白字符 -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="LineLength">
<property name="max" value="120"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/