文章目录
- 前言
- 一、报错提示
- 二、实现
- 1.commitlint.config.js规范配置
- 2. **修改正则表达式**:
- 3. **移除 scope-case 规则**:
- 4. **增强自定义规则逻辑**:
- 测试结果:
- 正则表达式详解:
前言
提示:正常的配置git规范
看这篇配置即可;我的是在此规范上新加了一个要求
一、报错提示
要求:
以下可正常提交
git commit -m "fix: 修复按钮样式"
git commit -m "fix 11: 修复bug的id为11"
git commit -m "fix 11,22: 修复bug的id为11,22"
以下报错禁止
提交
git commit -m "fix abc: 输入了非数字的范围"
报错提示:
二、实现
1.commitlint.config.js规范配置
const config = {parserPreset: {parserOpts: {headerPattern: /^(\w+)(?:\s+([^:]*))?:\s*(.+)$/,headerCorrespondence: ["type", "scope", "subject"]}},ignores: [commit => commit.includes("init")],rules: {"header-max-length": [2, "always", 100],// "scope-case": [2, "always", ["lower-case", "upper-case", "numeric"]], // 允许非数字scope;避免与自定义规则冲突"subject-empty": [2, "never"],"subject-case": [2, "always", ["lower-case", "sentence-case", "start-case", "pascal-case", "upper-case"]],"subject-full-stop": [2, "never", "."],"type-empty": [2, "never"],"type-case": [2, "always", "lower-case"],"type-enum": [2, "always", ["feat", "fix", "style", "perf", "docs", "refactor", "test"]],"scope-issue-format": [2, "always"]},plugins: [{rules: {"scope-issue-format": parsed => {const { type, scope } = parsed// console.log("%c【" + "参数" + "】打印", "color:#fff;background:#0f0", parsed, type, scope)// 1. 如果没有 scope(传统格式),直接通过if (!scope) return [true]// 2. 验证 scope 格式(数字或逗号分隔的数字)if (/^\d+(,\d+)*$/.test(scope)) {return [true]}// 3. 检查类型是否正确(避免类型错误时显示错误信息)const validTypes = ["feat", "fix", "style", "perf", "docs", "refactor", "test"]if (!validTypes.includes(type)) {return [true] // 让 type-enum 规则处理类型错误}// 4. 如果 scope 存在但不符合数字格式,显示错误return [false, `类型格式错误!必须是以下格式之一:\n` + `- 基础类型: "${validTypes.join('", "')}"\n` + `- scope格式为数字: "fix 123" 或 "fix 111,222"`]}}}]
}export default config
2. 修改正则表达式:
headerPattern: /^(\w+)(?:\s+([^:]*))?:\s*(.+)$/
- 现在可以匹配任何非冒号字符作为 scope
- 支持以下格式:
fix: 描述
(scope 为 null)fix 123: 描述
(scope 为 “123”)fix abc: 描述
(scope 为 “abc”)fix 111,222: 描述
(scope 为 “111,222”)
3. 移除 scope-case 规则:
- 因为我们现在允许非数字 scope(但会在自定义规则中验证)
- 避免与自定义规则冲突
4. 增强自定义规则逻辑:
- 首先检查是否有 scope(传统格式直接通过)
- 然后验证 scope 是否为数字格式
- 最后检查类型是否正确(避免类型错误时显示错误信息)
测试结果:
# 正确格式
git commit -m "fix: 传统格式"
# 输出: 成功git commit -m "fix 123: 单issue格式"
# 输出: 成功git commit -m "fix 111,222: 多issue格式"
# 输出: 成功# 错误格式
git commit -m "fix abc: 非数字scope"
# 输出:
# Scope 格式错误!必须是数字或用逗号分隔的数字,例如:123 或 111,222
# 您输入的 scope: "abc" 不符合要求git commit -m "feat 123,abc: 混合格式"
# 输出:
# Scope 格式错误!必须是数字或用逗号分隔的数字,例如:123 或 111,222
# 您输入的 scope: "123,abc" 不符合要求
正则表达式详解:
^(\w+) // 匹配类型(如 "fix")
(?:\s+([^:]*))? // 非捕获组:一个或多个空格 + 任何非冒号字符(作为 scope)
:\s* // 冒号后跟零个或多个空格
(.+)$ // 匹配剩余部分作为描述
这个配置确保:
- 所有格式都能被正确解析(包括错误格式)
- 自定义规则能够正确验证 scope 格式
- 提供清晰、具体的错误信息
- 保持与传统格式的兼容性