Skip to content

Commit bfb5eb1

Browse files
feat: add stable rule IDs and a rules reference (#512)
* feat: add stable rule IDs and a rules reference Every check that can report a failure now has a stable rule ID (CC001, CC003, ...) plus a link to its documentation. IDs are assigned in the catalog and attached centrally when rules are built, so new rules inherit their identity automatically. Rule IDs and docs links now appear in the default, compact, and JSON output, giving users a durable handle to reference and look up. Add docs/rules.rst documenting every rule, and a test that fails if a rule ships without a corresponding entry in that page. * ci: auto fixes from pre-commit.com hooks * test: strengthen internal-entry assertion and document full output Assert unconditionally that the ignore_authors catalog entry and its built rule carry no rule ID; the previous conditional guard let the test pass vacuously if the rule were never built. Show the complete default output in the rules reference, including the Docs link, and document the compact form alongside it. * perf: derive rule identity from the catalog instead of copying it Attaching the rule ID with dataclasses.replace() rebuilt every rule on each build_all_rules() call, roughly doubling its cost (19us -> 41us) and showing up as a broad benchmark regression. Expose rule_id and docs_url as properties backed by a check-name lookup into the catalog. Identity still lives in one place, so rules cannot carry a stale copy, and building them no longer does extra work. Add a test asserting the lookup's key assumption that identified check names are unique. * docs: point rule links at the documentation domain Rule IDs print a link to their reference section, and that link ships in terminal output and JSON results. Settle it on the project's own domain before the first release that carries it, so the URLs do not need redirecting later. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent c8303f5 commit bfb5eb1

7 files changed

Lines changed: 557 additions & 9 deletions

File tree

‎commit_check/engine.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,19 @@ class CheckOutcome:
5858
value: str = ""
5959
error: str = ""
6060
suggest: str = ""
61+
rule_id: str = ""
62+
docs_url: str = ""
6163

6264
def to_dict(self) -> dict[str, str]:
6365
"""Serialise to a plain dict (suitable for JSON encoding)."""
6466
return {
67+
"rule_id": self.rule_id,
6568
"check": self.check,
6669
"status": self.status,
6770
"value": self.value,
6871
"error": self.error,
6972
"suggest": self.suggest,
73+
"docs_url": self.docs_url,
7074
}
7175

7276

@@ -873,9 +877,18 @@ def validate_all_detailed(self, context: ValidationContext) -> list[CheckOutcome
873877
value=failure.get("value", ""),
874878
error=failure.get("error", ""),
875879
suggest=failure.get("suggest", ""),
880+
rule_id=rule.rule_id or "",
881+
docs_url=rule.docs_url or "",
876882
)
877883
)
878884
else:
879-
outcomes.append(CheckOutcome(check=rule.check, status="pass"))
885+
outcomes.append(
886+
CheckOutcome(
887+
check=rule.check,
888+
status="pass",
889+
rule_id=rule.rule_id or "",
890+
docs_url=rule.docs_url or "",
891+
)
892+
)
880893

881894
return outcomes

‎commit_check/rule_builder.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
COMMIT_RULES,
88
BRANCH_RULES,
99
PUSH_RULES,
10+
RULES_BY_CHECK,
1011
RuleCatalogEntry,
1112
)
1213
from commit_check import (
@@ -31,6 +32,18 @@ class ValidationRule:
3132
allowed: list[str] | None = None
3233
ignored: list[str] | None = None
3334

35+
@property
36+
def rule_id(self) -> str | None:
37+
"""Stable rule ID from the catalog, e.g. ``CC003``."""
38+
entry = RULES_BY_CHECK.get(self.check)
39+
return entry.rule_id if entry else None
40+
41+
@property
42+
def docs_url(self) -> str | None:
43+
"""Link to this rule's section in the rules reference."""
44+
entry = RULES_BY_CHECK.get(self.check)
45+
return entry.docs_url if entry else None
46+
3447
def to_dict(self) -> dict[str, Any]:
3548
"""Convert to dictionary for backward compatibility."""
3649
result: dict[str, Any] = {
@@ -39,6 +52,10 @@ def to_dict(self) -> dict[str, Any]:
3952
"error": self.error or "",
4053
"suggest": self.suggest or "",
4154
}
55+
if self.rule_id:
56+
result["rule_id"] = self.rule_id
57+
if self.docs_url:
58+
result["docs_url"] = self.docs_url
4259
if self.value is not None:
4360
result["value"] = self.value
4461
if self.allowed:

‎commit_check/rules_catalog.py‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,110 +1,159 @@
1-
"""Centralized catalog of all commit-check rules, regexes, and error messages."""
1+
"""Centralized catalog of all commit-check rules, regexes, and error messages.
2+
3+
Every user-facing rule has a **stable rule ID** (e.g. ``CC003``) that never
4+
changes once released. Rule IDs give users a durable handle to reference in
5+
documentation, error output, and machine-readable results.
6+
7+
ID ranges
8+
---------
9+
========= ==================================
10+
``CC0xx`` Commit message rules
11+
``CC1xx`` Author (name / email) rules
12+
``CC2xx`` Branch rules
13+
``CC3xx`` Push rules
14+
========= ==================================
15+
16+
Internal bookkeeping entries that never produce a diagnostic (such as
17+
``ignore_authors``) intentionally have no rule ID.
18+
"""
219

320
from __future__ import annotations
421
from dataclasses import dataclass
522

23+
#: Base URL of the rules reference documentation.
24+
RULES_DOCS_URL = "https://docs.commit-check.com/rules.html"
25+
626

727
@dataclass(frozen=True)
828
class RuleCatalogEntry:
929
check: str
1030
regex: str | None = None
1131
error: str | None = None
1232
suggest: str | None = None
33+
rule_id: str | None = None
34+
35+
@property
36+
def name(self) -> str:
37+
"""Human-readable rule name, e.g. ``subject-imperative``."""
38+
return self.check.replace("_", "-")
39+
40+
@property
41+
def docs_url(self) -> str | None:
42+
"""Link to this rule's section in the rules reference, if it has an ID."""
43+
if not self.rule_id:
44+
return None
45+
return f"{RULES_DOCS_URL}#{self.rule_id.lower()}"
1346

1447

1548
# Commit message rules
1649
COMMIT_RULES = [
1750
RuleCatalogEntry(
51+
rule_id="CC001",
1852
check="message",
1953
regex=None, # Built dynamically from config
2054
error="The commit message should follow Conventional Commits. See https://www.conventionalcommits.org",
2155
suggest="Use <type>(<scope>): <description> with allowed types",
2256
),
2357
RuleCatalogEntry(
58+
rule_id="CC002",
2459
check="subject_capitalized",
2560
regex=None,
2661
error="Subject must start with a capital letter",
2762
suggest="Capitalize the first word of the subject",
2863
),
2964
RuleCatalogEntry(
65+
rule_id="CC003",
3066
check="subject_imperative",
3167
regex=None,
3268
error="Commit message should use imperative mood (e.g., 'fix bug' not 'fixed bug', 'add feature' not 'adding feature')",
3369
suggest="Change the first verb to imperative form, e.g., 'fix' instead of 'fixed'/'fixes'/'fixing'",
3470
),
3571
RuleCatalogEntry(
72+
rule_id="CC004",
3673
check="subject_max_length",
3774
regex=None,
3875
error="Subject must be at most {max_len} characters",
3976
suggest="Keep the subject concise (<= configured max)",
4077
),
4178
RuleCatalogEntry(
79+
rule_id="CC005",
4280
check="subject_min_length",
4381
regex=None,
4482
error="Subject must be at least {min_len} characters",
4583
suggest="Provide a meaningful subject (>= configured min)",
4684
),
4785
RuleCatalogEntry(
86+
rule_id="CC006",
4887
check="allow_merge_commits",
4988
regex=None,
5089
error="Merge commits are not allowed",
5190
suggest="Rebase or squash your changes instead of merging",
5291
),
5392
RuleCatalogEntry(
93+
rule_id="CC007",
5494
check="allow_revert_commits",
5595
regex=None,
5696
error="Revert commits are not allowed",
5797
suggest="Avoid using 'revert' commits; rewrite history if necessary",
5898
),
5999
RuleCatalogEntry(
100+
rule_id="CC008",
60101
check="allow_empty_commits",
61102
regex=None,
62103
error="Empty commit messages are not allowed",
63104
suggest="Provide a non-empty subject",
64105
),
65106
RuleCatalogEntry(
107+
rule_id="CC009",
66108
check="allow_fixup_commits",
67109
regex=None,
68110
error="Fixup commits are not allowed",
69111
suggest="Use interactive rebase to clean up fixup commits",
70112
),
71113
RuleCatalogEntry(
114+
rule_id="CC010",
72115
check="allow_wip_commits",
73116
regex=None,
74117
error="WIP commits are not allowed",
75118
suggest="Complete the work before committing or remove 'WIP'",
76119
),
77120
RuleCatalogEntry(
121+
rule_id="CC011",
78122
check="require_body",
79123
regex=None,
80124
error="Commit body is required",
81125
suggest="Add a body explaining the change",
82126
),
83127
RuleCatalogEntry(
128+
rule_id="CC101",
84129
check="author_name",
85130
regex=r"^[A-Za-zÀ-ÖØ-öø-ÿ\u0100-\u017F\u0180-\u024F ,.'\-]+$|.*(\[bot])",
86131
error="The committer name seems invalid",
87132
suggest="git config user.name 'Your Name'",
88133
),
89134
RuleCatalogEntry(
135+
rule_id="CC102",
90136
check="author_email",
91137
regex=r"^.+@.+$",
92138
error="The committer's email seems invalid",
93139
suggest="git config user.email [email protected]",
94140
),
95141
RuleCatalogEntry(
142+
# Internal bookkeeping entry - never produces a diagnostic.
96143
check="ignore_authors",
97144
regex=None,
98145
error=None,
99146
suggest=None,
100147
),
101148
RuleCatalogEntry(
149+
rule_id="CC012",
102150
check="require_signed_off_by",
103151
regex=r"Signed-off-by: .+ <.+@.+>",
104152
error="Signed-off-by not found in latest commit",
105153
suggest="git commit --amend --signoff or use --signoff on commit",
106154
),
107155
RuleCatalogEntry(
156+
rule_id="CC013",
108157
check="ai_attribution",
109158
regex=None,
110159
error="AI attribution policy violation",
@@ -115,6 +164,7 @@ class RuleCatalogEntry:
115164
# Push rules
116165
PUSH_RULES = [
117166
RuleCatalogEntry(
167+
rule_id="CC301",
118168
check="no_force_push",
119169
regex=None,
120170
error="Force push is not allowed",
@@ -125,21 +175,35 @@ class RuleCatalogEntry:
125175
# Branch rules
126176
BRANCH_RULES = [
127177
RuleCatalogEntry(
178+
rule_id="CC201",
128179
check="branch",
129180
regex=None, # Built dynamically from config
130181
error="The branch should follow Conventional Branch. See https://conventionalbranch.org",
131182
suggest="Use <type>/<description> with allowed types or add branch name to allow_branch_names in config, or use ignore_authors in config branch section to bypass",
132183
),
133184
RuleCatalogEntry(
185+
rule_id="CC202",
134186
check="merge_base",
135187
regex=None, # Provided by config
136188
error="Current branch is not rebased onto target branch",
137189
suggest="Rebase or merge with the target branch",
138190
),
139191
RuleCatalogEntry(
192+
# Internal bookkeeping entry - never produces a diagnostic.
140193
check="ignore_authors",
141194
regex=None,
142195
error=None,
143196
suggest=None,
144197
),
145198
]
199+
200+
#: All catalog entries that represent a user-facing, documented rule.
201+
ALL_RULES = [
202+
entry
203+
for entry in (*COMMIT_RULES, *BRANCH_RULES, *PUSH_RULES)
204+
if entry.rule_id is not None
205+
]
206+
207+
#: Lookup from check name to its catalog entry, for rules that have an ID.
208+
#: Rule identity lives only here, so built rules can never carry a stale copy.
209+
RULES_BY_CHECK = {entry.check: entry for entry in ALL_RULES}

‎commit_check/util.py‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,25 @@ def _print_failure(
1919
compact: bool = False,
2020
) -> None:
2121
"""Print a standardized failure message."""
22+
rule_id = check.get("rule_id", "")
2223
if compact:
2324
compact_value = actual.splitlines()[0] if actual else actual
24-
print(f"[FAIL] {check['check']}: {compact_value}")
25+
label = f"{rule_id} {check['check']}" if rule_id else check["check"]
26+
print(f"[FAIL] {label}: {compact_value}")
2527
return
2628
if not no_banner and not print_error_header.has_been_called:
2729
print_error_header()
28-
print_error_message(check["check"], check.get("error", ""), actual)
30+
print_error_message(
31+
check["check"],
32+
check.get("error", ""),
33+
actual,
34+
rule_id=rule_id,
35+
)
2936
if check.get("suggest"):
3037
print_suggestion(check["suggest"])
38+
docs_url = check.get("docs_url", "")
39+
if docs_url:
40+
print(f"Docs: {docs_url}")
3141

3242

3343
def get_branch_name() -> str:
@@ -284,16 +294,19 @@ def print_error_header():
284294
print(" ")
285295

286296

287-
def print_error_message(check_type: str, error: str, reason: str):
297+
def print_error_message(check_type: str, error: str, reason: str, rule_id: str = ""):
288298
"""Print error message.
289-
:param check_type:
290-
:param error:
291-
:param reason:
299+
300+
:param check_type: the check that failed, e.g. ``subject_imperative``
301+
:param error: the human-readable explanation of the failure
302+
:param reason: the offending value
303+
:param rule_id: stable rule ID, e.g. ``CC003`` (omitted when empty)
292304
293305
:returns: Give error messages to user
294306
"""
307+
prefix = f"{YELLOW}{rule_id}{RESET_COLOR} " if rule_id else ""
295308
print(
296-
f"Type {YELLOW}{check_type}{RESET_COLOR} check failed ==> {RED}{reason}{RESET_COLOR} ",
309+
f"{prefix}{YELLOW}{check_type}{RESET_COLOR} check failed ==> {RED}{reason}{RESET_COLOR} ",
297310
end="",
298311
)
299312
print("")

‎docs/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
self
77
what-is-new
88
configuration
9+
rules
910
example
1011
migration
1112
troubleshoot

0 commit comments

Comments
 (0)