在团队开发中,我们会要求每次提交项目代码都需要写注释,也就是commit message。
落实到实际运用上,就会发现,提交的注释五花八门,简短如“commit”,“fix bug”。当看完了注释,发现还是不知道这次提交究竟做了什么,还是得仔细查看代码变动才能得知。
更糟糕的是,有时候真的是出现bug了,又不确定是在哪次改动中碰到,只能在茫茫的git log中苦苦寻找。

所以,本章的主题是,如何规范git commit message,让提交的注释不只是必填项,而且要“有意义”。同时介绍一下,规范化的message还带来了其他什么好处。

查询了许多资料,Angular 的提交规范 是目前使用最广泛的。
它的设计目标是:

  • 可以通过脚本生成 CHANGELOG.md
  • 识别不重要的提交
  • 回顾时可以提供更多的信息

Commit Message 格式

我们将提交的 message 约定为以下格式:

1
2
3
4
5
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>

其中:

  • 是必填项,表示此次提交的类型,只允许以下七种类型:

    • feat (feature)
    • fix (bug fix)
    • docs (documentation)
    • style (formatting, missing semi colons, …)
    • refactor
    • test (when adding missing tests)
    • chore (maintain)
  • 是选填项,表示此次提交的作用域,因项目而异,比如是控制层、数据层等等

  • 是必填项,是此次提交的简短描述。以动词、小写字母开头,结尾不加句号。(如果是国人项目,建议使用中文)

上面的三项内容可以认为是Header,下面的内容则是Body,Body 下面是 Footer。
Body的内容与Header、Footer各空一行,也就是
一般是对本次提交的一个详尽描述,可以由多行组成。

接下来便是Footer,Footer用于两种情况:

  1. 不兼容变动,如果当前代码与之前不兼容,则以BREAKING CHANGE开头,说明变动了什么、原由以及迁移方法,下面是Angular的一个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
BREAKING CHANGE: isolate scope bindings definition has changed and
the inject option for the directive controller injection was removed.

To migrate the code follow the example below:

Before:

scope: {
myAttr: 'attribute',
myBind: 'bind',
myExpression: 'expression',
myEval: 'evaluate',
myAccessor: 'accessor'
}

After:

scope: {
myAttr: '@',
myBind: '@',
myExpression: '&',
// myEval - usually not useful, but in cases where the expression is assignable, you can use '='
myAccessor: '=' // in directive's template change myAccessor() to myAccessor
}

The removed `inject` wasn't generaly useful for directives so there should be no code using it.
  1. 引用的issue,如果commit有对应的某个issue,则可以在这里选择关闭它。比如:
1
Closes #123, #245, #992

规范的好处

当 commit 信息形成规范,那么有许多工具可以帮助我们做事情,比如:

  • 校验提交信息是否规范
  • 生成 Change log
  • 发布 release 包

另外,我们还能方便地浏览历史变更,过滤到我们想要的信息:

  • 比如通过命令:git log <last tag> HEAD --pretty=format:%s查看上次发布后的变动
  • 比如通过命令:git log <last release> HEAD --grep feature显示本次发布新增加的功能

另外,规范化的 commit 信息可以更好地与 CI 工具结合,监控代码的变更与删除,减少代码误操作。

参考