git提交的姿势

January 14, 2024

提交日志规范

commintlint

commitlint 是一个校验提交日志的库,基本使用方法如下所示。

安装

pnpm i -D @commitlint/cli @commitlint/config-conventional # yarn add -D @commitlint/cli @commitlint/config-conventional # npm i -D @commitlint/cli @commitlint/config-conventional
shell

新增配置文件

在项目根目录下新增 commitlint.config.js 文件,这里我们继承一个常用的配置即可:

module.exports = { extends: ["@commitlint/config-conventional"], };
js

使用 cli 检查一段文本是否符合规范

echo 'foo: hello' | npx commitlint
shell

https://zhengxiaoping.xyz/assets/commitlint-error.c20147d3.png


husky + commitlint

因为 husky 可以轻松管理 git 钩子,我们可以为 git 仓库新增一个 commit-msg 的钩子,在该钩子里拿到用户的提交日志并校验,如果提交日志不符合规范,则抛出错误。

首先,我们使用 husky 新增一个 commit-msg 钩子:

npx husky add .husky/commit-msg 'npx --no -- commitlint --edit ${1}'
shell

然后,提交时就可以校验日志是否符合规范了:

https://zhengxiaoping.xyz/assets/husky-commitlint-error.6f3e1b2a.png

注:常见的 git 钩子: https://zhengxiaoping.xyz/assets/git-hooks.06754913.png