关于 commitlint
面向 commitlint 配置与使用的技能,用于按 Conventional Commits 规则检查提交信息。涵盖规则设置、配置发现、命令行与代码验证,以及与钩子、CI/CD 和 LLM 提交信息生成的集成。
主要功能
- 01发现 commitlint 配置文件
- 02配置 Conventional Commits 规则
- 03通过 CLI 或代码验证信息
- 04集成钩子与 CI/CD 检查
- 05提取规则用于 LLM 提示词
适用场景
- 01在代码库中设置提交信息检查
- 02在 CI/CD 流程中验证提交
- 03根据差异和规则生成提交信息
- 04排查 commitlint 配置错误
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jamie-bitflight/ claude_skills --skill commitlint安装后在 Claude Code 中输入/commitlint确认已加载。
详细介绍
Commitlint
使用 commitlint 配置和规则,根据 Conventional Commits 格式验证提交消息。
何时使用此技能
在以下情况下使用此技能:
- 为仓库设置 commitlint
- 配置 commitlint 规则和可共享配置
- 将 commitlint 集成到提交前钩子或 CI/CD 流水线
- 从 commitlint 配置中提取规则,以生成用于提交消息生成的 LLM 提示词
- 以编程方式验证提交消息
- 排查 commitlint 配置或验证错误
- 了解 commitlint 规则语法和严重级别
- 检测仓库中的 commitlint 配置文件
核心功能
配置检测
Commitlint 使用 cosmiconfig 按以下优先级查找配置文件:
专用配置文件:
.commitlintrc
.commitlintrc.json
.commitlintrc.yaml
.commitlintrc.yml
.commitlintrc.js
.commitlintrc.cjs
.commitlintrc.mjs
.commitlintrc.ts
.commitlintrc.cts
commitlint.config.js
commitlint.config.cjs
commitlint.config.mjs
commitlint.config.ts
commitlint.config.cts
包文件:
- 带有
commitlint字段的package.json - 带有
commitlint字段的package.yaml(PNPM)
配置格式
JavaScript ES 模块(推荐):
// commitlint.config.js or commitlint.config.mjs
export default {
extends: ['@commitlint/config-conventional'],
};
TypeScript:
// commitlint.config.ts
import type { UserConfig } from '@commitlint/types';
import { RuleConfigSeverity } from '@commitlint/types';
const config: UserConfig = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [RuleConfigSeverity.Error, 'always', ['feat', 'fix', 'docs']],
},
};
export default config;
JSON:
{
"extends": ["@commitlint/config-conventional"]
}
YAML:
extends:
- "@commitlint/config-conventional"
规则配置
规则配置为数组:[level, applicability, value]
严重级别:
| 级别 | 含义 | TypeScript 枚举 |
|---|---|---|
| 0 | 已禁用 | RuleConfigSeverity.Disabled |
| 1 | 警告 | RuleConfigSeverity.Warning |
| 2 | 错误 | RuleConfigSeverity.Error |
适用方式:
'always'- 规则必须匹配'never'- 规则不得匹配
规则示例:
rules: {
// Error if type is not in enum
'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore', 'revert']],
// Error if type is empty
'type-empty': [2, 'never'],
// Error if subject is empty
'subject-empty': [2, 'never'],
// Error if header exceeds 100 chars
'header-max-length': [2, 'always', 100],
// Error if subject ends with period
'subject-full-stop': [2, 'never', '.'],
// Warning if body doesn't have leading blank line
'body-leading-blank': [1, 'always'],
}
常见配置
@commitlint/config-conventional
最常用的可共享配置。默认的错误级别规则:
| 规则 | 配置 | 通过示例 | 未通过示例 |
|---|---|---|---|
type-enum | ['build', 'chore', 'ci', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test'] | fix: message | foo: message |
type-case | 'lowerCase' | fix: message | FIX: message |
type-empty | never | fix: message | : message |
subject-case | never + ['sentence-case', 'start-case', 'pascal-case', 'upper-case'] | fix: some message | fix: Some Message |
subject-empty | never | fix: message | fix: |
subject-full-stop | never, '.' | fix: message | fix: message. |
header-max-length | 100 | 短标头 | 标头超过 100 个字符 |
body-leading-blank | always(警告) | 正文前有空行 | 没有空行 |
body-max-line-length | 100 | 行长 <= 100 个字符 | 行长超过 100 个字符 |
footer-leading-blank | always(警告) | 页脚前有空行 | 没有空行 |
footer-max-line-length | 100 | 行长 <= 100 个字符 | 行长超过 100 个字符 |
完整配置架构
// commitlint.config.js
export default {
// Extend shareable configs (resolved via node resolution)
extends: ['@commitlint/config-conventional'],
// Parser preset for parsing commit messages
parserPreset: 'conventional-changelog-atom',
// Output formatter
formatter: '@commitlint/format',
// Custom rules (override inherited rules)
rules: {
'type-enum': [2, 'always', ['feat', 'fix', 'docs', 'style', 'refactor', 'test', 'chore']],
},
// Functions that return true to ignore specific commits
// Merged with default ignores (merge commits, reverts, semver tags)
ignores: [(commit) => commit.includes('WIP')],
// Whether to use default ignore patterns
// Default patterns: 'Merge pull request', 'Revert X', 'v1.2.3', etc.
defaultIgnores: true,
// Custom help URL shown on failure
helpUrl: 'https://example.com/commit-guidelines',
// Prompt configuration (for @commitlint/cz-commitlint)
prompt: {
messages: {},
questions: {
type: {
description: 'Select the type of change:',
},
},
},
};
CLI 用法
安装
# npm
npm install -D @commitlint/cli @commitlint/config-conventional
# yarn
yarn add -D @commitlint/cli @commitlint/config-conventional
# pnpm
pnpm add -D @commitlint/cli @commitlint/config-conventional
常用命令
# Lint the last commit
npx commitlint --last
# Lint a range of commits
npx commitlint --from HEAD~5
# Lint from a specific commit
npx commitlint --from abc1234
# Lint message from stdin
echo "feat: add feature" | npx commitlint
# Lint message from file
npx commitlint < .git/COMMIT_EDITMSG
# Lint with edit flag (reads .git/COMMIT_EDITMSG)
npx commitlint --edit
# Lint with custom config path
npx commitlint --config ./custom-commitlint.config.js
# Print resolved config
npx commitlint --print-config
# Strict mode (warnings become exit code 2)
npx commitlint --last --strict
退出代码
| 代码 | 含义 |
|---|---|
| 0 | 成功(没有错误) |
| 1 | 发现 Lint 错误 |
| 2 | 发现警告(仅严格模式) |
| 3 | 发现错误(严格模式) |
| 9 | 配置文件缺失(使用 -g 标志时) |
规则参考
Type 规则
| 规则 | 条件 | 默认适用性 |
|---|---|---|
type-enum | type 在 value 中 | always |
type-case | type 使用 value 指定的大小写形式 | always, 'lower-case' |
type-empty | type 为空 | never |
type-max-length | type 的字符数不超过 value | always, Infinity |
type-min-length | type 的字符数不少于 value | always, 0 |
主题规则
| 规则 | 条件 | 默认适用性 |
|---|---|---|
subject-case | subject 使用指定的 value 大小写形式 | always |
subject-empty | subject 为空 | never |
subject-full-stop | subject 以 value 结尾 | never, '.' |
subject-max-length | subject 的字符数不超过 value | always, Infinity |
subject-min-length | subject 的字符数不少于 value | always, 0 |
subject-exclamation-mark | subject 在 : 前有感叹号 | never |
范围规则
| 规则 | 条件 | 默认适用性 |
|---|---|---|
scope-enum | scope 在 value 中 | always, [] |
scope-case | scope 使用指定的 value 大小写形式 | always, 'lower-case' |
scope-empty | scope 为空 | never |
scope-max-length | scope 的字符数不超过 value | always, Infinity |
scope-min-length | scope 的字符数不少于 value | always, 0 |
标题规则
| 规则 | 条件 | 默认适用性 |
|---|---|---|
header-case | header 使用指定的 value 大小写形式 | always, 'lower-case' |
header-full-stop | header 以 value 结尾 | never, '.' |
header-max-length | header 的字符数不超过 value | always, 72 |
header-min-length | header 的字符数不少于 value | always, 0 |
header-trim | header 前后没有空白字符 | always |
正文规则
| 规则 | 条件 | 默认适用性 |
|---|---|---|
body-leading-blank | body 以空行开头 | always |
body-empty | body 为空 | never |
body-max-length | body 的字符数不超过 value | always, Infinity |
body-max-line-length | body 每行的字符数不超过 value(不包括 URL) | always, Infinity |
body-min-length | body 的字符数不少于 value | always, 0 |
body-case | body 使用指定的 value 大小写形式 | always, 'lower-case' |
body-full-stop | body 以 value 结尾 | never, '.' |
页脚规则
| 规则 | 条件 | 默认适用性 |
|---|---|---|
footer-leading-blank | footer 以空行开头 | always |
footer-empty | footer 为空 | never |
footer-max-length | footer 的字符数不超过 value | always, Infinity |
footer-max-line-length | footer 每行的字符数不超过 value | always, Infinity |
footer-min-length | footer 的字符数不少于 value | always, 0 |
大小写值
对于检查大小写的规则(*-case):
[
'lower-case', // lowercase
'upper-case', // UPPERCASE
'camel-case', // camelCase
'kebab-case', // kebab-case
'pascal-case', // PascalCase
'sentence-case', // Sentence case
'snake-case', // snake_case
'start-case', // Start Case
]
编程式用法
加载配置
import load from '@commitlint/load';
async function getCommitlintConfig() {
const config = await load();
console.log(config.rules);
return config;
}
验证消息
import load from '@commitlint/load';
import lint from '@commitlint/lint';
async function validateMessage(message) {
const config = await load();
const result = await lint(message, config.rules);
return {
valid: result.valid,
errors: result.errors,
warnings: result.warnings,
};
}
大模型集成模式
提取规则以生成提示词
根据 commitlint 配置生成适合大模型使用的约束:
def extract_rules_for_prompt(config: dict) -> str:
"""Extract commitlint rules into LLM-friendly format."""
rules = config.get("rules", {})
prompt_parts = []
# Extract type-enum if present
if "type-enum" in rules:
level, applicability, types = rules["type-enum"]
if level > 0 and applicability == "always":
prompt_parts.append(f"Allowed commit types: {', '.join(types)}")
# Extract scope-enum if present
if "scope-enum" in rules:
level, applicability, scopes = rules["scope-enum"]
if level > 0 and applicability == "always" and scopes:
prompt_parts.append(f"Allowed scopes: {', '.join(scopes)}")
# Extract header-max-length
if "header-max-length" in rules:
level, applicability, length = rules["header-max-length"]
if level > 0:
prompt_parts.append(f"Header must be {length} characters or less")
# Extract subject-case
if "subject-case" in rules:
level, applicability, cases = rules["subject-case"]
if level > 0 and applicability == "never":
prompt_parts.append(f"Subject must NOT use: {', '.join(cases)}")
return "\n".join(prompt_parts)
验证循环
import subprocess
async def validate_with_commitlint(message: str, cwd: Path | None = None) -> tuple[bool, list[str]]:
"""
Validate commit message with commitlint.
Args:
message: The commit message to validate
cwd: Working directory (defaults to current directory)
Returns:
Tuple of (is_valid, error_messages)
"""
result = subprocess.run(["npx", "commitlint"], input=message, capture_output=True, text=True, cwd=cwd)
if result.returncode == 0:
return True, []
# Parse errors from stderr
errors = [line.strip() for line in result.stderr.split("\n") if line.strip()]
return False, errors
验证循环模式:
- 大模型根据差异和规则生成提交消息
- 对生成的消息运行 commitlint
- 如果验证失败,将错误连同上下文反馈给大模型
- 重试(默认最多 3 次)
- 返回最终消息(有效消息,或重试后尽力生成的消息)
常见问题
Node v24 ESM 问题:
ES 模块配置请使用 .mjs 扩展名,或在 package.json 中添加 "type": "module"
缺少 extends:
不含 extends 或 rules 的配置会报错“Please add rules”。请至少包含其中一项:
export default {
extends: ['@commitlint/config-conventional'],
};
配置为空错误:
配置文件必须至少定义 extends 或 rules。
scope 枚举为空数组:
scope-enum 使用 [] 时会通过所有 scope。请使用具体数组进行限制:
rules: {
'scope-enum': [2, 'always', ['api', 'ui', 'docs']],
}
主题大小写陷阱:
@commitlint/config-conventional 对特定大小写形式使用 never,这意味着这些形式是禁止的(而非必须的):
// This forbids sentence-case, start-case, pascal-case, upper-case
'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case', 'upper-case']]
提交前集成
如需将 commitlint 集成到提交前钩子,请直接配置钩子管理器。如果你的工作区中安装了提交前插件,可以参考该插件的钩子设置指南。
Conventional Commits 参考
如需了解 Conventional Commits 格式规范和示例,请使用本文档中的参考内容。如果你的工作区中安装了 Conventional Commits 插件,可以参考该插件获取更多示例和消息模式。
参考资料
官方文档
- Commitlint 官方网站(访问日期:2025-01-15)
- 配置参考(访问日期:2025-01-15)
- 规则参考(访问日期:2025-01-15)
- CLI 参考(访问日期:2025-01-15)
- 入门指南(访问日期:2025-01-15)
- GitHub 仓库(访问日期:2025-01-15)
相关规范
- Conventional Commits - 提交消息格式规范
- Cosmiconfig - 配置文件发现机制