Simpl-Resultat/scripts/review-levels.py
le king fu 628864937f fix(scripts): read comments by extension, lock origins by canonical form (#476)
meaningful() now depends on the file extension: in .rs, .ts, .tsx and .js
only a line that starts with // is a comment (// @ts- and /// <reference
stay code, and so do #[ and #!); in .toml, .yml and .sh a # line, except a
#! shebang; nothing in .json, .md or any other file. The old rule took any
# or // line of any file for a comment, so an attribute added to lib.rs
came out normal.

A lock origin is judged on its canonical form instead of its host: a
Cargo source other than the crates.io index, or an npm resolved other than
https://registry.npmjs.org/<name>/-/<short name>-<version>.tgz for the key
and version that package-lock.json gives at the PR head (read from the
API only when the diff adds a resolved line). A tarball of another package
on registry.npmjs.org, or another index on github.com, used to pass.

CONSENT_FILES adds the Feedback Hub consent (LogViewerCard.tsx,
FeedbackConsentDialog.tsx), and a fetchPrice( added outside
PriceFetchControl.tsx and the tests is high. is_test() replaces the
substring match on "test", which also skipped DownloadLatestButton.tsx.

PROBES take the hunks of a synthetic diff: one probe per "toujours"
pattern that no PR of #344-#452 exercises, an attribute and a comment
added to lib.rs, both lock origins and a canonical bump, both new consent
files, a new fetchPrice caller and a test that calls it. A lock probe's
hunk covers the whole file, its post-image being the lock at the head.
The docstring lists what the script does not model, and says that a PR's
level is read in REVIEW.md, never in its output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 21:51:27 -04:00

558 lines
26 KiB
Python
Executable file

#!/usr/bin/env python3
"""Replay the review levels of REVIEW.md on merged pull requests (#456).
Usage:
python3 scripts/review-levels.py [FIRST LAST] (default: 344 452)
python3 scripts/review-levels.py --check (no network)
The first form reads the Forgejo API (token in $FORGEJO_TOKEN, else
~/.forgejo-token; read-only calls) and prints each merged PR of the range
with its trial level (pilot document, section 4.3) and its REVIEW.md level,
then the distributions for the 39 reference PRs and for the whole range
(a set with no PR in the range is skipped).
--check compares the patterns of this script with the first column of the
Haut table of REVIEW.md, runs the offline PROBES (a path, the hunks of a
synthetic diff, the expected level), and exits 1 on any difference: a PR
that changes the Niveaux section updates this script in the same diff.
--check does not prove the conditions of the table: they stay with the
high-level review.
A PR's level is read in REVIEW.md, never in this script's output (neither
/pr-review, #457, nor the pilot, #458, runs it on an open PR): the content
conditions of the Haut table are only approximated from the diff.
- Comments, by file extension: a line that starts with // in .rs, .ts, .tsx
and .js (// @ts- and /// <reference stay code, like #[ and #!), with # in
.toml, .yml and .sh (a #! shebang stays code), none in .json, .md or any
other file. They and blank lines are skipped wherever the script reads
the changed lines, while REVIEW.md says "hors commentaires" for lib.rs
and the manifests only.
- lib.rs: only generate_handler![] entries are exempt, not the tests module.
- Tauri configuration and manifests: only a line that sets a version.
- Lock files: a package added or removed; an added source or resolved
outside its canonical form (the crates.io index; the npm tarball of the
key's name at the version that the lock read at the PR head gives that
key); a checksum or integrity added in a hunk that adds no version.
- Check workflows: a change that can turn a failing check green, read
against the PR's merge base; an env: block added at the workflow or job
level, or a run: step that deletes or edits a file (rm, sed -i), comes
out normal.
- Network calls: reqwest in Rust, fetch to an absolute URL in TS; an opened
URL is not seen.
- Consents: a changed line that says "consent" in CONSENT_FILES, and a
fetchPrice( added outside PriceFetchControl.tsx and the tests; a change
without the word, or a new path to FeedbackDialog, is not seen.
- Hooks and MCP servers: a file that .claude/settings.json or .mcp.json
makes the agents run is not detected.
"""
import itertools
import json
import os
import re
import sys
import urllib.request
API = "https://git.lacompagniemaximus.com/api/v1/repos/maximus/simpl-resultat"
REVIEW_MD = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "REVIEW.md")
# The 39 reference PRs of the pilot document, frozen by number: the listing
# that produced them (closed PRs, limit=40, sort=recentupdate) is not stable.
REF39 = [344, 375, 377, 378, 379, 380, 381, 382, 383, 386, 387, 388, 394, 402, 403,
407, 412, 413, 414, 415, 416, 417, 418, 420, 428, 433, 434, 435, 436, 438,
439, 440, 441, 442, 443, 444, 445, 448, 452]
TRIAL_HIGH = [
"src-tauri/src/commands/{auth_commands,token_store,license_commands,entitlements,account_cache,backup_commands,fs_commands,export_import_commands}.rs",
"src-tauri/src/lib.rs", "src-tauri/src/database/**", "src-tauri/tauri.conf.json",
"src-tauri/capabilities/**", ".forgejo/workflows/**", ".cargo/**", "src-tauri/Cargo.{toml,lock}",
"package.json", "package-lock.json",
"src/services/{authService,licenseService,db,feedbackService,dataExportService}.ts",
"src/services/entitlements*", "scripts/build-latest-json*",
]
TRIAL_LOW = ["**/*.md", "docs/**", "reports/**", "tasks/**", "public/CHANGELOG*", "LICENSE"]
# REVIEW.md, table Haut: rows without a condition.
HIGH_ALWAYS = [
"src-tauri/src/database/**",
"src-tauri/src/commands/profile_commands.rs",
"src-tauri/src/commands/{license_commands,entitlements,auth_commands,token_store,account_cache}.rs",
"src/services/{licenseService,authService}.ts",
".claude/skills/issue-license/**",
"src-tauri/src/commands/export_import_commands.rs",
"src-tauri/src/commands/feedback_commands.rs", "src/services/feedbackService.ts",
"src-tauri/capabilities/**",
".forgejo/workflows/release.yml", "scripts/build-latest-json*", "scripts/check-latest-json.jq",
".claude/skills/release/scripts/**",
"src-tauri/build.rs", "{vite,vitest,postcss}.config.*", ".postcssrc*", ".npmrc", "**/rust-toolchain*",
"Cargo.{toml,lock}",
"**/.cargo/**",
".claude/settings.json", ".mcp.json",
]
# REVIEW.md, row "code livré": the price consent, then the Feedback Hub one
# (openFeedback of LogViewerCard.tsx, the only path to FeedbackDialog).
CONSENT_FILES = {"src/components/balance/PriceFetchControl.tsx",
"src/components/settings/PriceFetchConsentToggle.tsx",
"src/components/settings/LogViewerCard.tsx",
"src/components/settings/FeedbackConsentDialog.tsx"}
# The one caller of prices.fetchPrice, behind the price consent.
PRICE_CALLER = "src/components/balance/PriceFetchControl.tsx"
CRATES_IO = "registry+https://github.com/rust-lang/crates.io-index"
# Comment syntax by extension (REVIEW.md, "commentaire"); any other: none.
SLASH_COMMENT = (".rs", ".ts", ".tsx", ".js")
HASH_COMMENT = (".toml", ".yml", ".sh")
TAURI_CONFIG = ["src-tauri/{tauri*.conf.json*,Tauri*.toml}"]
CHECK_WORKFLOWS = {".forgejo/workflows/check-rust.yml", ".forgejo/workflows/check-frontend.yml"}
SHIPPED = ["src/**", "src-tauri/src/**", "index.html", "public/**"]
LOW = ["**/*.md", "docs/**", "LICENSE", "tasks/**", "reports/**"]
NEVER_LOW = ["CLAUDE.md", "REVIEW.md", "docs/adr/**", "docs/architecture.md", "docs/qa-update-cycle.md", ".claude/**"]
def token():
return os.environ.get("FORGEJO_TOKEN") or open(os.path.expanduser("~/.forgejo-token")).read().strip()
def get(path, raw=False):
req = urllib.request.Request(API + path, headers={"Authorization": "token " + token()})
data = urllib.request.urlopen(req).read()
return data if raw else json.loads(data)
def raw_file(path, ref):
return get(f"/raw/{path}?ref={ref}", raw=True).decode()
def expand_braces(pat):
m = re.search(r"\{([^{}]*)\}", pat)
if not m:
return [pat]
return list(itertools.chain.from_iterable(
expand_braces(pat[:m.start()] + alt + pat[m.end():]) for alt in m.group(1).split(",")))
def glob_re(pat):
# '**/' spans zero or more directories, '*' and '?' never cross '/'
i, out = 0, ""
while i < len(pat):
if pat.startswith("**/", i):
out += "(?:.*/)?"; i += 3; continue
if pat.startswith("**", i):
out += ".*"; i += 2; continue
c = pat[i]
out += "[^/]*" if c == "*" else "[^/]" if c == "?" else re.escape(c)
i += 1
return re.compile("^" + out + "$")
def match(pats, path):
# '{a,b}' alternates, wildcards allowed inside
return any(glob_re(p).match(path) for pat in pats for p in expand_braces(pat))
def file_blocks(diff):
out = {}
for block in re.split(r"(?m)^diff --git ", diff)[1:]:
out[block.split("\n", 1)[0].split(" b/")[-1]] = block
return out
def meaningful(text, path):
"""False for a blank line and for a comment, by the extension of path."""
t = text.strip()
if t == "":
return False
if path.endswith(SLASH_COMMENT):
# compiler directives are code, and so are #[...] and #! (no //)
return not t.startswith("//") or re.match(r"//+\s*@ts-|///\s*<reference", t) is not None
if path.endswith(HASH_COMMENT):
return not t.startswith("#") or t.startswith("#!")
return True
def changed(block, path):
return [l for l in block.split("\n")
if l[:1] in "+-" and not l.startswith(("+++", "---")) and meaningful(l[1:], path)]
def is_test(path):
return re.search(r"\.test\.[cm]?[jt]sx?$", path) is not None or path.startswith("src/test/")
def npm_canonical(key, version):
# the name follows the key's last node_modules/; a scoped tarball drops the scope
name = key.rsplit("node_modules/", 1)[-1]
return f"https://registry.npmjs.org/{name}/-/{name.split('/')[-1]}-{version}.tgz"
def off_canonical(cargo, added, head):
"""The added source or resolved values outside the canonical form of their package."""
if cargo:
return [s for s in added if s != CRATES_IO]
try:
packages = json.loads(head())["packages"]
except (ValueError, KeyError, TypeError):
return added # a lock that cannot be read at the head: the condition counts as met
out = []
for url in added:
keys = [k for k, v in packages.items() if isinstance(v, dict) and v.get("resolved") == url]
if not keys or any(url != npm_canonical(k, packages[k].get("version")) for k in keys):
out.append(url)
return out
def lock_adds_or_removes(name, block, head):
"""head() returns the lock at the PR head, read only when an origin line is added."""
cargo = name.endswith("Cargo.lock")
lines = block.split("\n")
if cargo and any(re.match(r'^[+-]name = ', l) for l in lines):
return True
if not cargo and any(re.match(r'^[+-]\s+"node_modules/[^"]+": \{', l) for l in lines):
return True
# an origin outside the canonical form, with or without a new version
source = r'^\+source = "([^"]+)"' if cargo else r'^\+\s+"resolved": "([^"]+)"'
added = [m.group(1) for m in (re.match(source, l) for l in lines) if m]
if added and off_canonical(cargo, added, head):
return True
# a checksum or integrity that changes without a new version
digest = r'^\+checksum = ' if cargo else r'^\+\s+"integrity": '
version = r'^\+version = ' if cargo else r'^\+\s+"version": '
for hunk in re.split(r"(?m)^@@", block)[1:]:
hl = hunk.split("\n")
if any(re.match(digest, l) for l in hl) and not any(re.match(version, l) for l in hl):
return True
return False
STEP = re.compile(r"^\s*- (name|uses):")
VERDICT = re.compile(r"npm ci|npm run build|npm test|cargo check|cargo test|cargo audit|cargo-audit|Verify", re.I)
def regions(base):
lines = base.split("\n")
region, top, job_key = {}, None, None
for i, l in enumerate(lines, 1):
m = re.match(r"^([A-Za-z_][\w-]*):", l)
if m:
top = m.group(1)
m = re.match(r"^ ([A-Za-z_][\w-]*):", l)
if m:
job_key = m.group(1)
elif re.match(r"^\S", l) or re.match(r"^ \S", l):
job_key = None
if top in ("on", "true"):
region[i] = "on"
elif top == "permissions" or job_key in ("env", "container", "permissions"):
region[i] = "jobcfg"
else:
region[i] = "other"
starts = [i for i, l in enumerate(lines, 1) if STEP.match(l)]
for k, s in enumerate(starts):
e = starts[k + 1] - 1 if k + 1 < len(starts) else len(lines)
if VERDICT.search("\n".join(lines[s - 1:e])):
for i in range(s, e + 1):
if region[i] == "other":
region[i] = "verdict"
return region, lines
def weakening(path, block, base):
"""Ways a check-workflow diff could turn a failing check green (empty = none)."""
region, lines = regions(base)
reasons, old, plus = set(), 0, []
def flush(pos):
texts = [p[1:] for p in plus]
active = [t for t in texts if meaningful(t, path)] # comments never count
if any(re.search(r"continue-on-error|\|\|\s*true", t) for t in active):
reasons.add("continue-on-error or || true added")
if any(re.search(r"GITHUB_ENV|GITHUB_PATH|npm pkg set|git checkout|git restore", t) for t in active):
reasons.add("writes the job environment or the repository")
if any(re.search(r"^\s*(- )?uses:", t) and not re.search(r"Swatinem/rust-cache|actions/cache", t) for t in active):
reasons.add("action added (not a cache)")
if any(re.search(r"rustup|toolchain|\bPATH\b|/bin/", t) for t in active):
reasons.add("install step changes the toolchain or the PATH")
if any(re.match(r"^(\s{4})?(if|defaults):", t) for t in active):
reasons.add("job-level if/defaults changed")
first = next((t for t in texts if meaningful(t, path)), None)
if first is None or STEP.match(first):
return
prev, nxt = region.get(pos - 1, "other"), region.get(pos, "other")
if "on" in (prev, nxt):
if any(re.search(r"branches|paths-ignore", t) for t in active):
reasons.add("trigger narrowed")
j = pos - 1
while j > 0 and not re.match(r"^\s*[\w-]+:", lines[j - 1]):
j -= 1
if j > 0 and "paths-ignore" in lines[j - 1] and any(re.match(r"^\s*- ", t) for t in active):
reasons.add("paths-ignore entry added")
elif prev == nxt == "verdict":
reasons.add("verdict step modified")
elif "jobcfg" in (prev, nxt):
reasons.add("job env/container/permissions modified")
for line in block.split("\n"):
m = re.match(r"^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@", line)
if m:
flush(old); plus = []
old = int(m.group(1)); continue
if line.startswith("+") and not line.startswith("+++"):
plus.append(line); continue
flush(old); plus = []
if line.startswith("-") and not line.startswith("---"):
if meaningful(line[1:], path):
if re.match(r"^(\s{4})?(if|defaults):", line[1:]):
reasons.add("job-level if/defaults changed")
if re.search(r"rustup|toolchain|\bPATH\b|/bin/", line[1:]):
reasons.add("install step changes the toolchain or the PATH")
r = region.get(old, "other")
if r == "on":
reasons.add("trigger removed or changed")
elif r == "verdict":
reasons.add("verdict step modified or removed")
elif r == "jobcfg":
reasons.add("job env/container/permissions modified")
old += 1
elif line.startswith(" "):
old += 1
flush(old)
return sorted(reasons)
def adds_network_call(path, block):
if not match(SHIPPED, path) or is_test(path):
return False
for l in block.split("\n"):
if l.startswith("+") and not l.startswith("+++"):
if path.endswith(".rs") and "reqwest" in l:
return True
if re.search(r"\.(ts|tsx)$", path) and re.search(r"fetch\(\s*[`'\"]https?://", l):
return True
return False
def trial_level(paths):
if any(match(TRIAL_HIGH, p) for p in paths):
return "haut"
return "bas" if all(match(TRIAL_LOW, p) for p in paths) else "normal"
def review_level(number, files, diff, merge_base, head, read=raw_file):
"""read(path, ref) returns a file at the merge base or at the PR head."""
blocks = file_blocks(diff)
triggers = []
for f in files:
b = blocks.get(f["filename"], "")
for path in filter(None, {f["filename"], f.get("previous_filename")}):
if match(HIGH_ALWAYS, path):
triggers.append(path)
elif path == "src-tauri/src/lib.rs":
if [l for l in changed(b, path) if not re.match(r"^[+-]\s*commands::\w+,?\s*$", l)]:
triggers.append(path)
elif path == "src-tauri/src/commands/balance_commands.rs":
hunks = re.split(r"(?m)^(?=@@)", b)[1:]
if any(re.search(r"fetch_price|activation", h.split("\n")[0]) or
any(re.search(r"fetch_price|activation", l) for l in changed(h, path)) for h in hunks):
triggers.append(path)
elif match(TAURI_CONFIG, path) or path in ("src-tauri/Cargo.toml", "package.json"):
if [l for l in changed(b, path) if not re.match(r'^[+-]\s*"?version"?\s*[:=]', l)]:
triggers.append(path)
elif path in ("src-tauri/Cargo.lock", "package-lock.json"):
if lock_adds_or_removes(path, b, lambda: read(path, head)):
triggers.append(path)
elif path == ".forgejo/workflows/audit.yml" and changed(b, path):
triggers.append(path)
elif path in CHECK_WORKFLOWS:
if weakening(path, b, read(path, merge_base)):
triggers.append(path)
elif path.startswith(".forgejo/workflows/") and f["status"] == "added":
triggers.append(path + " (new workflow)")
elif path == "REVIEW.md":
triggers.append(path + " (check the « Niveaux » section by hand)")
if adds_network_call(path, b):
triggers.append(path + " (network call)")
added = [l for l in b.split("\n") if l.startswith("+") and not l.startswith("+++")]
if path.startswith(".forgejo/workflows/") and any(re.search(r"\bsecrets\b|pull_request_target", l) for l in added):
triggers.append(path + " (secrets or pull_request_target added)")
if path in CONSENT_FILES and any(re.search(r"consent", l, re.I) for l in changed(b, path)):
triggers.append(path + " (consent)")
if (match(SHIPPED, path) and not is_test(path) and path != PRICE_CALLER and any(
l.startswith("+") and re.search(r"\bfetchPrice\(", l) for l in changed(b, path))):
triggers.append(path + " (fetchPrice caller)")
parts = path.split("/")
top_level = len(parts) == 1 or (parts[0] == "src-tauri" and len(parts) == 2)
new_hidden = f["status"] == "added" and any(
x.startswith(".") for x in parts[:-1]) and parts[0] not in (".forgejo", ".claude", ".cargo", ".github")
# Forgejo reports an edited file as "changed"
if (f["status"] not in ("changed", "modified") and top_level and not path.endswith(".md")) or new_hidden:
triggers.append(path + " (" + f["status"] + " at top level)")
paths = [f["filename"] for f in files]
if triggers:
return "haut", sorted(set(triggers))
if all(match(LOW, p) and not match(NEVER_LOW, p) for p in paths):
return "bas", []
return "normal", []
CONDITIONAL = {
"src-tauri/src/lib.rs", "src-tauri/src/commands/balance_commands.rs",
"src-tauri/Cargo.toml", "package.json", "src-tauri/Cargo.lock", "package-lock.json",
".forgejo/workflows/**", ".forgejo/workflows/audit.yml",
".forgejo/workflows/{check-rust,check-frontend}.yml", "REVIEW.md",
}
# A lock probe's one hunk covers the whole file: its post-image is the lock
# that the script reads at the PR head.
NPM_OFF_CANONICAL = """@@ -1,10 +1,10 @@
{
"lockfileVersion": 3,
"packages": {
"node_modules/foo": {
- "version": "1.2.3",
- "resolved": "https://registry.npmjs.org/foo/-/foo-1.2.3.tgz",
- "integrity": "sha512-b2xk"
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/evil-foo/-/evil-foo-1.2.4.tgz",
+ "integrity": "sha512-ZXZp"
}
}
}"""
NPM_CANONICAL_BUMP = """@@ -1,10 +1,10 @@
{
"lockfileVersion": 3,
"packages": {
"node_modules/foo/node_modules/@scope/bar": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/@scope/bar/-/bar-2.0.0.tgz",
- "integrity": "sha512-b2xk"
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/@scope/bar/-/bar-2.0.1.tgz",
+ "integrity": "sha512-ZXZp"
}
}
}"""
CARGO_OFF_INDEX = '''@@ -1,5 +1,5 @@
[[package]]
name = "foo"
version = "1.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
+source = "registry+https://github.com/evil/crates.io-index"
checksum = "e3b0c442"'''
# Offline probes run by --check: a path, the hunks of its diff (None: an empty
# diff) and the expected level. A typo shared by the Haut table and the script
# passes the pattern comparison, and the replay sees it only when a PR of the
# range has that pattern for its only high trigger (review of #498, mutation
# M4). Hence one probe per "toujours" pattern that no PR of #344-#452
# exercises, the two of the Release row, and one per rule of this script that
# the range does not exercise either (#476).
PROBES = [
(".claude/skills/release/scripts/verify-release.sh", None, "haut"),
(".claude/skills/release/SKILL.md", None, "normal"),
(".claude/skills/issue-license/SKILL.md", None, "haut"),
("src-tauri/src/commands/export_import_commands.rs", None, "haut"),
("src-tauri/src/commands/feedback_commands.rs", None, "haut"),
("src/services/feedbackService.ts", None, "haut"),
("src-tauri/capabilities/default.json", None, "haut"),
("src-tauri/build.rs", None, "haut"),
("vite.config.ts", None, "haut"),
(".postcssrc.json", None, "haut"),
(".npmrc", None, "haut"),
("src-tauri/rust-toolchain.toml", None, "haut"),
("Cargo.toml", None, "haut"),
(".cargo/audit.toml", None, "haut"),
(".claude/settings.json", None, "haut"),
(".mcp.json", None, "haut"),
# an attribute is code, a // line a comment
("src-tauri/src/lib.rs", '@@ -1 +1,2 @@\n+#[cfg(feature = "dev-override")]\n pub fn run() {', "haut"),
("src-tauri/src/lib.rs", "@@ -1 +1,2 @@\n+// Builds the app.\n pub fn run() {", "normal"),
("package-lock.json", NPM_OFF_CANONICAL, "haut"),
("package-lock.json", NPM_CANONICAL_BUMP, "normal"),
("src-tauri/Cargo.lock", CARGO_OFF_INDEX, "haut"),
("src/components/settings/LogViewerCard.tsx",
'@@ -21 +21 @@\n- const accepted = localStorage.getItem(FEEDBACK_CONSENT_KEY) === "true";\n'
"+ const accepted = true;", "haut"),
("src/components/settings/FeedbackConsentDialog.tsx",
'@@ -47 +47 @@\n- <p>{t("feedback.consent.body")}</p>\n+ <p>{t("feedback.consent.short")}</p>', "haut"),
("src/components/balance/SnapshotLineRow.tsx",
'@@ -1 +1,2 @@\n import { prices } from "../../services/balance.service";\n'
'+void prices.fetchPrice(symbol, date);', "haut"),
("src/services/balance.service.test.ts",
'@@ -1 +1,2 @@\n import { prices } from "./balance.service";\n'
'+const result = await prices.fetchPrice("AAPL", "2026-04-25");', "normal"),
]
def image(hunks, post):
"""The post-image (at the head) or the pre-image (at the base) of a probe's hunks."""
keep = "+" if post else "-"
return "\n".join(l[1:] for l in (hunks or "").split("\n") if l[:1] in (" ", keep))
def check():
"""Compare this script's patterns with the first column of the Haut table, then run PROBES."""
text = open(REVIEW_MD, encoding="utf-8").read()
table = text.split("### Haut", 1)[1].split("\n\n", 2)[1]
documented = set()
for row in table.split("\n"):
if not row.startswith("| ") or row.startswith("| Motif") or row.startswith("| fichier à la racine"):
continue
documented.update(re.findall(r"`([^`]+)`", row.split(" | ")[0]))
coded = set(HIGH_ALWAYS) | set(TAURI_CONFIG) | set(SHIPPED) | CONDITIONAL
for label, extra in (("REVIEW.md only", documented - coded), ("script only", coded - documented)):
for pattern in sorted(extra):
print(f"{label}: {pattern}")
failed = documented != coded
for path, hunks, want in PROBES:
diff = f"diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n{hunks}\n" if hunks else ""
got = review_level(0, [{"filename": path, "status": "changed"}], diff, "base", "head",
lambda p, ref, h=hunks: image(h, ref == "head"))[0]
if got != want:
print(f"probe: {path} is {got}, expected {want}")
failed = True
if failed:
return 1
print(f"ok: {len(coded)} patterns, identical to the Haut table of REVIEW.md; {len(PROBES)} probes")
return 0
def main():
if sys.argv[1:] == ["--check"]:
sys.exit(check())
first, last = (int(sys.argv[1]), int(sys.argv[2])) if len(sys.argv) == 3 else (344, 452)
merged, page = [], 1
while True:
batch = get(f"/pulls?state=closed&limit=50&page={page}")
if not batch:
break
merged += [p for p in batch if p.get("merged") and first <= p["number"] <= last]
page += 1
merged.sort(key=lambda p: p["number"])
rows = []
for p in merged:
n = p["number"]
files, fpage = [], 1
while True:
# the instance caps a page at 50 items: read until an empty page
fb = get(f"/pulls/{n}/files?limit=50&page={fpage}")
if not fb:
break
files += fb
fpage += 1
diff = get(f"/pulls/{n}.diff", raw=True).decode("utf-8", "replace")
pr = get(f"/pulls/{n}")
trial = trial_level([f["filename"] for f in files])
level, triggers = review_level(n, files, diff, pr["merge_base"], pr["head"]["sha"])
rows.append((n, trial, level, triggers))
print(f"#{n}\t{'ref' if n in REF39 else ' '}\t{trial}\t{level}\t{'; '.join(triggers)}")
for label, keep in (("39 reference PRs", lambda n: n in REF39), (f"{len(rows)} PRs #{first}-#{last}", lambda n: True)):
sel = [r for r in rows if keep(r[0])]
if not sel:
# a range that holds none of them, such as "491 491"
print(f"{label}: none in this range")
continue
for col, name in ((1, "trial"), (2, "REVIEW.md")):
counts = {lvl: sum(1 for r in sel if r[col] == lvl) for lvl in ("bas", "normal", "haut")}
share = 100 * counts["haut"] / len(sel)
print(f"{label}, {name}: {counts} -> haut {share:.1f} %")
if __name__ == "__main__":
main()