方法1:使用Maven插件检查Git状态
在pom.xml
中配置exec-maven-plugin
,在构建前检查未提交的代码:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>check-uncommitted-changes</id>
<phase>validate</phase> <!-- 在验证阶段执行 -->
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>git</executable>
<arguments>
<argument>diff</argument>
<argument>--quiet</argument>
<argument>HEAD</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
说明:
-
git diff --quiet HEAD
命令会检测工作区与最新提交的差异。若有未提交的修改,返回非零状态,导致Maven构建失败。 -
仅检测已跟踪文件:若需包含未跟踪文件(新增未提交),改用
git status --porcelain
检查。
方法2:自定义脚本检查(跨平台方案)
-
创建检查脚本(如
check-clean.sh
):#!/bin/bash if [[ -n $(git status -s) ]]; then echo "存在未提交的更改,终止构建!"; exit 1; fi
-
配置插件执行脚本:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <id>check-clean-workspace</id> <phase>validate</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>bash</executable> <arguments> <argument>check-clean.sh</argument> </arguments> </configuration> </execution> </executions> </plugin>
方法3:使用CI/CD策略(推荐生产环境)
在持续集成(如GitHub Actions、GitLab CI)中配置流程,仅允许打包已提交到版本库的代码:
GitHub Actions示例:
jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Check for uncommitted changes run: | if [[ -n $(git status --porcelain) ]]; then echo "错误:存在未提交的更改!"; exit 1; fi - name: Build with Maven run: mvn package
方法4:手动清理工作区
打包前手动确保代码已提交:
git stash -u # 暂存所有修改(包括未跟踪文件) mvn clean package git stash pop # 恢复修改
构建失败自定义提示语
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.6.0</version> <executions> <execution> <id>check-uncommitted-changes</id> <phase>validate</phase> <!-- 在验证阶段执行 --> <goals> <goal>exec</goal> </goals> <configuration> <executable>powershell</executable> <arguments> <argument>-Command</argument> <argument> if (git status -s) { Write-Host "========================>:[ERROR]: There are uncommitted changes! Please submit or stage all changes before packaging"; exit 1; } </argument> </arguments> </configuration> </execution> </executions> </plugin>
注意事项 -
Git可执行路径:确保构建环境中
git
命令可用。 -
忽略未跟踪文件:若只需检查已跟踪文件,将
git status -s
改为git status -s -uno
。 -
跨平台兼容:Windows环境需改用Batch/PowerShell脚本或使用Maven Profile区分系统。