commit-check 2.25.0__py3-none-any.whl → 2.26.1__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
@@ -164,8 +164,10 @@ DEFAULT_BOOLEAN_RULES = {
164
164
  #: The policies ``ai_attribution`` accepts. ``ignore`` checks nothing;
165
165
  #: ``forbid`` rejects every known AI signature; ``disclose`` accepts AI
166
166
  #: assistance that is disclosed with an accepted trailer and rejects the tool
167
- #: as a co-author or a sign-off.
168
- AI_ATTRIBUTION_POLICIES = ("ignore", "forbid", "disclose")
167
+ #: as a co-author or a sign-off; ``require`` is ``disclose`` with a
168
+ #: disclosure on every commit, ``Assisted-by: none`` when no tool helped, so
169
+ #: a missing trailer is not read as "no AI".
170
+ AI_ATTRIBUTION_POLICIES = ("ignore", "forbid", "disclose", "require")
169
171
  DEFAULT_AI_ATTRIBUTION = "ignore"
170
172
  # The trailers that disclose AI assistance under "disclose": Assisted-by is
171
173
  # the Linux kernel's, Fedora's and FluxCD's; Generated-by is the Apache
@@ -173,6 +175,25 @@ DEFAULT_AI_ATTRIBUTION = "ignore"
173
175
  DEFAULT_AI_DISCLOSURE_TRAILERS = ["Assisted-by", "Generated-by"]
174
176
  # A regex the disclosure's value must match; empty accepts any non-empty value.
175
177
  DEFAULT_AI_DISCLOSURE_PATTERN = ""
178
+ #: The value of a disclosure trailer that says no AI tool helped.
179
+ AI_DISCLOSURE_NONE = "none"
180
+
181
+ # Pull request rules
182
+ #: What counts as naming an issue in a pull request description when
183
+ #: ``[pull_request] issue_reference_pattern`` is not set (CC502): ``#123``,
184
+ #: ``GH-123``, ``owner/repo#123`` (or a GitLab ``group/sub/project#123``),
185
+ #: and a link to an issue on GitHub, GitLab or Bitbucket Cloud, or to a Jira
186
+ #: ticket. A bare Jira key is left out: ``[A-Z]+-\d+`` also matches
187
+ #: ``UTF-8``, ``SHA-256`` and ``ISO-8601``.
188
+ DEFAULT_ISSUE_REFERENCE_PATTERN = (
189
+ r"(?<![\w/&#])#\d+\b"
190
+ r"|\b[Gg][Hh]-\d+\b"
191
+ r"|(?<![\w/.-])[\w.-]+(?:/[\w.-]+)+#\d+\b"
192
+ # The path of a link: its start is not needed to tell, and matching from
193
+ # "https://" would rescan the rest of a long line from every scheme.
194
+ r"|/(?:issues|work_items)/\d+\b"
195
+ r"|/browse/[A-Z][A-Z0-9_]*-\d+\b"
196
+ )
176
197
 
177
198
 
178
199
  if TYPE_CHECKING:
commit_check/ai_policy.py CHANGED
@@ -18,7 +18,11 @@ import re
18
18
  from dataclasses import dataclass
19
19
  from functools import lru_cache
20
20
 
21
- from commit_check.ai_signatures import detect_ai_signatures, find_trailers
21
+ from commit_check.ai_signatures import (
22
+ detect_ai_signatures,
23
+ find_trailers,
24
+ is_none_disclosure,
25
+ )
22
26
  from commit_check.ai_signatures_data import (
23
27
  GENERIC_AI,
24
28
  PERSON_TRAILERS,
@@ -49,6 +53,11 @@ class Disclosure:
49
53
  def ok(self) -> bool:
50
54
  return not self.problem
51
55
 
56
+ @property
57
+ def says_none(self) -> bool:
58
+ """Whether it declares that no AI tool helped (``Assisted-by: none``)."""
59
+ return is_none_disclosure(self.value)
60
+
52
61
 
53
62
  @dataclass(frozen=True)
54
63
  class AiPolicyReport:
@@ -67,9 +76,19 @@ class AiPolicyReport:
67
76
 
68
77
  @property
69
78
  def disclosed(self) -> bool:
70
- """Whether an accepted, well-formed disclosure is present."""
79
+ """Whether an accepted, well-formed disclosure names a tool."""
80
+ return any(d.ok and not d.says_none for d in self.disclosures)
81
+
82
+ @property
83
+ def declared(self) -> bool:
84
+ """Whether an accepted disclosure says either way, ``none`` included."""
71
85
  return any(d.ok for d in self.disclosures)
72
86
 
87
+ @property
88
+ def says_none(self) -> list[Disclosure]:
89
+ """The disclosures that declare no AI tool helped."""
90
+ return [d for d in self.disclosures if d.says_none]
91
+
73
92
  @property
74
93
  def malformed(self) -> list[Disclosure]:
75
94
  return [d for d in self.disclosures if d.problem]
@@ -96,6 +115,8 @@ class AiPolicyReport:
96
115
  or self.malformed
97
116
  or self.co_author_lines
98
117
  or self.signoff_lines
118
+ # "none" beside a tool contradicts itself.
119
+ or (self.says_none and self.disclosed)
99
120
  )
100
121
 
101
122
 
@@ -117,7 +138,9 @@ def _problem_with(value: str, pattern: str) -> str:
117
138
  """Why a disclosure does not count, or ``""`` when it does."""
118
139
  if not value:
119
140
  return "empty"
120
- if pattern and not re.match(pattern, value):
141
+ # "none" is the one value every project's pattern accepts: it names no
142
+ # tool, so there is no agent/model to write.
143
+ if pattern and not is_none_disclosure(value) and not re.match(pattern, value):
121
144
  return "pattern"
122
145
  return ""
123
146
 
@@ -201,25 +224,51 @@ def propose_fix(
201
224
  return None
202
225
  key = accepted[0]
203
226
  needed = not report.disclosed
204
- rewrites: dict[str, str | None] = {}
205
- for signature in (
206
- *report.co_author_lines,
207
- *report.signoff_lines,
208
- *report.other_disclosures,
209
- ):
210
- rewrites[signature["matched_text"]] = (
227
+ rewrites: dict[str, str | None] = {
228
+ signature["matched_text"]: (
211
229
  f"{key}: {_disclosed_value(signature)}" if needed else None
212
230
  )
231
+ for signature in (
232
+ *report.co_author_lines,
233
+ *report.signoff_lines,
234
+ *report.other_disclosures,
235
+ )
236
+ }
237
+ rewritten = bool(rewrites)
213
238
  fixed = (rewrite_lines(message, rewrites) if rewrites else None) or message
214
- if needed and not rewrites:
215
- # Only a vendor's mark says a tool was here, so nothing is rewritten
216
- # and the disclosure is added. A mark that names no particular tool
217
- # gives nothing to write after the key.
218
- tools = list(dict.fromkeys(s["tool"] for s in report.stamps))
219
- if GENERIC_AI.name in tools:
239
+ # Every way to fall short shows a tool helped, so "none" is not true.
240
+ fixed = _drop_lines(fixed, {d.line.strip() for d in report.says_none})
241
+ if needed and not rewritten:
242
+ appended = _append_stamp_disclosures(fixed, report, key)
243
+ if appended is None:
220
244
  return None
221
- for tool in tools:
222
- fixed = append_trailer(fixed, f"{key}: {tool}")
245
+ fixed = appended
223
246
  if fixed == message or not analyze(fixed, accepted, pattern).compliant:
224
247
  return None
225
248
  return fixed
249
+
250
+
251
+ def _drop_lines(message: str, lines: set[str]) -> str:
252
+ """*message* without the lines that are exactly one of *lines*.
253
+
254
+ A whole line, not a part of one: a body line that quotes a trailer
255
+ ("Write Assisted-by: none when ...") is the author's text and stays.
256
+ """
257
+ kept = [line for line in message.splitlines() if line.strip() not in lines]
258
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(kept)).strip()
259
+
260
+
261
+ def _append_stamp_disclosures(
262
+ message: str, report: AiPolicyReport, key: str
263
+ ) -> str | None:
264
+ """*message* with a disclosure for every tool only a vendor's mark names.
265
+
266
+ Nothing is rewritten then, and the disclosure is added. A mark that
267
+ names no particular tool gives nothing to write after the key.
268
+ """
269
+ tools = list(dict.fromkeys(s["tool"] for s in report.stamps))
270
+ if GENERIC_AI.name in tools:
271
+ return None
272
+ for tool in tools:
273
+ message = append_trailer(message, f"{key}: {tool}")
274
+ return message
@@ -21,6 +21,7 @@ from dataclasses import dataclass
21
21
  from functools import lru_cache
22
22
  from typing import TYPE_CHECKING
23
23
 
24
+ from commit_check import AI_DISCLOSURE_NONE
24
25
  from commit_check.ai_signatures_data import ALL_KNOWN_TOOLS as _ALL_KNOWN_TOOLS
25
26
  from commit_check.ai_signatures_data import GENERIC_AI, ROLE_CO_AUTHOR, ROLE_DISCLOSURE
26
27
 
@@ -207,6 +208,11 @@ def _split_trailer(line: str) -> tuple[str, str]:
207
208
  return key.strip(), value.strip()
208
209
 
209
210
 
211
+ def is_none_disclosure(value: str) -> bool:
212
+ """Whether a disclosure trailer's *value* says no AI tool helped."""
213
+ return value.strip().lower() == AI_DISCLOSURE_NONE
214
+
215
+
210
216
  def detect_ai_signatures(message: str) -> list[dict[str, str]]:
211
217
  """Scan *message* for known AI tool signatures.
212
218
 
@@ -235,6 +241,10 @@ def detect_ai_signatures(message: str) -> list[dict[str, str]]:
235
241
  if kind == "trailer":
236
242
  trailer, value = _split_trailer(matched)
237
243
  tool = tool_name
244
+ if role == ROLE_DISCLOSURE and is_none_disclosure(value):
245
+ # "Assisted-by: none" says no tool helped: it is a disclosure,
246
+ # not a sign of AI assistance.
247
+ continue
238
248
  if role == ROLE_DISCLOSURE and tool_name == GENERIC_AI.name:
239
249
  # The disclosure trailers are matched generically, on their
240
250
  # key alone; the value is where the tool is named.
@@ -104,6 +104,8 @@ class KnownAiTool:
104
104
 
105
105
  #: Trailers whose value credits a person who wrote part of the change.
106
106
  PERSON_TRAILERS = ("Co-authored-by", "Co-developed-by")
107
+ #: The same keys lowercased, to compare a trailer key against.
108
+ PERSON_TRAILER_KEYS = frozenset(key.lower() for key in PERSON_TRAILERS)
107
109
 
108
110
  #: Trailers that credit a person with some other part in the change: a
109
111
  #: review, a test, the idea for it. A tool named in one is a mark of its
commit_check/ci.py CHANGED
@@ -27,7 +27,10 @@ from dataclasses import dataclass
27
27
  from pathlib import Path
28
28
 
29
29
  from .config_merger import ConfigMerger
30
+ from .engine import ValidationContext, ValidationEngine, ValidationResult
30
31
  from .main import _VersionAction
32
+ from .rule_builder import RuleBuilder, ValidationRule
33
+ from .rules_catalog import RULES_BY_CHECK
31
34
 
32
35
  # Option name -> on by default. The names are the Action's input names.
33
36
  CHECKS: dict[str, bool] = {
@@ -226,6 +229,41 @@ def rebase_check_is_on() -> bool:
226
229
  return isinstance(branch, dict) and bool(branch.get("require_rebase_target"))
227
230
 
228
231
 
232
+ #: The description rules that turn the description check on by themselves.
233
+ #: CC501 waits for ``pr-body-ai-attribution``, as it did before them: without
234
+ #: it the description is checked with ``--ai-attribution ignore``, which
235
+ #: leaves the AI declaration out with the other AI rules.
236
+ DESCRIPTION_CHECKS = frozenset({"issue_reference", "description_min_length"})
237
+
238
+
239
+ def description_rules() -> list[ValidationRule] | None:
240
+ """The rules of :data:`DESCRIPTION_CHECKS` the config turns on.
241
+
242
+ None when the config cannot be read: the description is then checked
243
+ all the same, so commit-check says what is wrong with the config and
244
+ the job fails, where skipping it could let a job that checks nothing
245
+ else pass.
246
+ """
247
+ try:
248
+ config = ConfigMerger.from_all_sources(argparse.Namespace())
249
+ rules = RuleBuilder(config, []).build_all_rules()
250
+ except (OSError, ValueError):
251
+ return None
252
+ return [rule for rule in rules if rule.check in DESCRIPTION_CHECKS]
253
+
254
+
255
+ def unmet_rules(rules: list[ValidationRule], description: str) -> list[str]:
256
+ """The IDs of the *rules* that *description* does not meet."""
257
+ unmet = []
258
+ for rule in rules:
259
+ validator = ValidationEngine.VALIDATOR_MAP[rule.check](rule)
260
+ validator._suppress_output = True
261
+ result = validator.validate(ValidationContext(stdin_text=description))
262
+ if result == ValidationResult.FAIL:
263
+ unmet.append(RULES_BY_CHECK[rule.check].rule_id or rule.check)
264
+ return unmet
265
+
266
+
229
267
  def prepare_target(request: Request, env: Mapping[str, str]) -> None:
230
268
  """Make ``origin/<target>`` exist, which the rebase check (CC202) reads.
231
269
 
@@ -403,8 +441,9 @@ class Job:
403
441
  self.check_branch(request)
404
442
  if self.settings["pr-title"]:
405
443
  self.check_title(request)
406
- if self.settings["pr-body-ai-attribution"]:
407
- self.check_description(request)
444
+ rules = description_rules()
445
+ if self.settings["pr-body-ai-attribution"] or rules is None or rules:
446
+ self.check_description(request, rules or [])
408
447
  flags = [f"--{name}" for name in COMMIT_CHECKS if self.settings[name]]
409
448
  if flags:
410
449
  self.check_commits(request, flags)
@@ -430,20 +469,37 @@ class Job:
430
469
  return
431
470
  self.check(heading, ["--pr-title"], text=title + "\n")
432
471
 
433
- def check_description(self, request: Request) -> None:
472
+ def check_description(self, request: Request, rules: list[ValidationRule]) -> None:
434
473
  heading = f"{request.noun.capitalize()} description"
435
474
  try:
436
475
  description = self.request_text(request, "description")
437
476
  except Stop as error:
438
477
  self.stop(heading, error)
439
478
  return
479
+ args = ["--pr-body"]
440
480
  if self.env.get("CI_MERGE_REQUEST_DESCRIPTION_IS_TRUNCATED") == "true":
441
481
  print(
442
482
  f"Note: GitLab passed only the first {GITLAB_DESCRIPTION_LIMIT} "
443
483
  "characters of the description, so only that part is checked.",
444
484
  flush=True,
445
485
  )
446
- self.check(heading, ["--ai-attribution-only"], text=description + "\n")
486
+ unmet = unmet_rules(rules, description)
487
+ if unmet:
488
+ # The part GitLab left out may meet them: failing would
489
+ # reject a description that does. The rules it does meet
490
+ # would pass, so leaving them all out loses nothing.
491
+ print(
492
+ f"Note: that part does not meet {', '.join(unmet)}, and "
493
+ "the rest of the description may, so "
494
+ f"{'it is' if len(unmet) == 1 else 'they are'} not decided.",
495
+ flush=True,
496
+ )
497
+ args = ["--ai-attribution-only"]
498
+ if not self.settings["pr-body-ai-attribution"]:
499
+ # Only the description rules were asked for: the AI attribution
500
+ # rules and the AI declaration (CC501) stay off, as before.
501
+ args += ["--ai-attribution", "ignore"]
502
+ self.check(heading, args, text=description + "\n")
447
503
 
448
504
  def check_commits(self, request: Request, flags: list[str]) -> None:
449
505
  """Run the per-commit checks on every commit the request adds."""
@@ -129,12 +129,21 @@ _UNCHECKED_KEYS = frozenset({"warn", "jira"})
129
129
  #: Keys read from a table besides its defaults. In ``[commit]``,
130
130
  #: ``require_verified`` is read only by the GitHub App, which has GitHub's
131
131
  #: verdict on a commit's signature. ``[pull_request]`` has no defaults: the
132
- #: rule builder reads ``ai_declaration_checkboxes`` and the GitHub App the
133
- #: other three, so any other key in it is read by nothing.
132
+ #: rule builder reads ``ai_declaration_checkboxes``, ``require_issue_reference``,
133
+ #: ``issue_reference_pattern`` and ``description_min_length``, and the GitHub
134
+ #: App the other three, so any other key in it is read by nothing.
134
135
  _OTHER_SETTINGS: dict[str, frozenset[str]] = {
135
136
  "commit": frozenset({"require_verified"}),
136
137
  "pull_request": frozenset(
137
- {"check", "ai_label", "body_ai_attribution", "ai_declaration_checkboxes"}
138
+ {
139
+ "check",
140
+ "ai_label",
141
+ "body_ai_attribution",
142
+ "ai_declaration_checkboxes",
143
+ "require_issue_reference",
144
+ "issue_reference_pattern",
145
+ "description_min_length",
146
+ }
138
147
  ),
139
148
  }
140
149