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

相关推荐
2501_903238658 分钟前
Git Bash:Windows下的强大命令行工具
windows·git·bash·个人开发
神明木佑2 小时前
datalist 是什么?以及作用是什么?
git
那片海还在吗4 小时前
使用 Git、Postman、Newman、Jenkins 与邮件构建自动化接口测试及通知流程
git·jenkins·postman
heeheeai11 小时前
git 国内源
git
the_seventh_dog12 小时前
git | 团队协作开发注意事项
git
yinshuilan15 小时前
今日运维之-Mac笔记本python环境问题
运维·git·python·brew
辄也16 小时前
git拉取远程分支到本地分支
git
皮克斯的进化之路16 小时前
Git原理+使用(超详细)
git
wrjwww16 小时前
【Git学习笔记】Git常用命令
笔记·git·学习
大乔乔布斯17 小时前
WSL,Power shell 和CMD, Git bash的区别
开发语言·git·bash