使用 commitlint 和 husky 检查提交描述是否符合规范要求

在上一小节中,我们了解了 Git hooks 的概念,那么接下来我们就使用 Git hooks 来去校验我们的提交信息。

要完成这么个目标,那么我们需要使用两个工具:

注意:npm 需要在 7.x 以上版本。

1. commitlint 用于检查提交信息

1.1. 安装依赖

javascript 复制代码
npm install --save-dev @commitlint/config-conventional@12.1.4 @commitlint/cli@12.1.4

1.2. 创建配置文件commitlint.config.js

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

1.3. 增加配置项

javascript 复制代码
module.exports = {
    // 继承的规则
    extends: ['@commitlint/config-conventional'],
    // 定义规则类型
    rules: {
      // type 类型定义,表示 git 提交的 type 必须在以下类型范围内
      'type-enum': [
           2,
            'always',
          [
              'feat', // 新功能 feature
              'fix', // 修复 bug
              'docs', // 文档注释
              'style', // 代码格式(不影响代码运行的变动)
              'refactor', // 重构(既不增加新功能,也不是修复bug)
              'perf', // 性能优化
              'test', // 增加测试
              'chore', // 构建过程或辅助工具的变动
              'revert', // 回退
              'build' // 打包
          ]
      ],
      // subject 大小写不做校验
      'subject-case': [0]
    }
}

注意:确保保存为 UTF-8 的编码格式,否则可能出现错误。

2. husky:是Git hooks工具

2.1. 安装依赖

javascript 复制代码
npm install husky@7.0.1 --save-dev

2.2. 启动 hooks , 生成 .husky 文件夹

javascript 复制代码
npx husky install

2.3. 在 package.json 中生成 prepare 指令( 需要 npm > 7.0 版本 )

javascript 复制代码
npm set-script prepare "husky install"

生成后效果如下:

2.4. 执行 prepare 指令

javascript 复制代码
npm run prepare

执行后效果如下:

2.5. 添加 commitlint 的 hook 到 husky中,并在 commit-msg 的 hooks 下执行 npx --no-install commitlint --edit "$1" 指令

javascript 复制代码
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

此时的 .husky 的文件结构如下:

至此, 不符合规范的 commit 将不再可提交:

javascript 复制代码
PS F:\xxxxxxxxxxxxxxxxxxxxx\imooc-admin> git commit -m "测试"
⧗   input: 测试
✖   subject may not be empty [subject-empty]
✖   type may not be empty [type-empty]

✖   found 2 problems, 0 warnings
ⓘ   Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint

husky - commit-msg hook exited with code 1 (error)

那么至此,我们就已经可以处理好了 强制规范化的提交要求,到现在不符合规范的提交信息,将不可再被提交。

那么到这里我们的规范化目标 就完成了吗?

当然没有,现在我们还缺少一个 规范化的处理 ,那就是代码格式提交规范处理,下一篇文章《通过 pre-commit 处理提交时代码规范》将会对此作出介绍。

相关推荐
T - mars6 小时前
Git在Pycharm中的使用
git
sunarmy7 小时前
curl: (56) OpenSSL SSL_read: Connection reset by peer, errno 104
git
典学长编程8 小时前
高效学习之一篇搞定分布式管理系统Git !
大数据·git·搜索引擎
是2的10次方啊9 小时前
.gitignore失效自救指南:原理揭秘与工程师实战排查全流程
git
海外空间恒创科技9 小时前
香港站群服务器与普通香港服务器对比
服务器·git·github
Wetoria11 小时前
管理 git 分支时,用 merge 还是 rebase?
前端·git
泰勒朗斯1 天前
如何在新机器上设置github完成内容git push
git·github
小妖6661 天前
git branch -a 还有一些已经删除了的分支
git
&Sinnt&2 天前
Git 版本控制完全指南:从入门到精通
git·后端
Tiny2142 天前
多人协同开发时Git使用命令
git