Commit message编写指南
Git 的每次提交,都要有 Commit message(提交说明) ,否则就不允许提交
git commit -m 'some message'
上面代码的-m
参数,就是用来指定 commit mesage 的。
如果需要写多行提交说明,我们只需要执行 git commit
即可进入 vi
编辑器
git commit
基本上写什么都可以,但是,一般来说,commit message 应该清晰明了,说明本次提交的目的。
针对于 Commit message
有很多写法规范,但目前使用最广的写法,就是 Angular 规范。
一、Commit message 的作用
规范后的 Commit message,有几个好处。
1. 提供更多的历史信息,方便快速浏览
2. 可以过滤某些commit,便于快速查找信息
3. 可以直接从commit生成Change log
Change Log 是发布新版本时,用来说明与上一个版本差异的文档
二、Commit message 的格式
每次提交,Commit message 都包括三个部分:Header,Body 和 Footer。
<Header> # 必需
# 空一行
<body> # 可省略
# 空一行
<footer> # 可省略
2.1 Header
Header部分只有一行,包括三个字段:type(必需)
、 scope(可选)
、 subject(必需)
。
(1)type
type
用于说明 commit 的类别,只允许使用以下7个标识。
feat:新功能(feature)
fix:修补 bug
docs:文档(documentation)
style: 格式(不影响代码运行的变动)
refactor:重构(即不是新增功能,也不是修改 bug 的代码变动)
test:增加测试
chore:构建过程或辅助工具的变动
如果type
为feat
和fix
,则该 commit 将肯定出现在 Change log 之中。其他情况(docs
、chore
、style
、refactor
、test
)由你决定,要不要放入 Change log,建议是不要。
(2)scope
scope
用于说明 commit 影响的范围,比如数据层、控制层、视图层等等,视项目不同而不同。
(3)subject
subject
是 commit 目的的简短描述。
2.2 Body
Body 部分是对本次 commit 的详细描述,可以分成多行。
2.3 Footer
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 #234
# 也可以关闭多个
Closes #123, #234, #345
2.4 Revert
还有一种特殊情况,如果当前 commit 用于撤销以前的 commit,则必须以revert:
开头,后面跟着被撤销 Commit 的 Header。
revert: feat(pencil): add 'graphiteWidth' option
This reverts commit 667ecc1654a317a13331b17617d973392f415f02.
Body部分的格式是固定的,必须写成This reverts commit <hash>.
,其中的hash是被撤销 commit 的 SHA 标识符。
如果当前 commit 与被撤销的 commit,在同一个发布(release)里面,那么它们都不会出现在 Change log 里面。如果两者在不同的发布,那么当前 commit,会出现在 Change log 的Reverts
小标题下面。
三、Commit message 格式检查工具
commitelint 用于检查项目 Commit message 是否符合格式的工具。
3.1 安装 commitlint
# Mac 安装命令
npm install --save-dev @commitlint/{config-conventional,cli}
# Windows 安装命令
npm install --save-dev @commitlint/config-conventional @commitlint/cli
3.2 创建文件写入内容
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
3.3 安装 husky
npm install husky --save-dev
# 激活 husky
npx husky install
3.4 配置 husky
找到package.json
文件
"scripts": {
...
"prepare": "husky install"
},
3.5 添加 hook
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit ${1}'
到这就安装配置完成,再运行 git commit
提交时,就会校验格式了