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

相关推荐
图书馆钉子户2 小时前
git 常用功能
git
普世的微光3 小时前
ue----git局域网内部署裸仓库,别的机器进行访问
windows·git
图书馆钉子户3 小时前
怎么合并主从分支,要注意什么
git
David_0265 小时前
刚实习?还不知道git怎么使用?看完这篇文章,教你掌握git常用命令及场景
git
LIU_Skill5 小时前
Git版本控制系统---本地操作(万字详解!)
git
qq_2187533110 小时前
常用Git命令
java·git
4277240021 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
利刃大大1 天前
【Git】五、多人协作
git
逸Y 仙X1 天前
Git常见命令--助力开发
java·大数据·git·java-ee·github·idea
wgslucky2 天前
pipeline 使用git parameter插件实现动态选择分支构造
git