使用 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 处理提交时代码规范》将会对此作出介绍。

相关推荐
风也温柔☆29 分钟前
IDEA/WebStorm 切换分支(超简单)
git·intellij-idea·webstorm·切换分支·checkout
Jammingpro12 小时前
【Git版本控制】Git初识、安装、仓库初始化与仓库配置(含git init、git config与配置无法取消问题)
java·git·elasticsearch
shark18 小时前
无需放弃变更、关闭占用程序!用暂存区和 git底层命令实现 Git 变更备份
git·shell·自动化运维
_poplar_19 小时前
15 【C++11 新特性】统一的列表初始化和变量类型推导
开发语言·数据结构·c++·git·算法
北城笑笑19 小时前
Git 10 ,使用 SSH 提升 Git 操作速度实践指南( Git 拉取推送响应慢 )
前端·git·ssh
蓁蓁啊1 天前
GIT使用SSH 多账户配置
运维·git·ssh
相与还1 天前
IDEA和GIT实现cherry pick拣选部分变更到新分支
git·elasticsearch·intellij-idea
刘志辉2 天前
git指令
git
2501_916766542 天前
【Git学习】初识git:简单介绍及安装流程
git·学习
孤独的追光者2 天前
Git 完整流程:从暂存到推送
git