关于git:使用husky70来规范Git提交

9次阅读

共计 2334 个字符,预计需要花费 6 分钟才能阅读完成。

大家好,我是前端小贺,心愿可能通过本人的学习输入给你带来帮忙。

背景

在一个残缺的工作流中,Git 提交标准是肯定须要的。Git 提交标准包含什么呢?

我感觉应该包含代码的质检以及 commit message 校验。

咱们应用 husky 来增加咱们上述的需要:

husky 是利用 Git hooks(上面有常见的Git hooks)在git 的钩子函数中(比方pre-commitcommit-msg)做一些事件。上面是官网的介绍:

Modern native Git hooks made easy

申明:咱们应用的 husky 的版本是 7.0 及之后的版本

装置 husky

好了,关上我的项目的根目录,执行`npm install husky --save-dev, 前提是生成了package.json

npm install husky --save-dev

咱们依照官网的文档,进行husky install:

留神点:这里的 npm 的版本必须为 7.1 及之后的版本(https://github.com/npm/cli/re…)

npm set-script prepare "husky install"
npm run prepare

增加 eslint hook

咱们来配置 eslint 校验

npx husky add .husky/pre-commit "npm run lint"
git add .husky/pre-commit

上述咱们为什么可能配置 npm run lint 呢,是因为咱们的 package.json 文件中的 script 中蕴含了lint:

{
    "scripts": {"lint": "vue-cli-service lint"}
}

ok,至此咱们在 commit 的时候就会校验代码了,咱们试一下:

git commit -m"验证"

> webpack-vue@2.1.0 lint
> vue-cli-service lint

 DONE  No lint errors found!

如上,咱们提交的时候执行了 lint 脚本。

增加 commit-msg hook

接下来,咱们限度下 commit messge 标准。

咱们须要采纳 npm 社区中比拟成熟的两个依赖包@commitlint/cli,@commitlint/config-conventional

  • @commitlint/cli 是用来在命令行中提醒用户信息的
  • @commitlint/config-conventional 是 commit message 标准

接下来咱们装置下两个包,并增加相干的配置文件:

npm install @commitlint/cli @commitlint/config-conventional --save-dev

echo "module.exports = {extends: ['@commitlint/config-conventional'] }" > commitlint.config.js

ok,至此咱们能够校验 commit meassage 中的内容了,咱们测试一下:

git commit -m"1"

> webpack-vue@2.1.0 lint
> vue-cli-service lint --mode production

The following files have been auto-fixed:

  src/utils/secret.js

 DONE  All lint errors auto-fixed.
npm ERR! canceled

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/hsm/.npm/_logs/2022-04-26T02_21_07_564Z-debug.log
husky - commit-msg hook exited with code 1 (error)

如上,咱们 commit message 轻易写了点货色,就校验住了。咱们批改下咱们的 commit message 从新 commit 下:

git commit -m"docs: 增加 husky 相干"

> webpack-vue@2.1.0 lint
> vue-cli-service lint --mode production

 DONE  No lint errors found!
[committest b61be77] docs: 增加 husky 相干
 1 file changed, 2 insertions(+)

Ok,胜利了~

提交标准

对于 git commit message 提交标准,咱们能够参考阮一峰的 Commit message 和 Change log 编写指南。

VSCode 中,咱们采纳了 Conventional Commits 插件来进行 commit 提交

Git hooks

pre-commit git commit执行前 能够通过 git commit --no-verify 绕过
commit-msg git commit执行前 能够用 git commit --no-verify 绕过
post-commit git commit执行后 不影响 git commit 的后果
pre-merge-commit git merge执行前 能够用 git merge --no-verify 绕过。
prepare-commit-msg git commit执行后,编辑器关上之前
pre-rebase git rebase执行前
post-checkout git checkoutgit switch 执行后 如果不应用 --no-checkout 参数,则在 git clone 之后也会执行。
post-merge git commit执行后 在执行 git pull 时也会被调用
pre-push git push执行前

最初

您的每一个点赞及评论都是对我保持写作最大的反对!
另外心愿各位朋友和我交换探讨,如有不对的中央,更心愿批评指正!

我是前端小贺,心愿可能通过本人的学习输入给你带来帮忙。

正文完
 0