约定式提交规范三部曲(一)之 commitlint

1,376 阅读4分钟

什么是 commitlint

ommitlint 是一个开源工具,用于规范化和验证 Git 提交消息的格式

它通常与约定式提交规范(Conventional Commits)一起使用,旨在帮助团队创建一致的提交消息格式,并确保提交消息包含必要的信息。

注意:commitlint 与其他 lint 工具一样,仅仅是负责验证提交是否符合约定式提交规范的工具

不过,可以通过挂载 git 的钩子(借助 husky)来实现在提交消息时验证消息是否符合规范。

规范化的提交信息验证流程

流程如下,此时不理解没关系,记得回过头来看一下:

  1. 使用 git commit 提交。
  2. 触发通过 husky 配置的 commit-msg 钩子脚本,执行该脚本。
  3. 在该脚本中使用 commitlint 命令验证此次的提交信息。

安装 commitlint

npm install --save-dev @commitlint/config-conventional @commitlint/cli

commitlint 需要配合提交规范进行提交信息验证,创建配置文件并配置需要使用的提交信息验证规范:

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

上述的 commitlint.config.js 是 commitlint 的配置文件。

注意:如果 package.json 中配置了 "type": "module",将 commitlint.config.js 文件名更改为 commitlint.config.cjs

配置还可以定义在以下文件中:

  • commitlint.config.js
  • .commitlintrc.js
  • .commitlintrc
  • .commitlintrc.json
  • .commitlintrc.yml
  • package.jsoncommitlint 属性对象

此时就可以使用 commitlint 验证提交信息,进入某个配置 git 并有一次提交的仓库执行:

npx commitlint --to HEAD --verbose

husky

husky 是一个用于管理 git 钩子(git hooks)的工具,它可以帮助开发团队在代码提交和其他 git 操作前后运行自定义的脚本。通过 husky,您可以轻松地配置和管理各种 git 钩子,以执行预定义的任务,例如代码格式化、单元测试、代码审查等。

# 安装
npm install --save-dev husky

# 激活 husky
npx husky init

使用 init 指令会在 .husky/ 中创建 pre-commit 脚本,并更新 package.json 中的 prepare 脚本。暂时不需要 pre-commit 脚本,使用 rm .husky/pre-commit 删除。

安装并激活 husky 后,就可以在 git 的 commit-msg 钩子上挂载 commitlint 的提交信息检查:

# 推荐方式:在 package.json 中配置脚本的方式
npm pkg set scripts.commitlint="commitlint --edit"
echo 'npm run commitlint ${1}' > .husky/commit-msg

# 或(二选一)

# 在 commit-msg 钩子上直接运行 commitlint 的方式
echo 'npx --no -- commitlint --edit ${1}' > .husky/commit-msg

使用 git 提交一次不符合规范的备注信息进行验证:

git commit -m "foo: this will fail" # 输出报错,阻止提交

自 commitlint v8.0.0 版本后,如果提交没有任何问题将不会有任何输出。

交互式提交

@commitlint/prompt-cli

推荐程度:⭐

@commitlint/prompt-cli 是一个用于在命令行界面(CLI)中提示用户输入标准格式的提交消息的工具。并确保它们遵守 commitlint.config.js 中配置的提交约定。它是 commitlint 生态系统中的一部分。

# 安装
npm install --save-dev @commitlint/prompt-cli

# 配置 prompt-cli 运行脚本
npm pkg set scripts.commit="commit"

# 运行提交
npm run commit

commitizen

推荐程度:⭐⭐⭐

commitizen 提供了一种更现代的交互方式的命令行界面(CLI),更多详情参考:约定式提交规范三部曲(二)之 Commitizen

cz-conventional-template-zh-cn

推荐程度:⭐⭐⭐⭐⭐

简体中文版命令行提交交互工具 cz-conventional-template-zh-cn 是作者发布在 npmjs 通用的可应用于多仓库/项目(multi-repo)的 简体中文 模块 ,目前作者的所有项目全部都基于此模板进行规范化提交。

cz-conventional-template-zh-cn 只不过是使用 commitizen 的多仓库/项目方式。

更多详情参考:约定式提交规范三部曲(二)之 Commitizen

更多

config-conventional

在上面的 commitlint.config.js 配置文件中,我们配置了 config-conventional 规范,是用于定义和配置提交消息的规范,比如定义了提交类型、提交范围和提交描述等,而 commitlint 则可以根据这些规范对提交消息进行验证,确保符合规范要求。如果提交消息不符合约定的规范,commitlint 可以发出警告或阻止提交,从而帮助团队保持提交消息的一致性和规范性。

CI 持续集成

CI(Continuous Integration)持续集成,是一种软件开发实践,它通过自动化的构建和测试流程,确保团队成员的代码变更能够快速、可靠地集成到共享的代码库中。commitlint 可应用于持续集成中,更多信息可参考 Guide: CI Setup

下一步

本文为原创内容,版权所有 © 2024 姚生。欢迎转载,但请注明出处,并附上原文链接。未经授权不得用于商业用途。如有疑问,请联系作者。