commit-check 2.20.3__py3-none-any.whl → 2.20.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
commit_check/__init__.py CHANGED
@@ -8,7 +8,8 @@ Exports:
8
8
 
9
9
  import os
10
10
  import sys
11
- from importlib.metadata import PackageNotFoundError, version
11
+ from functools import lru_cache
12
+ from typing import TYPE_CHECKING
12
13
 
13
14
  # Exit codes used across the package
14
15
  PASS = 0
@@ -158,7 +159,25 @@ DEFAULT_AI_DISCLOSURE_TRAILERS = ["Assisted-by", "Generated-by"]
158
159
  DEFAULT_AI_DISCLOSURE_PATTERN = ""
159
160
 
160
161
 
161
- try:
162
- __version__ = version("commit-check")
163
- except PackageNotFoundError:
164
- __version__ = "0.0.0.dev"
162
+ if TYPE_CHECKING:
163
+ __version__: str
164
+
165
+
166
+ @lru_cache(maxsize=1)
167
+ def _version() -> str:
168
+ """The installed package's version, read from its metadata."""
169
+ # Imported here, not at the top: importlib.metadata and the lookup cost
170
+ # more than the rest of startup, and only ``--version`` asks.
171
+ from importlib.metadata import PackageNotFoundError, version
172
+
173
+ try:
174
+ return version("commit-check")
175
+ except PackageNotFoundError:
176
+ return "0.0.0.dev"
177
+
178
+
179
+ def __getattr__(name: str) -> str:
180
+ """``__version__``, looked up on first access rather than at import."""
181
+ if name == "__version__":
182
+ return _version()
183
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
commit_check/_https.py ADDED
@@ -0,0 +1,32 @@
1
+ """The HTTPS-only opener that fetches a parent config for ``inherit_from``.
2
+
3
+ It lives apart from :mod:`commit_check.config` because ``urllib.request``
4
+ and ``urllib.error`` cost more to import than the rest of the CLI, and only
5
+ the rare run that inherits from a URL needs them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import urllib.error
11
+ import urllib.request
12
+
13
+
14
+ class HttpsOnlyRedirectHandler(urllib.request.HTTPRedirectHandler):
15
+ """Follow redirects only to HTTPS targets.
16
+
17
+ ``urlopen`` follows an HTTPS-to-HTTP redirect by default, which would
18
+ let a parent config be swapped in transit on the way to being merged
19
+ into the policy. Any redirect off HTTPS is refused instead.
20
+ """
21
+
22
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
23
+ if not newurl.startswith("https://"):
24
+ raise urllib.error.URLError(
25
+ f"redirect to a non-HTTPS URL refused: {newurl}"
26
+ )
27
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
28
+
29
+
30
+ def build_opener() -> urllib.request.OpenerDirector:
31
+ """An opener that refuses any redirect off HTTPS."""
32
+ return urllib.request.build_opener(HttpsOnlyRedirectHandler())
@@ -19,6 +19,7 @@ import re
19
19
  from collections.abc import Iterator
20
20
  from dataclasses import dataclass
21
21
  from functools import lru_cache
22
+ from typing import TYPE_CHECKING
22
23
 
23
24
  from commit_check.ai_signatures_data import ALL_KNOWN_TOOLS as _ALL_KNOWN_TOOLS
24
25
  from commit_check.ai_signatures_data import GENERIC_AI, ROLE_CO_AUTHOR, ROLE_DISCLOSURE
@@ -28,20 +29,38 @@ from commit_check.ai_signatures_data import GENERIC_AI, ROLE_CO_AUTHOR, ROLE_DIS
28
29
  ALL_KNOWN_TOOLS = _ALL_KNOWN_TOOLS
29
30
 
30
31
 
31
- #: Flat list of all compiled patterns for bulk scanning.
32
- #: Each tuple is ``(regex, tool_name, description, kind, role)``.
33
- ALL_PATTERNS: list[tuple[re.Pattern[str], str, str, str, str]] = [
34
- (p.regex, tool.name, p.description, p.kind, p.role)
35
- for tool in ALL_KNOWN_TOOLS
36
- for p in tool.patterns
37
- ]
32
+ if TYPE_CHECKING:
33
+ ALL_PATTERNS: list[tuple[re.Pattern[str], str, str, str, str]]
34
+
35
+
36
+ def __getattr__(name: str) -> object:
37
+ """``ALL_PATTERNS``, compiled on first access rather than at import.
38
+
39
+ Every pattern of the catalog as ``(regex, tool_name, description, kind,
40
+ role)``. The scanner reads the compiled groups instead (:func:`groups`),
41
+ so a run only builds this list when something asks for it by name, and
42
+ a run that checks no AI attribution compiles none of the catalog.
43
+ """
44
+ if name == "ALL_PATTERNS":
45
+ patterns = [
46
+ (p.regex, tool.name, p.description, p.kind, p.role)
47
+ for tool in ALL_KNOWN_TOOLS
48
+ for p in tool.patterns
49
+ ]
50
+ globals()["ALL_PATTERNS"] = patterns
51
+ return patterns
52
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
53
+
54
+
55
+ @lru_cache(maxsize=1)
56
+ def _named_tools() -> tuple[tuple[re.Pattern[str], str], ...]:
57
+ """The tools that can be recognised by name in free text."""
58
+ return tuple(
59
+ (tool.name_pattern, tool.name)
60
+ for tool in ALL_KNOWN_TOOLS
61
+ if tool.name_pattern is not None
62
+ )
38
63
 
39
- #: The tools that can be recognised by name in free text.
40
- _NAMED_TOOLS: list[tuple[re.Pattern[str], str]] = [
41
- (tool.name_pattern, tool.name)
42
- for tool in ALL_KNOWN_TOOLS
43
- if tool.name_pattern is not None
44
- ]
45
64
 
46
65
  #: What a match says about the tool: ``(tool, description, kind, role)``.
47
66
  _Member = tuple[str, str, str, str]
@@ -176,7 +195,7 @@ def _scan(message: str) -> Iterator[tuple[_Member, str]]:
176
195
 
177
196
  def tool_named_in(text: str) -> str | None:
178
197
  """The known tool *text* names, or ``None`` when it names none."""
179
- for pattern, name in _NAMED_TOOLS:
198
+ for pattern, name in _named_tools():
180
199
  if pattern.search(text):
181
200
  return name
182
201
  return None
@@ -16,6 +16,7 @@ from __future__ import annotations
16
16
 
17
17
  import re
18
18
  from dataclasses import dataclass, field
19
+ from functools import cached_property
19
20
 
20
21
  #: A trailer whose purpose is to disclose AI assistance: ``Assisted-by``
21
22
  #: (Linux kernel, Fedora, FluxCD), ``Generated-by`` (Apache Software
@@ -36,8 +37,11 @@ ROLES = frozenset({ROLE_DISCLOSURE, ROLE_CO_AUTHOR, ROLE_SIGNOFF, ROLE_STAMP})
36
37
  class AiSignaturePattern:
37
38
  """A single pattern that identifies AI tool usage in a commit message.
38
39
 
39
- :param regex: A compiled regex that, if matched anywhere in the commit
40
- message body, indicates the corresponding tool was involved.
40
+ :param source: A regex that, if matched anywhere in the commit message
41
+ body, indicates the corresponding tool was involved. It is compiled
42
+ with *flags* on first use of :attr:`regex`, not at import: a run
43
+ that never scans a message for AI signatures never pays for it.
44
+ :param flags: The ``re`` flags :attr:`regex` is compiled with.
41
45
  :param kind: ``"trailer"`` for structured ``Key: value`` footer lines
42
46
  (matched case-insensitively), ``"body_marker"`` for any other text
43
47
  marker.
@@ -52,13 +56,19 @@ class AiSignaturePattern:
52
56
  so a trailer line is read once however many tools the catalog knows.
53
57
  """
54
58
 
55
- regex: re.Pattern[str]
59
+ source: str
60
+ flags: int
56
61
  kind: str # "trailer" | "body_marker"
57
62
  role: str
58
63
  description: str = ""
59
64
  keys: frozenset[str] = frozenset()
60
65
  value_pattern: str = ""
61
66
 
67
+ @cached_property
68
+ def regex(self) -> re.Pattern[str]:
69
+ """The compiled :attr:`source`."""
70
+ return re.compile(self.source, self.flags)
71
+
62
72
 
63
73
  @dataclass(frozen=True)
64
74
  class KnownAiTool:
@@ -66,14 +76,26 @@ class KnownAiTool:
66
76
 
67
77
  :param name: Short display name (e.g. ``"Claude Code"``, ``"GitHub Copilot"``).
68
78
  :param patterns: One or more signature patterns that indicate this tool.
69
- :param name_pattern: A regex that recognises the tool when it is named in
70
- free text — the value of a disclosure trailer, say — so a generic
79
+ :param names: A regex for the tool's names, recognised as whole words
80
+ in free text — the value of a disclosure trailer, say — so a generic
71
81
  ``Assisted-by:`` match can still be attributed to the tool it names.
82
+ Compiled on first use of :attr:`name_pattern`.
72
83
  """
73
84
 
74
85
  name: str
75
86
  patterns: list[AiSignaturePattern] = field(default_factory=list)
76
- name_pattern: re.Pattern[str] | None = None
87
+ names: str | None = None
88
+
89
+ @cached_property
90
+ def name_pattern(self) -> re.Pattern[str] | None:
91
+ """:attr:`names` as whole words, or ``None`` for a tool without them.
92
+
93
+ Bounded at both ends, or ``Generated-by: Raider`` is disclosed as
94
+ Aider.
95
+ """
96
+ if self.names is None:
97
+ return None
98
+ return re.compile(rf"(?<!\w)(?:{self.names})(?!\w)", re.IGNORECASE)
77
99
 
78
100
 
79
101
  # ---------------------------------------------------------------------------
@@ -113,7 +135,8 @@ def _trailer(
113
135
  alternation = "|".join(re.escape(key) for key in keys)
114
136
  raw = rf"^(?:{alternation})[ \t]*:[ \t]*(?=\S)(?:{value_pattern})(?<![ \t])[ \t]*$"
115
137
  return AiSignaturePattern(
116
- regex=re.compile(raw, re.IGNORECASE | re.MULTILINE),
138
+ source=raw,
139
+ flags=re.IGNORECASE | re.MULTILINE,
117
140
  kind="trailer",
118
141
  role=role,
119
142
  description=description,
@@ -171,21 +194,14 @@ def _stamp_trailer(key: str, description: str) -> AiSignaturePattern:
171
194
  def _body_marker(pattern: str, description: str = "") -> AiSignaturePattern:
172
195
  """Build a free-text body marker pattern."""
173
196
  return AiSignaturePattern(
174
- regex=re.compile(pattern, re.MULTILINE),
197
+ source=pattern,
198
+ flags=re.MULTILINE,
175
199
  kind="body_marker",
176
200
  role=ROLE_STAMP,
177
201
  description=description,
178
202
  )
179
203
 
180
204
 
181
- def _names(pattern: str) -> re.Pattern[str]:
182
- """Compile a ``name_pattern``: the tool's names, as whole words.
183
-
184
- Bounded at both ends, or ``Generated-by: Raider`` is disclosed as Aider.
185
- """
186
- return re.compile(rf"(?<!\w)(?:{pattern})(?!\w)", re.IGNORECASE)
187
-
188
-
189
205
  # ---------------------------------------------------------------------------
190
206
  # Known tool signatures
191
207
  # ---------------------------------------------------------------------------
@@ -193,7 +209,7 @@ def _names(pattern: str) -> re.Pattern[str]:
193
209
  # --- Anthropic Claude Code / Claude CLI ---
194
210
  CLAUDE_CODE = KnownAiTool(
195
211
  name="Claude Code",
196
- name_pattern=_names(r"\bclaude\b|anthropic"),
212
+ names=r"\bclaude\b|anthropic",
197
213
  patterns=[
198
214
  # Standard Co-authored-by trailer added by Claude Code.
199
215
  # When an email is present, anchor to known AI noreply addresses
@@ -247,7 +263,7 @@ CLAUDE_CODE = KnownAiTool(
247
263
  # https://github.blog/changelog/2026-03-20-trace-any-copilot-coding-agent-commit-to-its-session-logs
248
264
  COPILOT = KnownAiTool(
249
265
  name="GitHub Copilot",
250
- name_pattern=_names(r"copilot"),
266
+ names=r"copilot",
251
267
  patterns=[
252
268
  *_identity(
253
269
  r"Copilot(?:[ \t]*<\d+\+Copilot@users\.noreply\.github\.com>)?",
@@ -266,7 +282,7 @@ COPILOT = KnownAiTool(
266
282
  # --- OpenAI Codex ---
267
283
  CODEX = KnownAiTool(
268
284
  name="OpenAI Codex",
269
- name_pattern=_names(r"codex"),
285
+ names=r"codex",
270
286
  patterns=[
271
287
  *_identity(r"Codex[ \t]*(?:<[^>\n]*>)?", "Codex"),
272
288
  # Codex in the cloud commits through its GitHub App.
@@ -280,7 +296,7 @@ CODEX = KnownAiTool(
280
296
  # --- Gemini (Google) ---
281
297
  GEMINI = KnownAiTool(
282
298
  name="Gemini",
283
- name_pattern=_names(r"gemini"),
299
+ names=r"gemini",
284
300
  patterns=[
285
301
  *_identity(r"Gemini[ \t]*(?:<[^>\n]*>)?", "Gemini"),
286
302
  ],
@@ -289,7 +305,7 @@ GEMINI = KnownAiTool(
289
305
  # --- Cursor ---
290
306
  CURSOR = KnownAiTool(
291
307
  name="Cursor",
292
- name_pattern=_names(r"cursor"),
308
+ names=r"cursor",
293
309
  patterns=[
294
310
  *_identity(r"Cursor(?: Agent)?[ \t]*(?:<[^>\n]*>)?", "Cursor"),
295
311
  # Cursor's agent signs as ``Cursor Agent <cursoragent@cursor.com>``;
@@ -318,7 +334,7 @@ CURSOR = KnownAiTool(
318
334
  # the address is the app's.
319
335
  DEVIN = KnownAiTool(
320
336
  name="Devin",
321
- name_pattern=_names(r"devin"),
337
+ names=r"devin",
322
338
  patterns=[
323
339
  *_identity(r"Devin AI[ \t]*(?:<[^>\n]*>)?", "Devin AI"),
324
340
  *_identity(
@@ -342,7 +358,7 @@ DEVIN = KnownAiTool(
342
358
  # --- Aider ---
343
359
  AIDER = KnownAiTool(
344
360
  name="Aider",
345
- name_pattern=_names(r"aider"),
361
+ names=r"aider",
346
362
  patterns=[
347
363
  *_identity(r"Aider[ \t]*(?:<[^>\n]*>)?", "Aider"),
348
364
  # aider's own trailer names the model, on by default since v0.85:
@@ -357,7 +373,7 @@ AIDER = KnownAiTool(
357
373
  # --- Windsurf (Codeium) ---
358
374
  WINDSURF = KnownAiTool(
359
375
  name="Windsurf",
360
- name_pattern=_names(r"windsurf|codeium"),
376
+ names=r"windsurf|codeium",
361
377
  patterns=[
362
378
  *_identity(r"Windsurf[ \t]*(?:<[^>\n]*>)?", "Windsurf"),
363
379
  ],
@@ -366,7 +382,7 @@ WINDSURF = KnownAiTool(
366
382
  # --- Tabby ---
367
383
  TABBY = KnownAiTool(
368
384
  name="Tabby",
369
- name_pattern=_names(r"tabby"),
385
+ names=r"tabby",
370
386
  patterns=[
371
387
  *_identity(r"Tabby[ \t]*(?:<[^>\n]*>)?", "Tabby"),
372
388
  ],
@@ -377,7 +393,7 @@ TABBY = KnownAiTool(
377
393
  # https://ampcode.com/docs/cli/settings
378
394
  AMP = KnownAiTool(
379
395
  name="Amp",
380
- name_pattern=_names(r"amp|ampcode"),
396
+ names=r"amp|ampcode",
381
397
  patterns=[
382
398
  # "Amp" is a short word, so when an address is present it must be
383
399
  # Amp's own.
@@ -392,7 +408,7 @@ AMP = KnownAiTool(
392
408
  # https://docs.openhands.dev/openhands/usage/settings/application-settings
393
409
  OPENHANDS = KnownAiTool(
394
410
  name="OpenHands",
395
- name_pattern=_names(r"openhands|all-hands"),
411
+ names=r"openhands|all-hands",
396
412
  patterns=[
397
413
  # By name only: the people who work at All Hands share the agent's
398
414
  # all-hands.dev domain.
@@ -405,7 +421,7 @@ OPENHANDS = KnownAiTool(
405
421
  # https://docs.factory.com/droid-cli/settings.md
406
422
  FACTORY_DROID = KnownAiTool(
407
423
  name="Factory Droid",
408
- name_pattern=_names(r"factory-droid|droid"),
424
+ names=r"factory-droid|droid",
409
425
  patterns=[
410
426
  *_identity(r"factory-droid\[bot\][ \t]*(?:<[^>\n]*>)?", "factory-droid[bot]"),
411
427
  ],
@@ -417,7 +433,7 @@ FACTORY_DROID = KnownAiTool(
417
433
  # "Jules" alone is a person's name, so only the app's name counts.
418
434
  JULES = KnownAiTool(
419
435
  name="Jules",
420
- name_pattern=_names(r"google-labs-jules|jules"),
436
+ names=r"google-labs-jules|jules",
421
437
  patterns=[
422
438
  *_identity(
423
439
  r"google-labs-jules\[bot\][ \t]*(?:<[^>\n]*>)?", "google-labs-jules[bot]"
@@ -459,7 +475,7 @@ CONTINUE = KnownAiTool(
459
475
  # names the tool.
460
476
  MISTRAL_VIBE = KnownAiTool(
461
477
  name="Mistral Vibe",
462
- name_pattern=_names(r"mistral[ \t-]?vibe"),
478
+ names=r"mistral[ \t-]?vibe",
463
479
  patterns=[
464
480
  *_identity(r"Mistral[ \t]+Vibe[ \t]*(?:<[^>\n]*>)?", "Mistral Vibe"),
465
481
  *_identity(r"[^<\n]*<vibe@mistral\.ai>", "... <vibe@mistral.ai>"),
@@ -475,7 +491,7 @@ MISTRAL_VIBE = KnownAiTool(
475
491
  # https://github.com/QwenLM/qwen-code/blob/main/packages/core/src/config/config.ts
476
492
  QWEN_CODE = KnownAiTool(
477
493
  name="Qwen Code",
478
- name_pattern=_names(r"qwen[ \t-]?code|qwen-coder"),
494
+ names=r"qwen[ \t-]?code|qwen-coder",
479
495
  patterns=[
480
496
  *_identity(r"Qwen-Coder[ \t]*(?:<[^>\n]*>)?", "Qwen-Coder"),
481
497
  *_identity(
@@ -489,7 +505,7 @@ QWEN_CODE = KnownAiTool(
489
505
  # The Amazon Q Developer agent commits through its GitHub App.
490
506
  AMAZON_Q = KnownAiTool(
491
507
  name="Amazon Q Developer",
492
- name_pattern=_names(r"amazon[ \t]+q(?:[ \t]+developer)?|amazon-q-developer"),
508
+ names=r"amazon[ \t]+q(?:[ \t]+developer)?|amazon-q-developer",
493
509
  patterns=[*_app_bot("amazon-q-developer")],
494
510
  )
495
511
 
@@ -516,7 +532,7 @@ WARP = KnownAiTool(
516
532
  # the charm.land address and the notice to its own wording.
517
533
  CRUSH = KnownAiTool(
518
534
  name="Crush",
519
- name_pattern=_names(r"crush"),
535
+ names=r"crush",
520
536
  patterns=[
521
537
  *_identity(r"[^<\n]*<crush@charm\.land>", "... <crush@charm.land>"),
522
538
  _body_marker(
commit_check/config.py CHANGED
@@ -8,10 +8,11 @@ import os
8
8
  import stat
9
9
  import sys
10
10
  import tomllib
11
- import urllib.error
12
- import urllib.request
13
11
  from pathlib import Path
14
- from typing import Any
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ if TYPE_CHECKING:
15
+ import urllib.request
15
16
 
16
17
  toml_load = tomllib.load
17
18
 
@@ -94,27 +95,12 @@ def _github_shorthand_to_url(value: str) -> str | None:
94
95
  return f"https://raw.githubusercontent.com/{repo_part}/{ref}/{file_path}"
95
96
 
96
97
 
97
- class _HttpsOnlyRedirectHandler(urllib.request.HTTPRedirectHandler):
98
- """Follow redirects only to HTTPS targets.
99
-
100
- ``urlopen`` follows an HTTPS-to-HTTP redirect by default, which would
101
- let a parent config be swapped in transit on the way to being merged
102
- into the policy. Any redirect off HTTPS is refused instead.
103
- """
104
-
105
- def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[override]
106
- if not newurl.startswith("https://"):
107
- raise urllib.error.URLError(
108
- f"redirect to a non-HTTPS URL refused: {newurl}"
109
- )
110
- return super().redirect_request(req, fp, code, msg, headers, newurl)
111
-
112
-
113
98
  class _LazyOpener:
114
99
  """The HTTPS-only opener, built on first use.
115
100
 
116
- ``build_opener`` is not free, and most runs never fetch a parent config
117
- at all, so the cost is paid only by the run that does.
101
+ Importing ``urllib`` and building the opener are not free, and most runs
102
+ never fetch a parent config at all, so the cost is paid only by the run
103
+ that does.
118
104
  """
119
105
 
120
106
  def __init__(self) -> None:
@@ -126,7 +112,9 @@ class _LazyOpener:
126
112
 
127
113
  def _get(self) -> urllib.request.OpenerDirector:
128
114
  if self._opener is None:
129
- self._opener = urllib.request.build_opener(_HttpsOnlyRedirectHandler())
115
+ from commit_check._https import build_opener
116
+
117
+ self._opener = build_opener()
130
118
  return self._opener
131
119
 
132
120
  def open(self, url: str, timeout: float = 10): # type: ignore[no-untyped-def]
commit_check/engine.py CHANGED
@@ -268,17 +268,20 @@ class BaseValidator(ABC):
268
268
  """Perform validation and return result."""
269
269
 
270
270
  @staticmethod
271
- def _resolve_current_author(context: ValidationContext) -> str:
271
+ def _resolve_current_author(
272
+ context: ValidationContext, pending: bool = False
273
+ ) -> str:
272
274
  """Resolve the relevant author identity based on validation mode.
273
275
 
274
276
  Two distinct modes:
275
277
 
276
- *Prospective message* (``stdin_text`` or ``commit_file`` is set):
278
+ *Prospective message* (``stdin_text`` or ``commit_file`` is set, or
279
+ *pending* is passed by a check that judges the next commit):
277
280
  the user is about to create a new commit. The last commit's author
278
281
  is unrelated — the relevant identity is the one git would record:
279
282
  ``GIT_AUTHOR_NAME`` when set (how a tool commits under its own name,
280
283
  and how the Action passes on the author of a commit it pipes in),
281
- else ``user.name``.
284
+ else ``author.name``, else ``user.name``.
282
285
 
283
286
  *Existing commit* (no ``stdin_text``, no ``commit_file``):
284
287
  the last commit is the one being validated. Use its own author
@@ -289,9 +292,10 @@ class BaseValidator(ABC):
289
292
  # An explicit revision names an existing commit; its author is a
290
293
  # fact about that commit, so the config never enters into it.
291
294
  return get_commit_info("an", context.rev)
292
- if context.stdin_text is not None or context.commit_file is not None:
295
+ if pending or context.stdin_text is not None or context.commit_file is not None:
293
296
  return (
294
297
  os.environ.get("GIT_AUTHOR_NAME", "").strip()
298
+ or get_git_config_value("author.name")
295
299
  or get_git_config_value(_USER_NAME)
296
300
  or get_commit_info("an")
297
301
  )
@@ -338,13 +342,15 @@ class BaseValidator(ABC):
338
342
  body = get_commit_info("b")
339
343
  return f"{subject}\n\n{body}".strip()
340
344
 
341
- def _author_in_ignore_list(self, context: ValidationContext) -> bool:
345
+ def _author_in_ignore_list(
346
+ self, context: ValidationContext, pending: bool = False
347
+ ) -> bool:
342
348
  """Check if the current author or any co-author is in the ignore list."""
343
349
  ignore_authors = context.config.get("commit", {}).get("ignore_authors", [])
344
350
  if not ignore_authors:
345
351
  return False
346
352
 
347
- current_author = self._resolve_current_author(context)
353
+ current_author = self._resolve_current_author(context, pending)
348
354
  if current_author and current_author in ignore_authors:
349
355
  self._skip_reason = f"author {current_author} is in [commit].ignore_authors"
350
356
  return True
@@ -688,11 +694,23 @@ class AuthorValidator(BaseValidator):
688
694
  """Validates author information."""
689
695
 
690
696
  def validate(self, context: ValidationContext) -> ValidationResult:
691
- # Use commit skip logic for ignore_authors
692
- if self._should_skip_commit_validation(context):
697
+ if self._author_in_ignore_list(context):
693
698
  return ValidationResult.SKIP
694
699
 
695
- author_value = self._get_author_value(context)
700
+ # With no message and no --rev the commit checks skip a repository
701
+ # that has no commits. The author checks do not: the value under
702
+ # test is the identity the next commit will carry, and git knows
703
+ # that before the first commit exists. ignore_authors then reads
704
+ # that identity too, there being no commit author to read.
705
+ has_head: bool | None = None
706
+ if not self._message_was_supplied(context):
707
+ has_head = has_commits()
708
+ if not has_head and self._author_in_ignore_list(context, pending=True):
709
+ return ValidationResult.SKIP
710
+
711
+ author_value = self._get_author_value(context, has_head)
712
+ if author_value is None:
713
+ return ValidationResult.SKIP
696
714
  if not author_value:
697
715
  return ValidationResult.PASS
698
716
 
@@ -700,11 +718,16 @@ class AuthorValidator(BaseValidator):
700
718
 
701
719
  return self._validate_author(author_value)
702
720
 
703
- def _get_author_value(self, context: ValidationContext) -> str:
721
+ def _get_author_value(
722
+ self, context: ValidationContext, has_head: bool | None = None
723
+ ) -> str | None:
704
724
  """Get author value based on rule type.
705
725
 
706
- Checks git config first (for pre-commit validation of the configured identity),
707
- then falls back to the last commit's author info.
726
+ Reads the identity git would record for a new commit first (for
727
+ pre-commit validation), then falls back to the last commit's author.
728
+ ``None`` when neither exists: no identity is configured and the
729
+ repository has no commit yet. *has_head* is whether it has one,
730
+ when the caller already knows.
708
731
  """
709
732
  supplied = context.piped_name
710
733
  if supplied is not None:
@@ -726,16 +749,31 @@ class AuthorValidator(BaseValidator):
726
749
  format_str = git_log_map.get(self.rule.check, "")
727
750
  return get_commit_info(format_str, context.rev) if format_str else ""
728
751
 
729
- # Try git config first (validates configured identity for new commits)
752
+ # The identity git would record for the next commit, in git's order:
753
+ # GIT_AUTHOR_NAME / GIT_AUTHOR_EMAIL (set for the hooks by
754
+ # ``git commit --author``, and by tools that commit under their own
755
+ # name), then author.name / author.email, then user.name / user.email.
730
756
  config_key = git_config_map.get(self.rule.check, "")
731
757
  if config_key:
732
- config_value = get_git_config_value(config_key)
733
- if config_value:
734
- return config_value
735
-
736
- # Fall back to last commit's author info
758
+ field = config_key.split(".")[1]
759
+ from_env = os.environ.get(f"GIT_AUTHOR_{field.upper()}", "").strip()
760
+ if from_env:
761
+ return from_env
762
+ for key in (f"author.{field}", config_key):
763
+ config_value = get_git_config_value(key)
764
+ if config_value:
765
+ return config_value
766
+
767
+ # Fall back to the last commit's author. Before the first commit
768
+ # there is none, and git would answer with an error message.
737
769
  format_str = git_log_map.get(self.rule.check, "")
738
- return get_commit_info(format_str) if format_str else ""
770
+ if not format_str:
771
+ return ""
772
+ if has_head is None:
773
+ has_head = has_commits()
774
+ if not has_head:
775
+ return None
776
+ return get_commit_info(format_str)
739
777
 
740
778
  def _validate_author(self, author_value: str) -> ValidationResult:
741
779
  """Validate author against rule constraints."""
@@ -1189,6 +1227,34 @@ class SignoffValidator(BaseValidator):
1189
1227
  return name, email
1190
1228
 
1191
1229
 
1230
+ #: A trailer line: a key with a hyphen (``Signed-off-by``, ``Change-Id``)
1231
+ #: or one of the common one-word keys, then a colon. A one-word key such as
1232
+ #: ``Note:`` is left as body text, since a sentence can start that way.
1233
+ _BODY_TRAILER_LINE = re.compile(
1234
+ r"^(?:[a-z]\w*-[\w-]+|Fixes|Closes|Resolves|Refs|Link|Cc|Bug)[ \t]*:",
1235
+ re.IGNORECASE,
1236
+ )
1237
+
1238
+
1239
+ def _body_without_trailers(message: str) -> str:
1240
+ """The body of *message*: what follows the subject, minus the trailer block.
1241
+
1242
+ ``git commit -s`` adds a ``Signed-off-by:`` line, so a message with only
1243
+ trailers after its subject used to count as having a body.
1244
+ """
1245
+ paragraphs = [
1246
+ p.strip() for p in re.split(r"\n[ \t]*\n", message.strip()) if p.strip()
1247
+ ]
1248
+ # The subject is the first line, even when the body follows it directly.
1249
+ rest = paragraphs[0].partition("\n")[2] if paragraphs else ""
1250
+ body = ([rest.strip()] if rest.strip() else []) + paragraphs[1:]
1251
+ if body and all(
1252
+ _BODY_TRAILER_LINE.match(ln.strip()) for ln in body[-1].splitlines()
1253
+ ):
1254
+ body = body[:-1]
1255
+ return "\n\n".join(body).strip()
1256
+
1257
+
1192
1258
  class BodyValidator(BaseValidator):
1193
1259
  """Validates that commit messages contain a body when required."""
1194
1260
 
@@ -1202,24 +1268,9 @@ class BodyValidator(BaseValidator):
1202
1268
 
1203
1269
  self._checked_value = message
1204
1270
 
1205
- # Split message into lines and check if there's content after the subject
1206
- lines = message.strip().split("\n")
1207
-
1208
- # Filter out empty lines
1209
- non_empty_lines = [line.strip() for line in lines if line.strip()]
1210
-
1211
- # If there's more than just the subject line, we have a body
1212
- if len(non_empty_lines) > 1:
1271
+ if _body_without_trailers(message):
1213
1272
  return ValidationResult.PASS
1214
1273
 
1215
- # Check if there's content after the first line (even if separated by empty lines)
1216
- # Unreachable: the message is stripped, so two or more lines always
1217
- # hold two non-empty ones and have passed above.
1218
- if len(lines) > 1: # pragma: no cover
1219
- body_content = "\n".join(lines[1:]).strip()
1220
- if body_content:
1221
- return ValidationResult.PASS
1222
-
1223
1274
  self._print_failure(message)
1224
1275
  return ValidationResult.FAIL
1225
1276
 
@@ -1697,10 +1748,13 @@ class AiAuthorValidator(BaseValidator):
1697
1748
  # would rewrite the one before it, and --reset-author on its own
1698
1749
  # records this same identity again. The Action pipes existing
1699
1750
  # pull request commits this way too, hence the last clause.
1751
+ # author.name and author.email outrank user.name and user.email,
1752
+ # so a tool named there survives setting the user.* pair alone.
1700
1753
  suggest = (
1701
1754
  "Commit as yourself: set git config user.name and user.email "
1702
- "to your own, and unset GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL "
1703
- "if a tool set them; a commit that already exists then needs "
1755
+ "to your own, and unset author.name, author.email, "
1756
+ "GIT_AUTHOR_NAME and GIT_AUTHOR_EMAIL if a tool set them; a "
1757
+ "commit that already exists then needs "
1704
1758
  "git commit --amend --reset-author"
1705
1759
  )
1706
1760
  else:
commit_check/main.py CHANGED
@@ -34,7 +34,7 @@ from commit_check.util import (
34
34
  split_message_comments,
35
35
  )
36
36
 
37
- from . import AI_ATTRIBUTION_POLICIES, __version__
37
+ from . import AI_ATTRIBUTION_POLICIES
38
38
 
39
39
  # Exit codes. ``1`` is a verdict on the commit; ``2`` means the run could not
40
40
  # be set up at all -- the same code argparse uses for a bad command line -- so
@@ -133,6 +133,35 @@ def _build_pre_commit_push_input() -> str | None:
133
133
  return f"{local_ref} {local_sha} {remote_ref} {remote_sha}"
134
134
 
135
135
 
136
+ class _VersionAction(argparse.Action):
137
+ """``--version``, with the version looked up only when it is asked for.
138
+
139
+ Reading the package metadata costs more than the rest of startup, so the
140
+ parser must not do it on every run just to have the string ready.
141
+ """
142
+
143
+ def __init__(self, option_strings: list[str], dest: str, **kwargs: object) -> None:
144
+ super().__init__(
145
+ option_strings,
146
+ dest=argparse.SUPPRESS,
147
+ default=argparse.SUPPRESS,
148
+ nargs=0,
149
+ help="show program's version number and exit",
150
+ )
151
+
152
+ def __call__(
153
+ self,
154
+ parser: argparse.ArgumentParser,
155
+ namespace: argparse.Namespace,
156
+ values: object,
157
+ option_string: str | None = None,
158
+ ) -> None:
159
+ from . import __version__
160
+
161
+ print(f"{parser.prog} {__version__}")
162
+ parser.exit()
163
+
164
+
136
165
  def _get_parser() -> argparse.ArgumentParser:
137
166
  """Get parser to interpret CLI args."""
138
167
  parser = argparse.ArgumentParser(
@@ -151,8 +180,7 @@ def _get_parser() -> argparse.ArgumentParser:
151
180
  parser.add_argument(
152
181
  "-v",
153
182
  "--version",
154
- action="version",
155
- version=f"%(prog)s {__version__}",
183
+ action=_VersionAction,
156
184
  )
157
185
 
158
186
  parser.add_argument(
@@ -222,6 +222,22 @@ def _check_booleans(config: dict[str, Any]) -> None:
222
222
  )
223
223
 
224
224
 
225
+ def _check_author_lists(config: dict[str, Any]) -> None:
226
+ """Make each ``ignore_authors`` a list, or refuse it.
227
+
228
+ A string such as ``"renovate[bot], Bot User"`` was tested with ``in``,
229
+ which on a string is a substring match: any author whose name was part
230
+ of it, ``bot`` or ``Bot``, skipped every check. A comma-separated string
231
+ is now split, as ``--ignore-authors`` and ``CCHK_IGNORE_AUTHORS`` split it.
232
+ """
233
+ for section in ("commit", "branch"):
234
+ values = config.get(section)
235
+ if isinstance(values, dict) and "ignore_authors" in values:
236
+ values["ignore_authors"] = _string_list(
237
+ values, "ignore_authors", [], f"[{section}] ignore_authors"
238
+ )
239
+
240
+
225
241
  class RuleBuilder:
226
242
  """Builds validation rules from config and catalog entries."""
227
243
 
@@ -233,6 +249,7 @@ class RuleBuilder:
233
249
  self.tag_config = config.get("tag", {})
234
250
  self.files_config = config.get("files", {})
235
251
  _check_booleans(config)
252
+ _check_author_lists(config)
236
253
  self.warn_checks = self._resolve_warn_list(config.get("warn", []))
237
254
 
238
255
  def build_all_rules(self) -> list[ValidationRule]:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: commit-check
3
- Version: 2.20.3
3
+ Version: 2.20.5
4
4
  Summary: Commit policy as code for teams and AI agents: check commit messages, branch names, authors, tags, files and AI attribution.
5
5
  Author-email: Xianpeng Shen <xianpeng.shen@gmail.com>
6
6
  License-Expression: MIT
@@ -87,7 +87,7 @@ Stop bad commits before they exist. In `.pre-commit-config.yaml`:
87
87
  ```yaml
88
88
  repos:
89
89
  - repo: https://github.com/commit-check/commit-check
90
- rev: v2.20.3
90
+ rev: v2.20.5
91
91
  hooks:
92
92
  - id: check-message
93
93
  - id: check-branch
@@ -0,0 +1,22 @@
1
+ commit_check/__init__.py,sha256=tUcLbyzkRZddft_HVCLOV7QPQuWyJ75sdDJNjyPOlkA,6140
2
+ commit_check/_https.py,sha256=Eyi-zKEfDcwXJ_3b82UOo9_RxFQkD8uF4zU7MGUVDj0,1215
3
+ commit_check/ai_policy.py,sha256=gYC3ROLgGL1TDyhPkFXkV-NiYbvMt80Qt0MFrJcbJY4,8131
4
+ commit_check/ai_signatures.py,sha256=y_iqVVmMXhcutcKoNvdp5dUUEwgsDwj1HGwYGyN5oCA,11708
5
+ commit_check/ai_signatures_data.py,sha256=fZ9TpKNGqk0sYuko5PoHUFEEL_uRu9HK9RYGSvZTp3w,23170
6
+ commit_check/api.py,sha256=07bvBtV8PrhZIOwCDHiHfu_7CXsX_4U2_K2xMAucd6c,12905
7
+ commit_check/config.py,sha256=R8FSnHRwC1NOwNdMBlcLnhfxmY_WxLaHBeBi2qanTdo,13331
8
+ commit_check/config_merger.py,sha256=52m45cPOVzQnjvxgjf8pHPbK3BKVHPrvBMmtocztU-0,13707
9
+ commit_check/engine.py,sha256=4AFfBGNTnrKrEsU1stzBQ3lXygFvNtUx5EDXTG9LTv4,80833
10
+ commit_check/fixes.py,sha256=BpbdoHsKDyw2WfsqymwYpnrW73aHdCDGr8tMF6Ho2RU,7305
11
+ commit_check/imperatives.py,sha256=dEd_ssu4G0j6Cann6jqPdB97lw5Adua43K0_Odg_FyA,9518
12
+ commit_check/main.py,sha256=0BXw9aHG335eX9-aD8Fe_pZeiRWYyxL51m2iew8NMQs,31992
13
+ commit_check/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ commit_check/rule_builder.py,sha256=N_3qkZpLG1Yb_hUTMFNro2w7VsWtXLGjjyGPEOEPs88,35708
15
+ commit_check/rules_catalog.py,sha256=KtP64QRFSI_p3fRtaF1XDx3MUikIU__p1o-XmQBpSMY,12736
16
+ commit_check/util.py,sha256=pl_UZIgluo9wGdqlaePWNbULKqAlQpZd3LTHm9OytCc,35170
17
+ commit_check-2.20.5.dist-info/licenses/LICENSE,sha256=9mdTva71kQhrpWh_nZulxrdCnUrl5c6xJYh5hdo4p_s,1070
18
+ commit_check-2.20.5.dist-info/METADATA,sha256=YcqMsf9WwfcDS1tAM-cCZs5Uwbuiw9zAIqv05wXPXJ8,18084
19
+ commit_check-2.20.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
20
+ commit_check-2.20.5.dist-info/entry_points.txt,sha256=YMrkFGeub-3-IanV1d9qnopXVaRQM7MA9foXKW9iZ88,86
21
+ commit_check-2.20.5.dist-info/top_level.txt,sha256=Wf46u-ooHBMJNHbhfrBNQw3wC5_m8wt-o_Lfbc4QpRg,13
22
+ commit_check-2.20.5.dist-info/RECORD,,
@@ -1,21 +0,0 @@
1
- commit_check/__init__.py,sha256=rzJMSqdTrxg7PmxRDY4yWhCbGkEXAT3hK4C9Y6NwxSU,5529
2
- commit_check/ai_policy.py,sha256=gYC3ROLgGL1TDyhPkFXkV-NiYbvMt80Qt0MFrJcbJY4,8131
3
- commit_check/ai_signatures.py,sha256=qPbyVndU5egHRtDtu3S2vEO5_lKyDsz1PLUWqKPMMvU,11054
4
- commit_check/ai_signatures_data.py,sha256=lvJDZ_-eH2RYqVn8MMry9oNXVv27u9okLawPZx_y4XA,22851
5
- commit_check/api.py,sha256=07bvBtV8PrhZIOwCDHiHfu_7CXsX_4U2_K2xMAucd6c,12905
6
- commit_check/config.py,sha256=I7yMZBJynjVUuY-GWAkuu9a59aT9fDTJsGh4znu2hDU,13941
7
- commit_check/config_merger.py,sha256=52m45cPOVzQnjvxgjf8pHPbK3BKVHPrvBMmtocztU-0,13707
8
- commit_check/engine.py,sha256=oZZ_FnDXYh_zXF_-JoShKyosOSrAUk5bj1vCLMCZuPc,78395
9
- commit_check/fixes.py,sha256=BpbdoHsKDyw2WfsqymwYpnrW73aHdCDGr8tMF6Ho2RU,7305
10
- commit_check/imperatives.py,sha256=dEd_ssu4G0j6Cann6jqPdB97lw5Adua43K0_Odg_FyA,9518
11
- commit_check/main.py,sha256=5nchWwh4axbrVBkUCVtedjccEBHxm9ynKSJjSq5VcvQ,31165
12
- commit_check/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
- commit_check/rule_builder.py,sha256=kujszrki8VKXAarrmUwOCu0Yv7QzIiu5lm5mRBAQVns,34950
14
- commit_check/rules_catalog.py,sha256=KtP64QRFSI_p3fRtaF1XDx3MUikIU__p1o-XmQBpSMY,12736
15
- commit_check/util.py,sha256=pl_UZIgluo9wGdqlaePWNbULKqAlQpZd3LTHm9OytCc,35170
16
- commit_check-2.20.3.dist-info/licenses/LICENSE,sha256=9mdTva71kQhrpWh_nZulxrdCnUrl5c6xJYh5hdo4p_s,1070
17
- commit_check-2.20.3.dist-info/METADATA,sha256=5XLZHm--1_ZKOTYJREm7M018AhFyIvSgmZwVdp6axKA,18084
18
- commit_check-2.20.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
19
- commit_check-2.20.3.dist-info/entry_points.txt,sha256=YMrkFGeub-3-IanV1d9qnopXVaRQM7MA9foXKW9iZ88,86
20
- commit_check-2.20.3.dist-info/top_level.txt,sha256=Wf46u-ooHBMJNHbhfrBNQw3wC5_m8wt-o_Lfbc4QpRg,13
21
- commit_check-2.20.3.dist-info/RECORD,,