分享一下团队已经落地的 Git Commit 规范~
基本准则
- 合理控制
commit
的粒度,每次commit
只包含一个功能或修复 - 正确设置
commit
时的用户信息,默认user.name
为姓名拼音、user.email
为公司邮箱 - 在个人开发分支上,通常会有很多临时
commit
,在推送分支前需要使用git rebase
合并commit
以保持主分支干净整洁,方便浏览提交记录 - 非国际化项目 Commit Message 均采用中文,避免一些英文语法及翻译理解上的问题
Commit Message 规范
注意:以下规范中的符号(如冒号、括号)均为中文字符
1. 基础格式
<类型>:<标题>
// 空行
<说明> // 选填
2. 类型
限定只能使用以下关键词:
- 特性
- 修复
- 优化
- 文档
- 重构
- 其他
3. 标题
- 通常
commit
列表只显示第一行文字,因此要用一句话概括本次提交的内容 - 如果
commit
与issue
相关,则在末尾关闭issue
:(close #id)
4. 说明
选填,对本次 commit
的详细说明,使用 Markdown 无序列表的格式书写
Commit Message 示例
以下均为符合规范的示例:
文档:Commit Message 规范
修复:用户注册验证码发送失败(close #123)
特性:用户中心模块(close #123)
- 用户注册功能
- 用户登录功能
- 用户信息接口
自动生成工具
Git Hooks
将脚本放入项目 .git/hooks/commit-msg
中,提交代码时会自动执行 Commit Message 格式检查
#!/bin/sh
FILE='.git/COMMIT_EDITMSG'
TYPE=('特性' '修复' '优化' '文档' '重构' '其他')
function ERROR() {
divider=$(printf %.s- {1..150})
echo -e $divider
echo -e "[ 提交信息错误 ] $1"
echo -e $divider
exit 1
}
# 检查长度
msg=$(cat $FILE)
if [ "$msg" == 'no message' ]; then
ERROR '不能为空!'
fi
if [ ${#msg} -lt 10 ]; then
ERROR "字数 < 10(当前 ${#msg} 个字)"
fi
# 检查类型
title=$(cat $FILE | awk 'NR==1')
item=(${title//':'/' '})
if [[ ${TYPE[*]/${item[0]}/} == ${TYPE[*]} ]]; then
ERROR "类型(${item[0]})错误!(仅限使用:${TYPE[*]})"
fi
# 检查空行
blank=$(cat $FILE | awk 'NR==2')
if [[ "$blank" != '' ]]; then
ERROR "第 2 行请留空!"
fi
# 检查说明
num=$(cat $FILE | awk 'END{print NR}')
for ((n = 3; n <= $num; n++)); do
desc=$(cat $FILE | awk "NR==$n")
if [[ "$desc" =~ ^(- .+) ]]; then
continue
fi
ERROR "说明($desc)格式错误!"
done