文章目錄
- 前言
- 一、報錯提示
- 二、實現
- 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 格式
- 提供清晰、具體的錯誤信息
- 保持與傳統格式的兼容性