git commit 规范

261 阅读2分钟

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代码回退
  • 第二步选择本次修改的范围(作用域)

image-20210723150147510

  • 第三步选择提交的信息

image-20210723150204780

  • 第四步提交详细的描述信息

image-20210723150223287

  • 第五步是否是一次重大的更改

image-20210723150322122

  • 第六步是否影响某个open issue

image-20210723150407822

代码提交验证

如果我们按照 cz 来规范了提交风格,但是依然有同事通过 git commit 按照不规范的格式提交应该怎么办呢?

让我们继续往下

husky

husky 是一个 git hook 工具,可以帮助我们触发 git 提交的各个阶段:pre-commit、commit-msg、pre-push

husky

推荐全局安装

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 ~/.huskyrc to 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"