mcpField
C
commitlint

commitlint

github.com/jamie-bitflight开发35 次安装
代码仓库

关于 commitlint

面向 commitlint 配置与使用的技能,用于按 Conventional Commits 规则检查提交信息。涵盖规则设置、配置发现、命令行与代码验证,以及与钩子、CI/CD 和 LLM 提交信息生成的集成。

主要功能

  1. 01发现 commitlint 配置文件
  2. 02配置 Conventional Commits 规则
  3. 03通过 CLI 或代码验证信息
  4. 04集成钩子与 CI/CD 检查
  5. 05提取规则用于 LLM 提示词

适用场景

  1. 01在代码库中设置提交信息检查
  2. 02在 CI/CD 流程中验证提交
  3. 03根据差异和规则生成提交信息
  4. 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: messagefoo: message
type-case'lowerCase'fix: messageFIX: message
type-emptyneverfix: message: message
subject-casenever + ['sentence-case', 'start-case', 'pascal-case', 'upper-case']fix: some messagefix: Some Message
subject-emptyneverfix: messagefix:
subject-full-stopnever, '.'fix: messagefix: message.
header-max-length100短标头标头超过 100 个字符
body-leading-blankalways(警告)正文前有空行没有空行
body-max-line-length100行长 <= 100 个字符行长超过 100 个字符
footer-leading-blankalways(警告)页脚前有空行没有空行
footer-max-line-length100行长 <= 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-enumtype 在 value 中always
type-casetype 使用 value 指定的大小写形式always, 'lower-case'
type-emptytype 为空never
type-max-lengthtype 的字符数不超过 valuealways, Infinity
type-min-lengthtype 的字符数不少于 valuealways, 0
主题规则
规则条件默认适用性
subject-casesubject 使用指定的 value 大小写形式always
subject-emptysubject 为空never
subject-full-stopsubject 以 value 结尾never, '.'
subject-max-lengthsubject 的字符数不超过 valuealways, Infinity
subject-min-lengthsubject 的字符数不少于 valuealways, 0
subject-exclamation-marksubject 在 : 前有感叹号never
范围规则
规则条件默认适用性
scope-enumscope 在 value 中always, []
scope-casescope 使用指定的 value 大小写形式always, 'lower-case'
scope-emptyscope 为空never
scope-max-lengthscope 的字符数不超过 valuealways, Infinity
scope-min-lengthscope 的字符数不少于 valuealways, 0
标题规则
规则条件默认适用性
header-caseheader 使用指定的 value 大小写形式always, 'lower-case'
header-full-stopheader 以 value 结尾never, '.'
header-max-lengthheader 的字符数不超过 valuealways, 72
header-min-lengthheader 的字符数不少于 valuealways, 0
header-trimheader 前后没有空白字符always
正文规则
规则条件默认适用性
body-leading-blankbody 以空行开头always
body-emptybody 为空never
body-max-lengthbody 的字符数不超过 valuealways, Infinity
body-max-line-lengthbody 每行的字符数不超过 value(不包括 URL)always, Infinity
body-min-lengthbody 的字符数不少于 valuealways, 0
body-casebody 使用指定的 value 大小写形式always, 'lower-case'
body-full-stopbody 以 value 结尾never, '.'
页脚规则
规则条件默认适用性
footer-leading-blankfooter 以空行开头always
footer-emptyfooter 为空never
footer-max-lengthfooter 的字符数不超过 valuealways, Infinity
footer-max-line-lengthfooter 每行的字符数不超过 valuealways, Infinity
footer-min-lengthfooter 的字符数不少于 valuealways, 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

验证循环模式:

  1. 大模型根据差异和规则生成提交消息
  2. 对生成的消息运行 commitlint
  3. 如果验证失败,将错误连同上下文反馈给大模型
  4. 重试(默认最多 3 次)
  5. 返回最终消息(有效消息,或重试后尽力生成的消息)

常见问题

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 插件,可以参考该插件获取更多示例和消息模式。

参考资料

官方文档
相关规范

评论

支持 Markdown