Git每次提交代码都需要写commit message,一般来说,commit message应该清晰明了,说明本次提交的目的,具体做了什么操作等。但是在日常开发中,开发者提交的的commit message千奇百怪,中英文混合使用,这就导致后续代码维护成本特别大,有时自己都不知道自己的fix bug修改的是什么问题。基于以上这些问题,我们希望通过某种方式来监控用户的git commit message,让规范更好的服务于质量,提高大家的研发效率。
所有项目的Commit Log的格式精确控制,增加可读性,便于查看变更历史,形成良好的git使用习惯。规范作为git hook的commit-msg和pre-receive执行,不合法无法提交。全面执行后可自动化执行以下操作:
Commit Log包含三部分header、body、footer,其中header是必须的,格式固定,body在变更有必要详细解释时使用。
commit log 格式
Plain Text
<types>(<scopes>): <subject>
<空行>
<body>
<空行>
<footer>
注意:冒号后面必须有一个小写空格,types和scopes可为多个,中间用逗号分隔。
举例:
fix(service,dao): 修改产品类型时不过滤产品Type
仅header,涉及模块较多用*代替
refactor(*): 修改DTO模型前缀
有header和body
fix(language-service): Improve signature selection for pipes with args
Pipes with arguments like `slice:0` or `slice:0:1` should not produce
diagnostic errors.
有header、body、footer
func(core,logic): 添加礼包审核
添加商品编辑审核状态和回调,blablablabla
PRD:https://km.sankuai.com/page/194127085
英文,小写。必须为下列中一个或多个:
英文,小写。表示变更的包或模块范围,可多个组合,若涉及范围较大,可用 * 代替。各服务可以自行定义,组内同学可轻易理解。通用scope列表如下:
除上述通用字段外,Scope中各方向可自行定义关键字。例如以下为商品平台中所定义字段:
中文。标题简述修改,结尾不要有句号。
中文。修改的背景(为什么做这次修改),说明修改逻辑。
中文。可以放置需求wiki或task链接,对以后其他同学blame很有用。
Java代码块
(^(\w+)\(([\w+,.\-_*]+?)\): .+(.|\n)*)|(^Automatic merge(.|\n)*)|(^Merge (.|\n)*)
#!/usr/bin/env python
import sys, os, re
from subprocess import check_output
commit_msg_filepath = sys.argv[1]
commit_type = sys.argv[2] if len(sys.argv) > 2 else ''
branch = check_output(['git', 'symbolic-ref', '--short', 'HEAD']).strip()
print "commit_type:", commit_type
with open(commit_msg_filepath, 'r+') as f:
content = f.read()
# ignore merge
if content.startswith('Merge'):
sys.exit(0)
result = re.match('(\w+)\(([\w+,.\-_*]+?)\): .+(.|\n)*)', content)
if result is None:
print "ERROR: commit msg not match pattern '<type>(<scope>): <subject>'\n\t%s" % content
sys.exit(1)
sys.exit(0)
然后在git仓库一级目录下执行:
mv commit-msg.txt .git/hooks/commit-msg
chmod +x .git/hooks/commit-msg