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

相关推荐
GISer_Jing6 小时前
Git协作开发:feature分支、拉取最新并合并
大数据·git·elasticsearch
高山莫衣12 小时前
git rebase多次触发冲突
大数据·git·elasticsearch
码农藏经阁12 小时前
工作中常用的Git操作命令(一)
git
kobe_OKOK_12 小时前
【团队开发】git 操作流程
git·elasticsearch·团队开发
码农垦荒笔记13 小时前
Git 安装闭坑指南(仅 Windows 环境)
windows·git
CC码码1 天前
管理你的多个 Git 密钥(多平台多账号)
git·gitlab·github
CC码码1 天前
管理你的多个 Git 密钥(单平台多账号)
git·gitlab·github
大卫小东(Sheldon)1 天前
GIM 1.5发布了! 支持Windows系统了
git·ai·rust
flying jiang1 天前
将大仓库拆分为多个小仓库
git
李boyang10 天前
Git(四):远程操作
git