网络上很多关于 commit message 的想法都来源于 tpope,在他看来,一个好的 Git commit messge 应该是这样的:
Capitalized, short (50 chars or less) summary More detailed explanatory text, if necessary. Wrap it to about 72 characters or so. In some contexts, the first line is treated as the subject of an email and the rest of the text as the body. The blank line separating the summary from the body is critical (unless you omit the body entirely); tools like rebase can get confused if you run the two together.
如上:
.
。commit message 应该使用祈使语气,也就是 “Fix bug”,而不是 “Fixed bug” 或者 “Fixes bug”。这是为了与 git merge
和 git revert
自动生成的 commit message 相一致。
关于这一行的摘要怎么写,也可以有一些约定:
Leading active verb | Explanation |
---|---|
Add | Create a capability e.g. feature, test, dependency. |
Cut | Remove a capability e.g. feature, test, dependency. |
Fix | Fix an issue e.g. bug, typo, accident, misstatement. |
Bump | Increase the version of something e.g. dependency. |
Make | Change the build process, or tooling, or infra. |
Start | Begin doing something; e.g. create a feature flag. |
Stop | End doing something; e.g. remove a feature flag. |
Refactor | A code change that MUST be just a refactoring. |
Reformat | Refactor of formatting, e.g. omit whitespace. |
Optimize | Refactor of performance, e.g. speed up code. |
Document | Refactor of documentation, e.g. help files. |
在详细描述部分,可以用 -
或者 *
分点阐释,每点的文字部分与 -
和 *
之间空一格,同时点与点之间以空行分隔,使用悬挂缩进。
具体操作时,有两种方式:
git commit
命令上添加参数:$ git commit -m "Title" -m "Description ......"
git commit
,在自动打开的编辑器中进行操作,默认是 Vim。推荐使用第 2 种方式,比较清楚和直观。如果在 Vim 中编辑 commit message,可以在 .vimrc
中加入以下配置, 开启拼写检查和设置文本宽度为 72 :
autocmd FileType gitcommit setlocal spell textwidth=72
可以考虑在 commit message 中加入相关的 PR, issue 链接,可以是一个编号,比如 #209
, GitHub 会自动关联到对应 PR 和 issue 的 URL。在 GitHub 上进行 merge 时,它也会自动帮我们加上相关的 PR 编号。
image.png
如果涉及本项目之外的 issue,可以直接写永久链接,避免冲突。
引用 issue 时,如果出现一些关键词,比如 “Close #209”, 那么 GitHub 就会关闭 issue #209。详细内容以及一些其他关键词可参见 Closing issues using keywords.
以上内容不用完全照做,只须做到 “力所能及” 的一些点。另外,每个项目,每个团队也都可能有自己的一些规范,尽量统一即可。
参考:
[1] A Note About Git Commit Messages [2] How to commit a change with both “message” and “description” from the command line? [3] 5 Useful Tips For A Better Commit Message [4] How to write a Git Commit Message (2014) [5] git_commit_message