Repository navigation
Expand file tree
/
Copy pathcommit_rules.py
More file actions
431 lines (370 loc) · 19.7 KB
/
Copy pathcommit_rules.py
File metadata and controls
431 lines (370 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# SPDX-FileCopyrightText: 2026 The RISE Project
# SPDX-License-Identifier: MIT
"""The measurable contribution rules a verified plan records, and their
deterministic checks.
The planner measures the project's commit conventions from its history
and records them as ``contribution_guidelines.commit_conventions.rules`` in
the plan (schema version 2 or later), and the required sections of the project's
pull request template as ``contribution_guidelines.pull_request_template``.
Trusted code applies them: the worker gate to every non-debug commit a
worker proposes, and the submission check to the reviewed series and the
reviewed pull request description. The series requirements of a plan of
schema version 4 (a path the series must change, such as a changelog entry)
are checked by the development observation on the exact head before
nomination, and by the worker gate on Work that carries one as feedback.
Only rules a machine can measure are here. Qualitative expectations (the
imperative mood, the scope of a change, a reviewer's style asks) are checked
by the model review at submission.
Nothing here runs a pattern from the plan: prefixes are compared as
literal strings, so a hostile plan cannot make a check slow.
"""
from __future__ import annotations
import email
import email.policy
import fnmatch
import re
import unicodedata
from typing import Any
from common import APP_COMMIT_EMAIL, APP_COMMIT_NAME, DEBUG_PREFIX
# The rules, their types, and their bounds.
RULE_KEYS = ("title_max_length", "title_prefixes", "title_prefix_required",
"title_capitalization", "title_trailing_period", "body_required",
"body_line_max_length", "signed_off_by_required", "max_commits")
CAPITALIZATION = ("upper", "lower", "any")
TRAILING_PERIOD = ("forbidden", "any")
MAX_PREFIXES = 20
MAX_SECTIONS = 30
_SIGNED_OFF = re.compile(r"^Signed-off-by: \S.* <[^<>\s]+@[^<>\s]+>$")
# An attribution trailer: any ``<token>-by:`` line (Signed-off-by,
# Co-authored-by, Reviewed-by, Acked-by, Tested-by, Reported-by,
# Suggested-by, and every other), matched on the line's lookalike-folded
# form (``_fold``): a key of any letters without white space that ends in
# ``-by``, then optional white space and a colon.
_ATTRIBUTION = re.compile(r"^\s*([^\s:]*-by)\s*:(.*)$")
# Characters folded to a hyphen or a colon before a line is matched, after
# NFKC (which already folds the fullwidth and small forms of most of them).
_HYPHENS = "\u2010\u2011\u2012\u2013\u2014\u2015\u2212\ufe58\ufe63\uff0d"
_COLONS = "\uff1a\ufe55\ufe13\u2236\ua789\u02d0\u02f8\u0589\u05c3\u1361\u1804\u205a\u2e2c"
_FOLD = str.maketrans({**{ch: "-" for ch in _HYPHENS}, **{ch: ":" for ch in _COLONS}})
APP_IDENTITY = f"{APP_COMMIT_NAME} <{APP_COMMIT_EMAIL}>"
_PATCH_PREFIX = re.compile(r"^\[PATCH[^\]]*\]\s*")
_DIFF_GIT = re.compile(r"diff --git a/(\S+) b/\S+")
_MBOX_FROM = re.compile(rb"^From [0-9a-f]{40} Mon Sep 17 00:00:00 2001$", re.M)
# An ATX heading opener; its text (the rest of the line, without a closing
# sequence of ``#`` and trailing white space) is cut in Python, so no pattern
# backtracks over a long line.
_HEADING = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]|$)")
class RuleError(ValueError):
"""The rules or the template sections a plan records are malformed."""
def _int(value: Any, low: int, high: int, name: str) -> int | None:
if value is None:
return None
if not isinstance(value, int) or isinstance(value, bool) or not low <= value <= high:
raise RuleError(f"{name} must be null or an integer in [{low}, {high}]")
return value
def _printable(value: Any, limit: int, name: str) -> str:
if not isinstance(value, str) or not value.strip() or len(value) > limit \
or any(ord(ch) < 32 or ord(ch) == 127 for ch in value):
raise RuleError(f"{name} must be a printable string of at most {limit} characters")
return value
def normalize(rules: Any) -> dict:
"""The rules with their types and bounds checked, every key present."""
if not isinstance(rules, dict):
raise RuleError("the commit rules must be an object")
unknown = sorted(set(rules) - set(RULE_KEYS))
if unknown:
raise RuleError(f"unknown commit rules {unknown}")
prefixes = rules.get("title_prefixes") or []
if not isinstance(prefixes, list) or len(prefixes) > MAX_PREFIXES:
raise RuleError(f"title_prefixes must be a list of at most {MAX_PREFIXES} prefixes")
prefixes = [_printable(p, 40, "a title prefix") for p in prefixes]
out = {
"title_max_length": _int(rules.get("title_max_length"), 20, 200, "title_max_length"),
"title_prefixes": prefixes,
"title_prefix_required": bool(rules.get("title_prefix_required", False)),
"title_capitalization": rules.get("title_capitalization", "any"),
"title_trailing_period": rules.get("title_trailing_period", "any"),
"body_required": bool(rules.get("body_required", False)),
"body_line_max_length": _int(rules.get("body_line_max_length"), 50, 200,
"body_line_max_length"),
"signed_off_by_required": bool(rules.get("signed_off_by_required", False)),
"max_commits": _int(rules.get("max_commits"), 1, 50, "max_commits"),
}
if out["title_capitalization"] not in CAPITALIZATION:
raise RuleError(f"title_capitalization must be one of {list(CAPITALIZATION)}")
if out["title_trailing_period"] not in TRAILING_PERIOD:
raise RuleError(f"title_trailing_period must be one of {list(TRAILING_PERIOD)}")
for key in ("title_prefix_required", "body_required", "signed_off_by_required"):
if not isinstance(rules.get(key, False), bool):
raise RuleError(f"{key} must be a boolean")
if out["title_prefix_required"] and not prefixes:
raise RuleError("title_prefix_required needs at least one title prefix")
return out
def normalize_sections(sections: Any) -> list[str]:
"""The required sections of a pull request template, checked."""
if not isinstance(sections, list) or len(sections) > MAX_SECTIONS:
raise RuleError(f"required_sections must be a list of at most {MAX_SECTIONS} headings")
return [_printable(s, 200, "a required section").strip() for s in sections]
def guidelines(plan: Any) -> dict | None:
"""The contribution guidelines of a plan, or ``None`` for a plan
written before they were part of the contract (schema version 1)."""
version = plan.get("schema_version") if isinstance(plan, dict) else None
if not isinstance(version, int) or isinstance(version, bool) or version < 2:
return None
value = plan.get("contribution_guidelines")
return value if isinstance(value, dict) else None
def from_plan(plan: Any) -> dict | None:
"""The measurable commit rules a plan records, or ``None`` when it
records none (a plan of schema version 1)."""
found = guidelines(plan)
if found is None:
return None
return normalize((found.get("commit_conventions") or {}).get("rules"))
def sections_from_plan(plan: Any) -> list[str] | None:
"""Every required section of every pull request template the plan
records, in order and without repeats; ``None`` for a plan of schema
version 1."""
found = guidelines(plan)
if found is None:
return None
template = found.get("pull_request_template") or {}
out: list[str] = []
for item in template.get("templates") or []:
for section in normalize_sections(item.get("required_sections") or []):
if section not in out:
out.append(section)
return out
# Bounds of the series requirements a plan records (schema version 4).
MAX_REQUIREMENTS = 6
MAX_REQUIREMENT_PATHS = 3
REQUIREMENT_ID = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
def series_requirements_from_plan(plan: Any) -> list[dict]:
"""The series requirements a plan records
(``contribution_guidelines.series_requirements``, schema version 4 or
later), each as ``{id, paths, description}``: the non-debug commits of
the series must change at least one file that matches one of ``paths``.
Empty for a plan of an earlier version or one that records none. Raises
``RuleError`` for a malformed value."""
version = plan.get("schema_version") if isinstance(plan, dict) else None
if not isinstance(version, int) or isinstance(version, bool) or version < 4:
return []
found = guidelines(plan) or {}
value = found.get("series_requirements")
if value is None:
return []
if not isinstance(value, list) or len(value) > MAX_REQUIREMENTS:
raise RuleError(f"series_requirements must be a list of at most {MAX_REQUIREMENTS} "
"requirements")
out: list[dict] = []
for item in value:
if not isinstance(item, dict):
raise RuleError("a series requirement must be an object")
rid = item.get("id")
if not isinstance(rid, str) or not REQUIREMENT_ID.match(rid) \
or any(rid == o["id"] for o in out):
raise RuleError("a series requirement needs a unique id of lower-case letters, "
"digits, and hyphens")
paths = item.get("paths")
if not isinstance(paths, list) or not 1 <= len(paths) <= MAX_REQUIREMENT_PATHS:
raise RuleError(f"series requirement {rid}: paths must list 1 to "
f"{MAX_REQUIREMENT_PATHS} paths")
out.append({"id": rid,
"paths": [_printable(p, 120, f"a path of series requirement {rid}")
for p in paths],
"description": _printable(item.get("description"), 300,
f"the description of series requirement {rid}")})
return out
def changed_paths_by_requirement(requirements: list[dict], paths: Any) -> tuple[list[str], list[dict]]:
"""Which ``requirements`` the changed ``paths`` meet: the ids met, and the
requirements unmet. A requirement is met when a changed path matches one
of its paths as ``fnmatch.fnmatchcase`` matches the scope."""
changed = [p for p in paths or () if isinstance(p, str)]
met, unmet = [], []
for item in requirements:
if any(fnmatch.fnmatchcase(path, pattern) for path in changed
for pattern in item["paths"]):
met.append(item["id"])
else:
unmet.append(item)
return met, unmet
def split_message(message: str) -> tuple[str, list[str]]:
"""The title and the body lines of a commit message."""
lines = str(message or "").replace("\r\n", "\n").rstrip("\n").split("\n")
title, body = lines[0], lines[1:]
while body and not body[0].strip():
body = body[1:]
return title, body
def is_debug(message: str) -> bool:
return split_message(message)[0].startswith(DEBUG_PREFIX)
def message_problems(message: str, rules: dict) -> list[str]:
"""Why one commit message breaks the rules; empty when it follows them."""
title, body = split_message(message)
shown = title if len(title) <= 80 else title[:77] + "..."
problems = []
limit = rules.get("title_max_length")
if limit is not None and len(title) > limit:
problems.append(f"the title {shown!r} has {len(title)} characters, more than {limit}")
rest = title
prefixes = rules.get("title_prefixes") or []
matched = next((p for p in sorted(prefixes, key=len, reverse=True) if title.startswith(p)), None)
if matched is not None:
rest = title[len(matched):].lstrip()
elif rules.get("title_prefix_required"):
problems.append(f"the title {shown!r} starts with none of the prefixes {prefixes}")
first = next((ch for ch in rest if ch.isalpha()), "")
case = rules.get("title_capitalization", "any")
if first and case == "upper" and not first.isupper():
problems.append(f"the title {shown!r} does not start with a capital letter")
if first and case == "lower" and not first.islower():
problems.append(f"the title {shown!r} does not start with a lower-case letter")
if rules.get("title_trailing_period") == "forbidden" and title.rstrip().endswith("."):
problems.append(f"the title {shown!r} ends with a period")
trailers = [line for line in body if _SIGNED_OFF.match(line.strip())]
text = [line for line in body if line.strip() and line not in trailers]
if rules.get("body_required") and not text:
problems.append(f"the commit {shown!r} has no body")
width = rules.get("body_line_max_length")
if width is not None:
long = [line for line in text if len(line) > width and " " in line.strip()
and "://" not in line]
if long:
problems.append(f"the commit {shown!r} has {len(long)} body line"
f"{'s' if len(long) != 1 else ''} longer than {width} characters")
if rules.get("signed_off_by_required") and not trailers:
problems.append(f"the commit {shown!r} has no Signed-off-by trailer")
return problems
def series_problems(messages: list[str], rules: dict | None, *,
count_commits: bool = True) -> list[str]:
"""Why a series of commit messages breaks the rules. ``{debug}`` commits
are development-only and are not checked; ``count_commits`` also checks
``max_commits`` against the other commits."""
if not rules:
return []
kept = [m for m in messages if not is_debug(m)]
problems = [p for m in kept for p in message_problems(m, rules)]
limit = rules.get("max_commits")
if count_commits and limit is not None and len(kept) > limit:
problems.append(f"the series has {len(kept)} commits, more than {limit}")
return problems
def _fold(line: str) -> str:
"""A line in the form attribution trailers are matched on: NFKC,
case-folded, with every hyphen-like character as ``-`` and every
colon-like character as ``:``."""
return unicodedata.normalize("NFKC", line).casefold().translate(_FOLD)
def _is_attribution(line: str) -> bool:
return bool(_ATTRIBUTION.match(_fold(line)))
def attribution_trailers(message: str) -> list[str]:
"""The attribution trailer lines of a commit message, exactly as written:
the title when it is one, and any line of its body."""
title, body = split_message(message)
return [line.rstrip("\r") for line in [title, *body] if _is_attribution(line)]
def _continued(message: str) -> list[str]:
"""The attribution trailers of a message that a white-space-led line
continues: ``git interpret-trailers`` folds that line into the trailer's
value, so it could name someone the trailer as written does not."""
_title, body = split_message(message)
return [line.rstrip("\r") for line, after in zip(body, body[1:])
if _is_attribution(line) and after[:1].isspace() and after.strip()]
def attribution_problems(messages: list[str], approved: list[str]) -> list[str]:
"""Why the attribution trailers of a series are not admitted. Each one
must name the App's commit identity, or be byte-identical to a trailer of
the ``approved`` commit messages: no commit attributes work to anyone the
approved series does not already name. A trailer is recognized under
Unicode lookalikes of its key and colon and as a title, and no trailer
may be continued on a white-space-led line."""
allowed = {t for m in approved for t in attribution_trailers(m)}
problems = []
for message in messages:
title = split_message(message)[0]
shown = title if len(title) <= 80 else title[:77] + "..."
for trailer in attribution_trailers(message):
raw = re.match(r"^\s*([A-Za-z0-9-]+-by)\s*:(.*)$", trailer, re.IGNORECASE)
value = raw.group(2).strip() if raw else None
if value == APP_IDENTITY or trailer in allowed:
continue
problems.append(f"the commit {shown!r} carries the attribution trailer "
f"{trailer[:200]!r}, which is neither the App's commit identity nor "
"a trailer of the approved commits")
for trailer in _continued(message):
problems.append(f"the commit {shown!r} continues the attribution trailer "
f"{trailer[:200]!r} on a line that starts with white space")
return problems
def mbox_starts(data: bytes) -> list[int]:
"""Where each message of a ``git format-patch`` mbox starts."""
return [m.start() for m in _MBOX_FROM.finditer(data or b"")]
def mbox_non_debug_paths(data: bytes) -> list[str]:
"""The paths the non-debug commits of a ``git format-patch`` mbox
change (``diff --git a/<path> b/<path>`` lines), in order and without
repeats. A ``{debug}`` commit is dropped at submission, so its paths
are not counted."""
starts = mbox_starts(data)
messages = mbox_messages(data)
out: list[str] = []
for i, start in enumerate(starts):
if is_debug(messages[i]):
continue
chunk = data[start: starts[i + 1] if i + 1 < len(starts) else len(data)]
for line in chunk.decode("utf-8", "replace").splitlines():
match = _DIFF_GIT.fullmatch(line)
if match and match.group(1) not in out:
out.append(match.group(1))
return out
def mbox_messages(data: bytes) -> list[str]:
"""The commit messages of a ``git format-patch`` mbox, in order: the
subject without its ``[PATCH ...]`` prefix, a blank line, and the body up
to the first ``---`` line, as ``git am`` reads them."""
starts = mbox_starts(data)
messages = []
for i, start in enumerate(starts):
chunk = data[start: starts[i + 1] if i + 1 < len(starts) else len(data)]
msg = email.message_from_bytes(chunk, policy=email.policy.default)
subject = _PATCH_PREFIX.sub("", " ".join(str(msg.get("Subject") or "").split()))
payload = msg.get_payload(decode=True) if not msg.is_multipart() else b""
charset = msg.get_content_charset() or "utf-8"
try:
text = (payload or b"").decode(charset, "replace")
except LookupError:
text = (payload or b"").decode("utf-8", "replace")
body = []
for line in text.replace("\r\n", "\n").split("\n"):
if line == "---":
break
body.append(line)
body_text = "\n".join(body).strip("\n")
messages.append(subject + ("\n\n" + body_text if body_text else ""))
return messages
def headings(markdown: str) -> list[str]:
"""The ATX headings of a Markdown text, normalized for comparison."""
found = []
fence = None
for line in str(markdown or "").split("\n"):
stripped = line.strip()
marker = stripped[:3]
if marker in ("```", "~~~"):
fence = None if fence == marker else (fence or marker)
continue
if fence:
continue
match = _HEADING.match(line)
if match:
found.append(_section_key(_heading_text(line[match.end():])))
return found
def _heading_text(rest: str) -> str:
"""The text of an ATX heading after its opener: without trailing white
space and an optional closing sequence of ``#`` preceded by white space."""
text = rest.strip(" \t")
stripped = text.rstrip("#")
if stripped != text and (not stripped or stripped[-1] in " \t"):
text = stripped.rstrip(" \t")
return text
def _section_key(text: str) -> str:
return " ".join(str(text).replace("*", "").replace("_", " ").split()).casefold()
def body_problems(body: str, sections: list[str] | None) -> list[str]:
"""The required template sections a pull request description lacks: a
required section is present when the description has a Markdown heading
with the same words (case and emphasis ignored)."""
if not sections:
return []
present = set(headings(body))
return [f"the description has no section {section!r} of the pull request template"
for section in sections if _section_key(section.lstrip("#").strip()) not in present]