Git commit 模板:配置自定义提交模板,强制遵循提交规范
·
Git Commit 模板配置指南
配置自定义提交模板并强制遵循规范需完成以下步骤:
1. 创建提交模板文件
在项目根目录创建模板文件(如.gitmessage.txt),内容示例:
# 类型: feat|fix|docs|style|refactor|test|chore
# 影响范围: (模块/文件)
# 关联问题: #issue编号
<50字符的简短描述>
# 详细说明(可选):
# - 变更原因
# - 解决方案
# - 注意事项
2. 配置本地模板
# 设置当前仓库模板
git config commit.template .gitmessage.txt
# 全局设置(所有仓库生效)
git config --global commit.template ~/.gitmessage.txt
3. 强制规范验证(使用 Git Hooks)
在.git/hooks/commit-msg创建可执行脚本:
#!/bin/sh
MSG_FILE=$1
MSG=$(cat $MSG_FILE)
# 验证标题长度 ≤ 50字符
if [ $(echo "$MSG" | head -n1 | wc -m) -gt 50 ]; then
echo "错误:提交标题超过50字符" >&2
exit 1
fi
# 验证包含类型标签
if ! grep -qE "^(feat|fix|docs|style|refactor|test|chore):" "$MSG_FILE"; then
echo "错误:必须包含有效的类型标签" >&2
exit 1
fi
4. 启用钩子
chmod +x .git/hooks/commit-msg
5. 团队强制方案(推荐)
-
模板文件纳入版本控制
git add .gitmessage.txt git commit -m "chore: 添加提交模板" -
共享钩子脚本
- 创建
githooks/目录存放脚本 - 设置仓库级配置:
git config core.hooksPath githooks/
- 创建
-
CI/CD 验证(终极强制) 在 CI 流水线中添加校验步骤:
# 示例:使用 commitlint 工具 npm install -g @commitlint/cli echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js git log -1 --pretty=%B | commitlint
验证效果
提交时自动加载模板:
git commit # 自动打开编辑器显示模板
若不符合规范,将被拒绝提交。
最佳实践建议:
- 使用Conventional Commits规范
- 结合工具如
commitizen交互式提交- 重要项目配置
pre-receive钩子服务端验证
通过此方案,既可保持提交灵活性,又能确保团队遵循统一规范。
更多推荐



所有评论(0)