git commit 规范
git commit
commitizen
通常我们的 git commit 会按照统一的风格来提交,这样可以快速定位每次提交的内容
但是如果每次手动来编写这些是比较麻烦的事情,我们可以使用一个工具:commitizen
- commitizen 是一个帮助我们编写规范 commit message 的工具;
- commitizen
安装
npm install commitizen -D
执行
npx cz
or npm scripts:
"scripts": {
"commit": "cz"
}
这时你会发现执行的界面不是很友好。
Making your repo Commitizen friendly
npx commitizen init cz-conventional-changelog --save-dev --save-exact
Or if you are using Yarn:
npx commitizen init cz-conventional-changelog --yarn --dev --exact
下面统一使用 yarn 进行配置:
提交代码可以使用 yarn commit:
- 第一步是选择type,本次更新的类型
| Type | 作用 |
|---|---|
| feat | 新增特性 (feature) |
| fix | 修复 Bug(bug fix) |
| docs | 修改文档 (documentation) |
| style | 代码格式修改(white-space, formatting, missing semi colons, etc) |
| refactor | 代码重构(refactor) |
| perf | 改善性能(A code change that improves performance) |
| test | 测试(when adding missing tests) |
| build | 变更项目构建或外部依赖(例如 scopes: webpack、gulp、npm 等) |
| ci | 更改持续集成软件的配置文件和 package 中的 scripts 命令,例如 scopes: Travis, Circle 等 |
| chore | 变更构建流程或辅助工具(比如更改测试环境) |
| revert | 代码回退 |
- 第二步选择本次修改的范围(作用域)
- 第三步选择提交的信息
- 第四步提交详细的描述信息
- 第五步是否是一次重大的更改
- 第六步是否影响某个open issue
代码提交验证
如果我们按照 cz 来规范了提交风格,但是依然有同事通过 git commit 按照不规范的格式提交应该怎么办呢?
让我们继续往下
husky
husky 是一个 git hook 工具,可以帮助我们触发 git 提交的各个阶段:pre-commit、commit-msg、pre-push
推荐全局安装
npm install husky -D
npm install husky -g
配置 npm scripts:
"scripts": {
"prepare": "husky install"
}
执行
yarn prepare
Add a hook:
npx husky add .husky/pre-commit "yarn lint"
这样每次提交前会校验 eslint(假如你配置的话)
注意:
-
如果我们使用了版本管理工具,可能会提示
husky npm: command not found -
you can use
~/.huskyrcto load the necessary before running hooks. -
在命令行新增文件,并输入下面的内容
-
# ~/.huskyrc # This loads nvm.sh and sets the correct PATH before running hook export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
commitlint
下面通过 commitlint 来限制提交;
yarn add -D @commitlint/config-conventional @commitlint/cli
2.在根目录创建commitlint.config.js文件,配置commitlint
module.exports = {
extends: ['@commitlint/config-conventional']
}
3.使用 husky 生成 commit-msg 文件,验证提交信息:
npx husky add .husky/commit-msg "yarn --no-install commitlint $1"