如何在Git预提交钩子中借助Maven插件格式化Kotlin文件?
适合Maven项目的Kotlin代码格式化方案(集成Git预提交钩子)
首推:Spotless Maven Plugin
Spotless是一款通用的代码格式化插件,完美支持Kotlin,无需额外安装包管理器,完全基于Maven运行,还能灵活配置仅格式化空白的规则,非常适配你的需求。
1. 配置插件到pom.xml
在项目的pom.xml的<build><plugins>节点下添加以下配置:
<plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>2.37.0</version> <!-- 替换为最新稳定版 --> <configuration> <kotlin> <!-- 集成官方ktfmt工具,支持仅格式化空白 --> <ktfmt> <style>kotlinlang</style> <!-- 可选风格:google/kotlinlang,也可自定义 --> <formatOnlyWhitespace>true</formatOnlyWhitespace> <!-- 开启仅空白格式化 --> </ktfmt> <!-- 指定要格式化的文件范围 --> <includes> <include>src/main/kotlin/**/*.kt</include> <include>src/test/kotlin/**/*.kt</include> </includes> </kotlin> </configuration> <!-- 绑定到verify阶段,构建时自动触发格式化 --> <executions> <execution> <id>auto-format</id> <phase>verify</phase> <goals> <goal>apply</goal> </goals> </execution> </executions> </plugin>
2. 手动测试格式化效果
配置完成后,执行以下命令手动运行格式化:
mvn spotless:apply
该命令会自动处理所有指定的Kotlin文件的空白格式。
3. 集成Git预提交钩子
要实现提交前自动格式化,在项目的.git/hooks目录下创建pre-commit脚本(无后缀),内容如下:
#!/bin/sh # 运行Spotless格式化 mvn spotless:apply # 将格式化后的文件加入本次提交 git add .
然后给脚本添加执行权限:
chmod +x .git/hooks/pre-commit
之后每次执行git commit时,都会自动完成格式化并把修改后的文件加入提交,确保代码格式统一。
备选:Kotlin官方Maven插件
如果你更倾向于使用官方工具,kotlin-maven-plugin也自带格式化功能,可以仅配置空白相关规则:
1. 配置插件
在pom.xml中添加:
<plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <version>你的Kotlin版本号</version> <!-- 需与项目Kotlin版本一致 --> <executions> <execution> <id>format-code</id> <goals> <goal>format</goal> </goals> </execution> </executions> <configuration> <format> <trimTrailingWhitespace>true</trimTrailingWhitespace> <insertFinalNewline>true</insertFinalNewline> <indentSize>4</indentSize> <!-- 自定义缩进大小 --> </format> </configuration> </plugin>
2. 手动运行
mvn kotlin:format
3. 集成预提交钩子
同样修改.git/hooks/pre-commit:
#!/bin/sh mvn kotlin:format git add .
注意事项
- 团队成员需统一使用相同的格式化配置,避免提交时出现不必要的冲突
- 首次运行格式化会修改大量文件,建议先提交现有代码,再单独提交格式化后的修改
- Spotless的ktfmt支持更多自定义规则(如换行长度、括号风格),适合团队统一代码规范
内容的提问来源于stack exchange,提问作者Stian Jørgensrud
相关产品推荐
相关产品推荐

