Coding Style(二)—— Git Commit 规范
所有的代码规范、接口设计以及各种规定,都是为了在团队内部形成共识,防止个人习惯差异引起的混乱。
你是否也受够了自己所有的 Git Commit 记录都是亘古不变的 Update
,某一天回查的时候啥也查不到。
写好 Commit Message 不仅有助于 Code Review,还可以便捷有效地输出 CHANGELOG。
本文将介绍 angular 团队的 Git Commit 规范格式以及方便标准提交 Git Commit 的工具。
:::info
关于 Git 的操作可以参照之前写的《程序员的时间机器 —— Git 与 GitHub 的使用》。
:::
Commit Message 格式
参照 angular 的 Commit Message Guidelines,angular 团队对 Git Commit 的格式有着非常精确的规定,在他们的规范中,每条 Commit Message 由 header
、body
、footer
组成。header
会有特殊的格式,包括type
、scope
、subject
。其中:
type
是 commit 的类型scope
是 commit 的影响范围subject
是 commit 的概述body
是 commit 的具体内容footer
是 commit 的一些备注
1 | <type>(<scope>): <subject> |
在 angular 团队的规范中,type
只能是以下的:
- build: 影响构建系统或外部依赖的变换
- ci: 改变了 CI 的配置及脚本
- docs: 更新了文档
- feat: 增加了新功能
- fix: 修复了 BUG
- perf: 提高了代码的性能
- refactor: 重构了代码,没有修复 BUG,也没有新增功能
- style: 代码格式上的调整,不影响代码的含义
- test: 新增缺失的测试或修正现有的测试
angular 官网的一些 Commit Message 的例子如下:
1 | docs(changelog): update changelog to beta.5 |
1 | fix(release): need to depend on latest rxjs and zone.js |
一些注意事项如下:
header
是必须的,scope
则是可选的。- Commit Message 中的任何一行都不能超过 100 个字符。
- 如果 commit 回滚了,Commit Message 则应该以
revert
开头,后面跟上被回滚的 commit 的header
,在body
中应该提到这是对<hash>
的回滚,其中<hash>
指的是被回滚的 commit 的 SHA。 - (这条非 angular 规范,但比较重要)理想情况下,每个 commit 都包含独立(isolated)且完整(complete)的修改。
Commitizen 工具
上面说了那么多的规范,到现在基本都差不多忘了吧?既然写好 Commit Message 是刚需,那社区自然少不了好用的工具。对于懒人来说,借助工具就可以把 Commit Message 写得规范,同时还能一步解决 Commit Message 和版本发布的事情。
首先介绍一个工具 commitizen/cz-cli,使用它提供的 git cz
就可以帮助我们生成符合规范的 Commit Message。此外,我们还需要 为它指定一个 Adapter(例如 commitizen/cz-conventional-changelog 是一个符合 Angular 的预设),使得 commitizen 可以按照我们指定的规范生成 Commit Message。
我觉得此类工具还是全局安装比较方便,以下为安装命令:
1 | npm i -g commitizen cz-conventional-changelog |
安装完成后,在 Git Repo 中要进行 Commit Message 时使用 git cz
命令即可:
自定义 Adapter
angular 的规范总归是其他团队的规范,如果需要指定一套符合自己团队的规范,也可以通过指定自定义 Adapter 来实现。
1 | npm i -g cz-customizable |
之后修改 .czrc
中的内容为:
1 | { "path": "cz-customizable" } |
同时在 ~/
目录下创建 .cz-config.js
,维护你想要的格式,一个参考格式如下:
1 | ; |
自动生成 CHANGELOG
工具除了可以帮助我们规范化进行 Commit Message,在规范提交 Commit 信息的情况下,还可以使用 conventional-changelog/standard-version 工具帮助我们自动生成 CHANGELOG。
1 | npm i -g standard-version |
1 | standard-version --first-release # 使用 standard-version 生成第一个发布版本的 CHANGELOG |
关于 standard-version
更多的使用方法可以参考官方 Repo 的使用说明。
- 感谢您的赞赏