提交规范配置

引言

要实现 Git 提交规范配置,通常会结合使用 commitlint 配合 husky 来确保提交信息符合约定的格式。
避免不规范的提交信息进入代码库。不仅提高了代码的可维护性,还能使团队协作更顺畅。


安装依赖

需要在项目中安装 commitlinthusky,这两个工具能够帮助实现提交信息的规范化。

  • @commitlint/cli: 是 commitlint 的命令行工具。
  • @commitlint/config-conventional: 是一组常用的提交信息规范规则。
  • husky: 用于在 Git 钩子(如 pre-commitcommit-msg)中添加钩子功能。
1
2
# 安装 commitlint 和 husky
npm install --save-dev @commitlint/{config-conventional,cli} husky

配置 Commitlint

在项目根目录下创建一个 commitlint 配置文件,通常是 .commitlintrc.jscommitlint.config.js
.commitlintrc.json,用于定义提交规范。

1
2
3
4
5
6
7
// commitlint.config.js
module.exports = {
extends: [
/* 表示遵循 `@commitlint/config-conventional` 中的默认规则。*/
'@commitlint/config-conventional'
]
};

@commitlint/config-conventional 常见规则包括:

  • type 必须是以下几种之一:
    • feat(新功能)
    • fix(修复)
    • docs(文档)
    • style(代码风格)
    • refactor(代码重构)
    • perf(性能优化)
    • test(增加测试)
    • build(构建工具相关)
    • ci(CI 配置相关)
    • chore(杂项任务)
    • revert(回滚)。
  • scope 可选,描述修改的范围。
  • subject 是提交的简短描述。

合规的提交信息示例:

1
2
# message:  type(scope): subject
git commit -m "feat(user): add login functionality"

配置 Husky

Husky 允许在 Git 钩子中添加自定义的行为,比如在提交时检查提交信息。

初始化 Husky 配置

1
npx husky

commit-msg hook

添加 commit-msg 钩子,这个钩子会在每次提交时检查提交信息是否符合规范。

配置 .husky/commit-msg 文件:

1
2
3
4
5
#!/usr/bin/env sh
#. "$(dirname "$0")/_/husky.sh"
echo "$0"

npx --no-install commitlint --edit "$1"

该钩子会在每次提交时自动调用 commitlint,确保提交信息符合规范。
如果提交信息不符合规则,提交会被拒绝,用户需要修改提交信息后再提交。


(可选) 自定义提交规范

如果需要自定义提交规范,可以在配置文件中进行修改。
可以更改 type 的可选值,或者自定义 subject 的最大长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
// type-enum: 定义提交类型
'type-enum': [
2,
'always',
[
'feat' /* 新功能 */,
'fix' /* 修补 bug */,
'docs' /* 文档 */,
'style' /* 代码风格 | 样式 */,
'refactor' /* 代码重构 */,
'perf' /* 性能优化 */,
'test' /* 增加测试 */,
'build' /* dep - 工具性依赖的安装与配置 | 构建工具相关 */,
'ci' /* CI 配置相关 */,
'chore' /* 杂项任务 */,
'revert' /* 回滚 */,
'workflow' /* 工作流 */,
'mod' /* 不明确类型的代码或模块调整 */,
'wip' /* 开发进行中 */,
'types' /* 类型定义文件 */,
'release' /* 版本发布相关 */,
'merge' /* 分支合并操作 */,
'bug' /* 修正非功能性问题 */,
'del' /* 删除 */,
'log' /* 日志类型 */,
'assets' /* 资源 */,
'base' /* 项目基础 */,
'editor' /* 编辑器配置 */
]
],
// subject-case: 定义主题的大小写格式
'subject-case': [
2,
'never',
[
'sentence-case',
'start-case',
'pascal-case',
'upper-case'
]
],
// subject-full-stop: 定义主题是否以句号结尾
'subject-full-stop': [2, 'never', '.'],
// header-max-length: 定义头部的最大长度
'header-max-length': [2, 'always', 72]
}
};