1 介绍

Git进行commit时都需要提交说明(commit message):

Git commit -m 'hello world'

-m参数就是用来指定commit message的

commit message应该清晰明了,说明本次提交的目的。

2 Commit message的格式

Commit message应该包括三个部分:Header/Body/Footer。其中,Header是必需的,Body和Footer可以省略。

<type>(<scope>): <subject>
// 空一行
<body>
// 空一行
<footer>

不管是哪一个部分,任何一行都不得超过72个字符(或100个字符)。这是为了避免自动换行影响美观。

2.1 Header

只有一行,包含三个字段,type(必须)、scope(可选)和subject(必须) (1)type
用于说明commit的类别,只允许使用一下7个标识:

  1. feat:新功能(feature)
  2. fix:修补bug
  3. docs:文档(documentation)
  4. style:格式(不影响代码运行的改动)
  5. refactor:重构(即不是新增功能,也不是修改bug的代码变动)
  6. test:增加测试
  7. chore:构建过程或辅助工具的变动

(2)scope
用于说明commit影响的范围,比如数据层、控制层、视图层等,是项目不同而不同

(3)subject
是commit的简短描述,不超过50字符

例如fix: array parsing issue when multiple spaces were contained in string.

  • 义动词开头,使用第一人称现在时(change,而不是changed)
  • 第一个字母小写
  • 结尾不加句号(.)

2.2 Body

是对本次commit的详细描述,可以分成多行:

More detailed explanatory text, if necessary.  Wrap it to 
about 72 characters or so. 

Further paragraphs come after blank lines.

- Bullet points are okay, too
- Use a hanging indent

有两个注意点:

  1. 使用第一人称现在时
  2. 说明代码变动的动机,以及与以前行为的对比

2.3 Footer

只是用与两种情况
(1) 不兼容变动
如果当前代码与上一个版本不兼容,则Footer部分以BREAKING CHANGE开头,后面是变动的描述以及变动理由和迁移方法
BREAKING CHANGE: isolate scope bindings definition has changed.

To migrate the code follow the example below:

Before:

scope: {
  myAttr: 'attribute',
}

After:

scope: {
  myAttr: '@',
}

The removed `inject` wasn't generaly useful for directives so there should be no code using it.

(2)关闭Issue
如果当前commit针对某个issue,那么可以在Footer部分关闭这个issue

Closes #123, #245, #992

2.4 Revert

有一种特殊情况,如果当前commit用于撤销以前的commit,则必须以revert:开头,后面跟着被撤销的Commit的Header

revert: feat(pencil): add 'graphiteWidth' option

This reverts commit 667ecc1654a317a13331b17617d973392f415f02.

Body部分的格式是固定的,必须写成·This reverts commit ·

Commitizen

一个撰写合格的Commit message的工具

安装:
npm install -g commitizen

然后,在项目目录里,运行下面的命令,使其支持 Angular 的 Commit message 格式。

commitizen init cz-conventional-changelog --save --save-exact

以后凡是用到git commit的命令,一律改为git cz,这时,就会出现选项,用来生成符合格式的Commit message。

validate-commit-msg

用于检查Node项目的Commit message是否符合格式,需要手动安装

首先拷贝这个JS文件到代码库,命名为validate-commit-msg.js

然后把这个脚本加入Git的Hook,在package.json中使用ghooks,把这个脚本加为commit-msg时运行

"config": {
  "ghooks": {
    "commit-msg": "./validate-commit-msg.js"
  }
}

然后每次Git commit时脚本就会自动检查Commit message是否合格,不合格就会报错

简单的示例

feat: 新增分析师清理功能

分析师清理功能,包括

  1. 查询分析师
  2. 分时段清理
feat: 新增分析师清理功能

分析师清理功能,包括
1. 查询分析师
2. 分时段清理

不包含正文的提交说明

docs: correct spelling of CHANGELOG

包含作用域的提交说明

feat(lang): added polish language

为fix编写的提交说明,包含可选的issue编号

fix: minor typos in code

see the issue for details on the typos fixed

fixes issue #12

为什么使用约定式提交Commit message

  1. 自动化生成 CHANGELOG。
  2. 基于提交的类型,自动决定语义化的版本变更。
  3. 向同事、公众与其他利益关系人传达变化的性质。
  4. 触发构建和部署流程。
  5. 让人们更容易地探索结构化的提交历史,降低贡献项目的难度。