diff --git a/scripts/auto_fetch.py b/scripts/auto_fetch.py index 2b3d25f2b..9f21c26a7 100644 --- a/scripts/auto_fetch.py +++ b/scripts/auto_fetch.py @@ -243,6 +243,7 @@ def step2_scan_branches(entry: dict) -> bytes | None: ["git", "ls-tree", "-r", "--name-only", ref], capture_output=True, text=True, + check=False, ) for filepath in result.stdout.strip().split("\n"): diff --git a/scripts/autorun.py b/scripts/autorun.py index 9935aebae..9404cb82f 100644 --- a/scripts/autorun.py +++ b/scripts/autorun.py @@ -587,11 +587,10 @@ def sync_worktree(worktree: Path) -> str: ahead = int(git(worktree, "rev-list", "--count", f"{upstream}..HEAD").stdout) if ahead == 0: git(worktree, "merge", "--ff-only", "--quiet", upstream) - elif git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", - check=False).returncode != 0: - if git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0: - git(worktree, "rebase", "--abort", check=False) - raise AutorunError(BLOCKED, f"{ahead} automation commits conflict with {upstream}") + elif (git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode != 0 + and git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0): + git(worktree, "rebase", "--abort", check=False) + raise AutorunError(BLOCKED, f"{ahead} automation commits conflict with {upstream}") return git(worktree, "rev-parse", upstream).stdout.strip() @@ -608,11 +607,10 @@ def push_batch(worktree: Path, gate_base: str, regate: Callable[[], bool]) -> st upstream = f"{REMOTE}/{TARGET}" if int(git(worktree, "rev-list", "--count", f"{upstream}..HEAD").stdout) == 0: return "" - if git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", - check=False).returncode != 0: - if git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0: - git(worktree, "rebase", "--abort", check=False) - raise AutorunError(BLOCKED, f"rebase onto {upstream} conflicts, batch kept") + if (git(worktree, "merge-base", "--is-ancestor", upstream, "HEAD", check=False).returncode != 0 + and git(worktree, "rebase", "--quiet", upstream, check=False).returncode != 0): + git(worktree, "rebase", "--abort", check=False) + raise AutorunError(BLOCKED, f"rebase onto {upstream} conflicts, batch kept") if git(worktree, "rev-parse", upstream).stdout.strip() != gate_base and not regate(): raise AutorunError(FAILED, f"gate failed on the batch rebased onto {upstream}") git(worktree, "push", "--quiet", REMOTE, f"HEAD:{TARGET}", env=token_env()) diff --git a/scripts/campaign.py b/scripts/campaign.py index 1021aee9f..c5fcd642b 100644 --- a/scripts/campaign.py +++ b/scripts/campaign.py @@ -64,6 +64,7 @@ import argparse import contextlib import datetime as dt import hashlib +import http.client import io import json import os @@ -82,6 +83,10 @@ import zipfile from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass, field from pathlib import Path +from typing import IO, TYPE_CHECKING, TypedDict, TypeVar + +if TYPE_CHECKING: + from typing_extensions import Unpack sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -95,6 +100,9 @@ import autorun import campaign_profiles import campaign_rules as rules import measurement_records as mr +from autorun import now_iso + +T = TypeVar("T") ROOT = Path(__file__).resolve().parent.parent CONTENT_FILE = ROOT / "tests" / "campaign" / "content.yml" @@ -134,10 +142,6 @@ class Unavailable(RuntimeError): # Small helpers # -------------------------------------------------------------------------- -def now_iso() -> str: - return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat() - - def slug(text: str) -> str: return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "x" @@ -213,8 +217,18 @@ def is_bios(entry: dict) -> bool: # Host # -------------------------------------------------------------------------- +class PopenOptions(TypedDict, total=False): + """The Popen arguments the campaign passes through run_group.""" + + cwd: str | Path + env: dict[str, str] + text: bool + stdout: int | IO[str] | IO[bytes] + stderr: int | IO[str] | IO[bytes] + + def run_group(argv: Sequence[str], *, timeout: float | None = None, check: bool = False, - capture_output: bool = False, **kwargs: object) -> subprocess.CompletedProcess: + capture_output: bool = False, **kwargs: Unpack[PopenOptions]) -> subprocess.CompletedProcess: """subprocess.run in a process group of its own, the whole group killed on a timeout or an interruption: a hung core never outlives its run.""" if capture_output: @@ -245,7 +259,7 @@ class Host: free_gb: Callable[[Path], float] = autorun.free_gb poll: float = 60.0 run: Callable[..., subprocess.CompletedProcess] = run_group - urlopen: Callable[..., object] = urllib.request.urlopen + urlopen: Callable[..., http.client.HTTPResponse] = urllib.request.urlopen @property def max_load(self) -> float: @@ -413,11 +427,11 @@ def export_commit(mirror: Callable[[str], Path], url: str, commit: str, dest: Pa except subprocess.CalledProcessError: git_out("-C", str(bare), "fetch", "--quiet", repo_url, sha) extract_tar(git_out("-C", str(bare), "archive", "--format=tar", sha), target) - links = {} + links: dict[str, str] = {} for entry in git_out("-C", str(bare), "ls-tree", "-r", "-z", sha).split(b"\0"): if entry.startswith(b"160000 commit "): - meta, path = entry.split(b"\t", 1) - links[path.decode()] = meta.split()[2].decode() + meta, raw_path = entry.split(b"\t", 1) + links[raw_path.decode()] = meta.split()[2].decode() if not links: return try: @@ -739,7 +753,7 @@ class Cores: self.c = campaign self.listing: set[str] | None = None - def retrying(self, what: str, call: Callable[[], object]) -> object: + def retrying(self, what: str, call: Callable[[], T]) -> T: for attempt, delay in enumerate((*self.c.settings.delays, None)): try: return call() @@ -896,6 +910,28 @@ class Unit: buildbot_only: bool = False +@dataclass(frozen=True) +class Trial: + """One core on one content: what every check of that pairing shares.""" + + unit: Unit + core: Core + content: Content + load: Path + frames: list[str] + digest: str + + +@dataclass(frozen=True) +class Held: + """A declared file the collection holds, at its place.""" + + index: int + entry: dict + dest: str + local: Path + + @dataclass class Pass: started: str @@ -1168,12 +1204,7 @@ class Campaign: if local and entry_dest(entry) not in staged: staged[entry_dest(entry)] = (index, entry, local) tested = {dest: item for dest, item in staged.items() if region_matches(item[1], content.region)} - keys = {"files": self.check_key(core, content, "files"), - "none": self.check_key(core, content, "none")} - for dest in tested: - keys[f"negative:{dest}"] = self.check_key(core, content, f"negative:{dest}") - if self.settings.bench: - keys["bench"] = self.check_key(core, content, "bench") + keys = self.content_keys(core, content, tested) # The rules run on every pass, from the records kept when nothing # needs to run again: a change of the table applies without a run. try: @@ -1185,73 +1216,103 @@ class Campaign: self.pending(emulator, key, str(exc), digest) return frames = ["--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every)] - repeat = ["--repeat", str(self.settings.check_repeat)] - stem = f"{core.name}-{slug(content.name)}" - - # files: every declared file the collection holds, at its place. - argv = self.probe_args("run", core, emulator, slug(f"files-{stem}"), content, load) + frames + repeat - for dest, (_, _, local) in sorted(staged.items()): - argv += ["--system-file", f"{dest}={local}"] - files_record = self.check(emulator, keys["files"], core, digest, argv, f"{emulator}-{stem}-files") - # none: no BIOS at all. - argv = self.probe_args("run", core, emulator, slug(f"none-{stem}"), content, load) + frames + repeat - none_record = self.check(emulator, keys["none"], core, digest, argv, f"{emulator}-{stem}-none") - if not files_record or not none_record: + trial = Trial(unit, core, content, load, frames, digest) + records = self.reference_runs(trial, keys, staged) + if not records: return + files_record, none_record = records full = rules.run_of(files_record, files_record["variants"][0]["label"]) none = rules.run_of(none_record, none_record["variants"][0]["label"]) self.log(f"{emulator}: {core.name} on {content.name}: full set {full.verdict}, " f"no BIOS {none.verdict}") for dest, (index, entry, local) in sorted(tested.items()): - record = self.negative(unit, core, content, load, frames, digest, keys[f"negative:{dest}"], - dest, entry, local, staged) - if not record: - continue - labels = [v["label"] for v in record["variants"]] - present = rules.run_of(record, labels[0]) - zeros, half = (rules.run_of(record, label) for label in labels[1:3]) - for label in labels[3:]: - self.log(f"{emulator}: {rules.rule_region(rules.run_of(record, label), present, entry, content.region)}") - if dest in self.opened(files_record, 0) or dest in self.opened(record, 0): - verdicts = rules.rule_need(none, present, entry, rules.read(none, present, zeros, half)) - validation = rules.rule_validation(zeros, half, none, present, entry) - if validation: - verdicts.append(validation) - self.settle(emulator, content, core, index, entry, verdicts) - variants = self.variant_files(entry, local) - if variants: - self.run_variants(unit, core, content, load, frames, digest, index, entry, dest, - local, variants) - else: - self.moved(unit, core, content, load, frames, digest, index, entry, dest, local, - files_record, record) + self.test_entry(trial, keys[f"negative:{dest}"], Held(index, entry, dest, local), staged, + files_record, none) boot = self.boot_entry(entries, content) if boot and entry_dest(boot[1]) in tested: index, entry = boot - self.follow_aliases(unit, core, content, load, frames, digest, index, entry, - tested[entry_dest(entry)][2], none_record) + self.follow_aliases(trial, index, entry, tested[entry_dest(entry)][2], none_record) if self.settings.bench and full.verdict == rules.BOOTS: - argv = self.probe_args("bench", core, emulator, slug(f"bench-{stem}"), content, load) - argv += ["--warmup", str(self.settings.bench_warmup), "--frames", - str(self.settings.bench_frames), "--repeat", str(self.settings.bench_repeat), - "--no-trace"] - if boot: - argv += ["--system-file", f"{entry_dest(boot[1])}={self.local_file(boot[1])}"] - self.check(emulator, keys["bench"], core, digest, argv, f"{emulator}-{stem}-bench") + self.bench(trial, keys["bench"], boot) - def negative(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str], - digest: str, key: str, dest: str, entry: dict, local: Path, + def content_keys(self, core: Core, content: Content, + tested: dict[str, tuple[int, dict, Path]]) -> dict[str, str]: + keys = {"files": self.check_key(core, content, "files"), + "none": self.check_key(core, content, "none")} + for dest in tested: + keys[f"negative:{dest}"] = self.check_key(core, content, f"negative:{dest}") + if self.settings.bench: + keys["bench"] = self.check_key(core, content, "bench") + return keys + + def reference_runs(self, trial: Trial, keys: dict[str, str], + staged: dict[str, tuple[int, dict, Path]]) -> tuple[dict, dict] | None: + """The full set and no BIOS at all, or None while either is missing.""" + core, emulator, content, load = trial.core, trial.unit.emulator, trial.content, trial.load + repeat = ["--repeat", str(self.settings.check_repeat)] + stem = f"{core.name}-{slug(content.name)}" + + # files: every declared file the collection holds, at its place. + argv = self.probe_args("run", core, emulator, slug(f"files-{stem}"), content, load) + trial.frames + repeat + for dest, (_, _, local) in sorted(staged.items()): + argv += ["--system-file", f"{dest}={local}"] + files_record = self.check(emulator, keys["files"], core, trial.digest, argv, f"{emulator}-{stem}-files") + # none: no BIOS at all. + argv = self.probe_args("run", core, emulator, slug(f"none-{stem}"), content, load) + trial.frames + repeat + none_record = self.check(emulator, keys["none"], core, trial.digest, argv, f"{emulator}-{stem}-none") + if not files_record or not none_record: + return None + return files_record, none_record + + def test_entry(self, trial: Trial, key: str, held: Held, staged: dict[str, tuple[int, dict, Path]], + files_record: dict, none: rules.Run) -> None: + """One declared file alone and replaced, then what its runs settle.""" + emulator, content, entry = trial.unit.emulator, trial.content, held.entry + record = self.negative(trial, key, held, staged) + if not record: + return + labels = [v["label"] for v in record["variants"]] + present = rules.run_of(record, labels[0]) + zeros, half = (rules.run_of(record, label) for label in labels[1:3]) + for label in labels[3:]: + self.log(f"{emulator}: {rules.rule_region(rules.run_of(record, label), present, entry, content.region)}") + if held.dest in self.opened(files_record, 0) or held.dest in self.opened(record, 0): + verdicts = rules.rule_need(none, present, entry, rules.read(none, present, zeros, half)) + validation = rules.rule_validation(zeros, half, none, present, entry) + if validation: + verdicts.append(validation) + self.settle(emulator, content, trial.core, held.index, entry, verdicts) + variants = self.variant_files(entry, held.local) + if variants: + self.run_variants(trial, held, variants) + else: + self.moved(trial, held, files_record, record) + + def bench(self, trial: Trial, key: str, boot: tuple[int, dict] | None) -> None: + core, emulator, content = trial.core, trial.unit.emulator, trial.content + stem = f"{core.name}-{slug(content.name)}" + argv = self.probe_args("bench", core, emulator, slug(f"bench-{stem}"), content, trial.load) + argv += ["--warmup", str(self.settings.bench_warmup), "--frames", + str(self.settings.bench_frames), "--repeat", str(self.settings.bench_repeat), + "--no-trace"] + if boot: + argv += ["--system-file", f"{entry_dest(boot[1])}={self.local_file(boot[1])}"] + self.check(emulator, key, core, trial.digest, argv, f"{emulator}-{stem}-bench") + + def negative(self, trial: Trial, key: str, held: Held, staged: dict[str, tuple[int, dict, Path]]) -> dict | None: """The file alone, then wrong files under its name: zeros of its size, its first half, and other regions' dumps.""" + core, content, entry, dest, local = trial.core, trial.content, held.entry, held.dest, held.local + unit = trial.unit stem = f"{core.name}-{slug(content.name)}" size = local.stat().st_size others = self.other_regions(entry, staged, local) argv = self.probe_args("check", core, unit.emulator, slug(f"negative-{entry['name']}-{stem}"), - content, load) + frames + content, trial.load) + trial.frames argv += ["--vary", f"{dest}={local}", "--vary", f"{dest}=@zeros:{size}", "--vary", f"{dest}=@head:{size // 2}:{local}"] for other in others: @@ -1266,20 +1327,19 @@ class Campaign: f"{content.frames} frames with no button pressed, every " f"{content.frame_hash_every}th frame hashed. The boot oracle judges " f"each variant against the reference frames of {content.name}.")] - return self.check(unit.emulator, key, core, digest, argv, f"{unit.emulator}-{stem}-negative") + return self.check(unit.emulator, key, core, trial.digest, argv, f"{unit.emulator}-{stem}-negative") - def moved(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str], - digest: str, index: int, entry: dict, dest: str, local: Path, files_record: dict, - alone: dict) -> None: + def moved(self, trial: Trial, held: Held, files_record: dict, alone: dict) -> None: """A file the core opened neither in the full set nor alone: where else it looked for a file of that name, else flagged.""" + unit, core, content = trial.unit, trial.core, trial.content + index, entry, dest = held.index, held.entry, held.dest probed = [p for record in (files_record, alone) for r in record["variants"][0]["repetitions"] for p in r.get("files_probed_absent") or ()] others = [p for p in dict.fromkeys(probed) if p != dest and p.rsplit("/", 1)[-1].casefold() == dest.rsplit("/", 1)[-1].casefold()] for candidate in others[:MAX_ALIAS_CANDIDATES]: - found = self.follow_up(unit, core, content, load, frames, digest, entry, local, candidate, - f"path:{entry['name']}:{candidate}") + found = self.follow_up(trial, entry, held.local, candidate, f"path:{entry['name']}:{candidate}") if found and candidate in self.opened(found, 0): verdict = rules.rule_path(entry, dest, rules.Opened(candidate, found["id"])) if verdict: @@ -1308,7 +1368,7 @@ class Campaign: def judged(self, emulator: str, rid: str) -> bool: """True for a record the boot oracle judged: only those prove a field.""" record = self.read_record(emulator, rid) - return bool(record) and record.get("record_version", 0) >= 4 + return record is not None and record.get("record_version", 0) >= 4 @staticmethod def opened(record: dict, position: int) -> set[str]: @@ -1317,18 +1377,18 @@ class Campaign: out |= {item["path"] for item in rep.get("files_opened") or ()} return out - def follow_up(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str], - digest: str, entry: dict, local: Path, dest: str, check: str) -> dict | None: + def follow_up(self, trial: Trial, entry: dict, local: Path, dest: str, check: str) -> dict | None: """The file staged at dest alone: does the core open it there.""" + unit, core, content = trial.unit, trial.core, trial.content stem = f"{core.name}-{slug(content.name)}" - argv = self.probe_args("run", core, unit.emulator, slug(f"{check}-{stem}"), content, load) - argv += frames + ["--system-file", f"{dest}={local}"] - return self.check(unit.emulator, self.check_key(core, content, check), core, digest, argv, + argv = self.probe_args("run", core, unit.emulator, slug(f"{check}-{stem}"), content, trial.load) + argv += trial.frames + ["--system-file", f"{dest}={local}"] + return self.check(unit.emulator, self.check_key(core, content, check), core, trial.digest, argv, f"{unit.emulator}-{stem}-{slug(check)}") - def follow_aliases(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str], - digest: str, index: int, entry: dict, local: Path, none_record: dict) -> None: + def follow_aliases(self, trial: Trial, index: int, entry: dict, local: Path, none_record: dict) -> None: """Names the core looked for, with no BIOS, that no entry declares.""" + unit, core, content = trial.unit, trial.core, trial.content declared = {e["name"] for e in unit.profile.get("files") or ()} declared |= {a for e in unit.profile.get("files") or () for a in e.get("aliases") or ()} suffix = Path(entry["name"]).suffix.casefold() @@ -1343,23 +1403,23 @@ class Campaign: and path not in probed): probed.append(path) for candidate in probed[:MAX_ALIAS_CANDIDATES]: - found = self.follow_up(unit, core, content, load, frames, digest, entry, local, candidate, + found = self.follow_up(trial, entry, local, candidate, f"alias:{entry['name']}:{candidate.rsplit('/', 1)[-1]}") if found and candidate in self.opened(found, 0): verdict = rules.rule_alias(self.reload_entry(unit, index), rules.Opened(candidate, found["id"])) if verdict: self.settle(unit.emulator, content, core, index, self.reload_entry(unit, index), [verdict]) - def run_variants(self, unit: Unit, core: Core, content: Content, load: Path, frames: list[str], - digest: str, index: int, entry: dict, dest: str, primary: Path, - variants: list[Path]) -> None: + def run_variants(self, trial: Trial, held: Held, variants: list[Path]) -> None: + unit, core, content, digest = trial.unit, trial.core, trial.content, trial.digest + index, entry, dest = held.index, held.entry, held.dest key = self.check_key(core, content, f"variants:{entry['name']}") if not self.needed(unit.emulator, key, core, digest): return stem = f"{core.name}-{slug(content.name)}" argv = self.probe_args("check", core, unit.emulator, slug(f"variants-{entry['name']}-{stem}"), - content, load) + frames - for path in [primary, *variants]: + content, trial.load) + trial.frames + for path in [held.local, *variants]: argv += ["--vary", f"{dest}={path}"] argv += ["--observable", "frame_hashes", "--repeat", str(self.settings.check_repeat), "--claim", f"every copy of {entry['name']} boots {content.name} on {core.name}", @@ -1508,7 +1568,7 @@ class Campaign: argv += ["--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every), "--repeat", str(self.settings.check_repeat), "--png-dir", str(target)] - for index, entry in self.system_entries(unit.profile, content.system): + for _, entry in self.system_entries(unit.profile, content.system): local = self.local_file(entry) if local and f"{entry_dest(entry)}=" not in " ".join(argv): argv += ["--system-file", f"{entry_dest(entry)}={local}"] @@ -1821,10 +1881,9 @@ def render_status(report: dict) -> str: counts = report["counts"] lines.append(f"{counts.get(DONE, 0)} done, {counts.get(FAILED, 0)} failed, " f"{counts.get(PENDING, 0)} pending") - for reason, number in sorted(report["pending_reasons"].items(), key=lambda kv: -kv[1]): - lines.append(f" pending {number:5} {reason}") - for item in report["failed"]: - lines.append(f" FAILED {item['emulator']} {item['check']}: {item['reason']}") + lines.extend(f" pending {number:5} {reason}" + for reason, number in sorted(report["pending_reasons"].items(), key=lambda kv: -kv[1])) + lines.extend(f" FAILED {item['emulator']} {item['check']}: {item['reason']}" for item in report["failed"]) for emulator, checks in report["emulators"].items(): ran = [k for k, v in checks.items() if v["status"] != PENDING] if ran: @@ -1894,7 +1953,7 @@ def review_finding(root: Path, key: str, status: str, reason: str, # Command line # -------------------------------------------------------------------------- -def main(argv: Sequence[str] | None = None) -> int: +def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter) sub = parser.add_subparsers(dest="command", required=True) @@ -1942,44 +2001,72 @@ def main(argv: Sequence[str] | None = None) -> int: help="with --status applied, a field to write into the entry") review_p.add_argument("--index", type=int, help="the entry's position when several share its name") sub.add_parser("gate", help="tests, schemas, verify and pack of the changed profiles") + return parser + + +def _review(parser: argparse.ArgumentParser, args: argparse.Namespace, paths: Paths) -> int: + updates: dict[str, object] = {} + for item in args.set: + name, sep, value = item.partition("=") + if not sep or not name: + parser.error(f"--set {item!r}: FIELD=YAML") + updates[name] = yaml.safe_load(value) + try: + line = review_finding(paths.root, args.key, args.status, args.reason, updates, + args.index) + except (ValueError, campaign_profiles.ProfileEditError) as exc: + print(f"campaign: {exc}", file=sys.stderr) + return 1 + print(f"{line['status']} {line['key']} [{line['id']}]") + return 0 + + +def _findings(args: argparse.Namespace, paths: Paths) -> int: + lines = open_findings(paths.root, args.all) + if args.json: + print(json.dumps(lines, indent=2)) + for line in [] if args.json else lines: + print(f"{line['status']:8} {line['key']}: profile says {json.dumps(line['profile_says'])}, " + f"run shows {json.dumps(line['run_shows'])}. {line['statement']} " + f"[{', '.join(line['evidence'])}]") + return 0 + + +def _settings(args: argparse.Namespace) -> Settings: + if args.command == "run": + return Settings(budget=args.budget, max_load_wait=args.max_load_wait, + min_free_gb=args.min_free_gb, cache_cap_gb=args.cache_cap_gb, + romfetch=args.romfetch, network=not args.offline, + allow_unsandboxed=args.allow_unsandboxed, bench=args.bench) + if args.command == "references": + return Settings(romfetch=args.romfetch, network=not args.offline, + allow_unsandboxed=args.allow_unsandboxed) + return Settings() + + +def _references(campaign: Campaign, args: argparse.Namespace, only: set[str]) -> int: + try: + with host_lock(campaign.lock_path): + listed = campaign.references(only, args.system, Path(args.png_dir)) + except autorun.LockBusy as exc: + print(f"campaign: deferred, {exc}", file=sys.stderr) + return 75 + print(json.dumps(listed, indent=2)) + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = _parser() args = parser.parse_args(argv) paths = Paths.default() if args.command == "gate": return gate(paths.root, changed_profiles(paths.root)) if args.command == "review": - updates: dict[str, object] = {} - for item in args.set: - name, sep, value = item.partition("=") - if not sep or not name: - parser.error(f"--set {item!r}: FIELD=YAML") - updates[name] = yaml.safe_load(value) - try: - line = review_finding(paths.root, args.key, args.status, args.reason, updates, - args.index) - except (ValueError, campaign_profiles.ProfileEditError) as exc: - print(f"campaign: {exc}", file=sys.stderr) - return 1 - print(f"{line['status']} {line['key']} [{line['id']}]") - return 0 + return _review(parser, args, paths) if args.command == "findings": - lines = open_findings(paths.root, args.all) - if args.json: - print(json.dumps(lines, indent=2)) - for line in [] if args.json else lines: - print(f"{line['status']:8} {line['key']}: profile says {json.dumps(line['profile_says'])}, " - f"run shows {json.dumps(line['run_shows'])}. {line['statement']} " - f"[{', '.join(line['evidence'])}]") - return 0 - settings = Settings() - if args.command == "run": - settings = Settings(budget=args.budget, max_load_wait=args.max_load_wait, - min_free_gb=args.min_free_gb, cache_cap_gb=args.cache_cap_gb, - romfetch=args.romfetch, network=not args.offline, - allow_unsandboxed=args.allow_unsandboxed, bench=args.bench) - elif args.command == "references": - settings = Settings(romfetch=args.romfetch, network=not args.offline, - allow_unsandboxed=args.allow_unsandboxed) + return _findings(args, paths) + settings = _settings(args) if args.command in ("run", "references"): paths.content_file = Path(args.content_file) campaign = Campaign(paths, settings) @@ -1989,17 +2076,14 @@ def main(argv: Sequence[str] | None = None) -> int: return 0 only = {item.strip() for item in args.only.split(",") if item.strip()} if args.command == "references": - try: - with host_lock(campaign.lock_path): - listed = campaign.references(only, args.system, Path(args.png_dir)) - except autorun.LockBusy as exc: - print(f"campaign: deferred, {exc}", file=sys.stderr) - return 75 - print(json.dumps(listed, indent=2)) - return 0 + return _references(campaign, args, only) if args.dry_run: campaign.run(only, args.system, dry_run=True) return 0 + return _run_pass(campaign, args, only, paths) + + +def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], paths: Paths) -> int: campaign.dirty_at_start = set(autorun.changed_files(paths.root)) if args.commit else set() def stop(signum: int, frame: object) -> None: diff --git a/scripts/campaign_profiles.py b/scripts/campaign_profiles.py index d935076b1..535d0149c 100644 --- a/scripts/campaign_profiles.py +++ b/scripts/campaign_profiles.py @@ -95,11 +95,11 @@ def key_lines(lines: list[str], first: int, stop: int, key_indent: int) -> dict[ match = KEY.match(line) if match and len(match["indent"]) == key_indent: order.append((match["key"], i)) - for position, (key, line) in enumerate(order): + for position, (key, start) in enumerate(order): end = order[position + 1][1] if position + 1 < len(order) else stop - while end > line + 1 and (not lines[end - 1].strip() or lines[end - 1].strip().startswith("#")): + while end > start + 1 and (not lines[end - 1].strip() or lines[end - 1].strip().startswith("#")): end -= 1 - keys[key] = (line, end) + keys[key] = (start, end) return keys diff --git a/scripts/campaign_rules.py b/scripts/campaign_rules.py index fdd2a9f49..00bf4ebb5 100644 --- a/scripts/campaign_rules.py +++ b/scripts/campaign_rules.py @@ -40,7 +40,7 @@ Standard library only. from __future__ import annotations -from collections.abc import Iterable, Sequence +from collections.abc import Callable, Iterable, Sequence from dataclasses import dataclass, field BOOTS = "boots" @@ -122,7 +122,8 @@ def current(entry: dict, name: str) -> object: def agrees(entry: dict, verdict: Verdict) -> bool: """True when the profile already says what the run showed.""" if verdict.field == "aliases": - return set(verdict.value or ()) <= set(entry.get("aliases") or ()) + shown = verdict.value if isinstance(verdict.value, (list, tuple)) else () + return set(shown) <= set(entry.get("aliases") or ()) if verdict.field == "validation": return verdict.rule == "validation_agrees" return current(entry, verdict.field) == verdict.value @@ -211,7 +212,8 @@ def rule_validation(zeros: Run | None, half: Run | None, none: Run, present: Run entry: dict) -> Verdict | None: """Same-size and short wrong files against the right one: validation.""" name = entry["name"] - content = {REFUSED: True, USED: False}.get(file_use(zeros, none, present)) if zeros else None + zeros_use = file_use(zeros, none, present) if zeros else None + content = {REFUSED: True, USED: False}.get(zeros_use) if zeros_use else None half_use = file_use(half, none, present) if half else None size: bool | None = None if half_use == USED: @@ -297,7 +299,7 @@ def rule_variants(runs: Iterable[Run], entry: dict) -> Verdict | None: def merge_evidence(existing: dict | None, verdict: Verdict, - keep: object = lambda rid: True) -> dict: + keep: Callable[[str], bool] = lambda rid: True) -> dict: """The entry's evidence: map with the verdict's record ids added under its field. An id `keep` refuses is dropped from that field: a record from before the oracle no longer proves anything.""" diff --git a/scripts/check_buildbot_system.py b/scripts/check_buildbot_system.py index d630bafbc..c6bada126 100644 --- a/scripts/check_buildbot_system.py +++ b/scripts/check_buildbot_system.py @@ -102,10 +102,7 @@ def check(registry_path: str = DEFAULT_REGISTRY) -> dict: buildbot_set = set(index_zips) tracked_set = set(tracked.keys()) - results: list[dict] = [] - - for z in sorted(buildbot_set - tracked_set): - results.append({"zip": z, "status": "NEW", "key": None}) + results: list[dict] = [{"zip": z, "status": "NEW", "key": None} for z in sorted(buildbot_set - tracked_set)] for z in sorted(tracked_set - buildbot_set): key, _ = tracked[z] diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index dd44d4cc7..3048a7755 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -40,7 +40,7 @@ import subprocess import sys import tempfile import urllib.request -from collections.abc import Iterator +from collections.abc import Container, Iterator from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, dataclass, field from datetime import datetime, timezone @@ -585,7 +585,7 @@ def _platform_overrides(overrides: dict, platform: str) -> dict: def unresolved_target_cores( - targets: dict, index: dict[str, str], overrides: dict + targets: dict, index: Container[str], overrides: dict ) -> dict[str, list[str]]: """Core names a target ends up with that no profile claims. @@ -618,7 +618,7 @@ def check_targets( ) -> list[Finding]: targets_dir = platforms_dir / "targets" overrides_path = targets_dir / "_overrides.yml" - overrides = {} + overrides: dict = {} if overrides_path.is_file(): with overrides_path.open(encoding="utf-8") as fh: overrides = yaml_load(fh) or {} @@ -1380,7 +1380,7 @@ def specifier_allows(spec: str, version: str) -> bool: for clause in filter(None, (c.strip() for c in spec.split(","))): match = _SPEC_CLAUSE.fullmatch(clause) test = _SPEC_TESTS.get(match.group(1)) if match else None - if test is None or not test(target, _version_tuple(match.group(2))): + if match is None or test is None or not test(target, _version_tuple(match.group(2))): return False return True diff --git a/scripts/check_platform_folder.py b/scripts/check_platform_folder.py index e26fba238..ce13028c6 100644 --- a/scripts/check_platform_folder.py +++ b/scripts/check_platform_folder.py @@ -23,14 +23,14 @@ def accepts(entry: dict, path: Path, mode: str) -> bool: with zipfile.ZipFile(path) as archive: names = {name.casefold(): name for name in archive.namelist()} member = names.get(entry["zipped_file"].casefold()) - return bool(member) and hashlib.new(digest, archive.read(member)).hexdigest() in values + return member is not None and hashlib.new(digest, archive.read(member)).hexdigest() in values actual = hashlib.new(digest, path.read_bytes()).hexdigest() if entry.get("zip_digest") != "composite" and actual in values: return True # whole digests, as batocera-systems:1088 compares them if digest == DIGESTS["md5"] and path.suffix.lower() == ".zip": # Recalbox: members in name order with zipfile.ZipFile(path) as archive: - names = sorted(name for name in archive.namelist() if not name.endswith("/")) - return hashlib.md5(b"".join(map(archive.read, names))).hexdigest() in values + members = sorted(name for name in archive.namelist() if not name.endswith("/")) + return hashlib.md5(b"".join(map(archive.read, members))).hexdigest() in values except (OSError, zipfile.BadZipFile): return False return False @@ -60,7 +60,7 @@ if __name__ == "__main__": except urllib.request.HTTPError as error: # a 404: no platform has that name with urllib.request.urlopen(API.replace("platforms/", "catalog.json")) as response: known = sorted(i["url"][10:-5] for i in json.load(response)["items"] if i["url"].startswith("manifests/")) - sys.exit(f"unknown platform: {sys.argv[1]}. Known: {', '.join(known)}" if error.code == 404 else error) + sys.exit(f"unknown platform: {sys.argv[1]}. Known: {', '.join(known)}" if error.code == 404 else str(error)) except OSError as error: # no such folder, or no network (URLError) sys.exit(f"error: {error}") for verdict in ("ok", "wrong", "missing"): diff --git a/scripts/check_release.py b/scripts/check_release.py index 41b422336..6859f7ee4 100644 --- a/scripts/check_release.py +++ b/scripts/check_release.py @@ -65,6 +65,18 @@ def parse_sums(text: str) -> dict[str, str]: return sums +def _registry_findings(packs: dict, released: set[str]) -> list[Finding]: + """Each platform marked release_pack has a pack, and each pack serves one.""" + served = {p for pack in packs.values() for p in pack.get("platforms", ())} + findings = [Finding("no-pack", platform, "release_pack: true, no pack in release.json") + for platform in sorted(released - served)] + findings.extend(Finding( + "not-released", pack_name, + "serves no platform marked release_pack in platforms/_registry.yml", + ) for pack_name, pack in sorted(packs.items()) if not set(pack.get("platforms", ())) & released) + return findings + + def compare_release( record: dict, sums: dict[str, str], @@ -84,18 +96,7 @@ def compare_release( if record.get("tag") != tag: findings.append(Finding("tag", tag, f"release.json records {record.get('tag')}")) if released is not None: - packs = record.get("packs", {}) - served = {p for pack in packs.values() for p in pack.get("platforms", ())} - for platform in sorted(released - served): - findings.append(Finding( - "no-pack", platform, "release_pack: true, no pack in release.json" - )) - for pack_name, pack in sorted(packs.items()): - if not set(pack.get("platforms", ())) & released: - findings.append(Finding( - "not-released", pack_name, - "serves no platform marked release_pack in platforms/_registry.yml", - )) + findings += _registry_findings(record.get("packs", {}), released) recorded = { name: pack_name @@ -105,14 +106,14 @@ def compare_release( expected = set(recorded) | set(sums) | {SUMS} | set(local_files or ()) allowed = expected | {SIGNATURE} - for name in sorted(expected - set(assets)): - findings.append(Finding("missing", name, "not attached to the release")) - for name in sorted(set(assets) - allowed): - findings.append(Finding("extra", name, "attached but neither recorded nor listed")) - for name in sorted(set(recorded) - set(sums)): - findings.append(Finding("unlisted", name, f"absent from {SUMS}")) - for name in sorted(set(sums) - set(recorded)): - findings.append(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json")) + findings.extend(Finding("missing", name, "not attached to the release") + for name in sorted(expected - set(assets))) + findings.extend(Finding("extra", name, "attached but neither recorded nor listed") + for name in sorted(set(assets) - allowed)) + findings.extend(Finding("unlisted", name, f"absent from {SUMS}") + for name in sorted(set(recorded) - set(sums))) + findings.extend(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json") + for name in sorted(set(sums) - set(recorded))) wanted = {**sums, **(local_files or {})} for name, digest in sorted(wanted.items()): diff --git a/scripts/check_release_assets.py b/scripts/check_release_assets.py index 069bf1ef3..e130f4a89 100644 --- a/scripts/check_release_assets.py +++ b/scripts/check_release_assets.py @@ -90,10 +90,11 @@ def compare( served = next( (name for name in _spellings(names[path]) if name in assets), None ) - published = assets[served] if served else None - if published is None: + if not served: findings.append(AssetFinding("missing", path, size, None)) - elif published != size: + continue + published = assets[served] + if published != size: findings.append(AssetFinding("size", path, size, published)) else: ours = (expected_digests or {}).get(path) diff --git a/scripts/cleanup_disk.py b/scripts/cleanup_disk.py index 1e13da6b4..e2afcce13 100644 --- a/scripts/cleanup_disk.py +++ b/scripts/cleanup_disk.py @@ -29,6 +29,7 @@ Usage: from __future__ import annotations import argparse +import contextlib import os import re import shutil @@ -81,10 +82,8 @@ def busy_paths() -> set[str]: if not pid.name.isdigit(): continue links = [pid / "cwd"] - try: + with contextlib.suppress(OSError): links += list((pid / "fd").iterdir()) - except OSError: - pass for link in links: try: found.add(os.readlink(link)) diff --git a/scripts/core_probe.py b/scripts/core_probe.py index e7a9dfb1b..64c1dea6c 100644 --- a/scripts/core_probe.py +++ b/scripts/core_probe.py @@ -36,9 +36,10 @@ import sys import tempfile import time import zlib -from collections.abc import Iterable, Iterator, Sequence +from collections.abc import Callable, Iterable, Iterator, Sequence from dataclasses import dataclass, field from pathlib import Path +from typing import IO # The probe tools do not import common.py, which states the 3.9 floor for the # other scripts. Under 3.8 they stopped on a str.removesuffix AttributeError. @@ -396,7 +397,7 @@ InputFn = ctypes.CFUNCTYPE(ctypes.c_int16, ctypes.c_uint, ctypes.c_uint, ctypes. class Frontend: """The libretro callbacks for one run.""" - def __init__(self, spec: dict) -> None: + def __init__(self, spec: dict, events: IO[str] | None = None) -> None: self.spec = spec self.system_dir = spec["system_dir"].encode() self.save_dir = spec["save_dir"].encode() @@ -417,10 +418,19 @@ class Frontend: self.unanswered: dict[int, int] = {} self.input_queries = 0 self.input_pressed = 0 - # What a run showed so far, one JSON line per event, flushed at once: - # a core that kills the worker leaves its logs and frames behind. - events = spec.get("events") - self.events = open(events, "a", encoding="utf-8", buffering=1) if events else None # noqa: SIM115 + self.events = events + self.env_handlers: dict[int, Callable[[int, int], bool]] = { + ENV_GET_CAN_DUPE: self.env_can_dupe, + ENV_GET_SYSTEM_DIRECTORY: self.env_directory, + ENV_GET_SAVE_DIRECTORY: self.env_directory, + ENV_SET_PIXEL_FORMAT: self.env_pixel_format, + ENV_SET_VARIABLES: self.env_set_variables, + ENV_GET_VARIABLE: self.env_get_variable, + ENV_GET_VARIABLE_UPDATE: self.env_variable_update, + ENV_SET_SUPPORT_NO_GAME: lambda cmd, data: True, + ENV_GET_LOG_INTERFACE: self.env_log_interface, + ENV_GET_CORE_OPTIONS_VERSION: self.env_core_options_version, + } self.callbacks = ( EnvFn(self.environment), VideoFn(self.video_refresh), AudioFn(self.audio_sample), AudioBatchFn(self.audio_batch), PollFn(lambda: None), InputFn(self.input_state), @@ -439,54 +449,63 @@ class Frontend: def environment(self, cmd: int, data: int) -> bool: cmd &= ~ENV_EXPERIMENTAL - if cmd == ENV_GET_CAN_DUPE: - ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = True - return True - if cmd in (ENV_GET_SYSTEM_DIRECTORY, ENV_GET_SAVE_DIRECTORY): - value = self.system_dir if cmd == ENV_GET_SYSTEM_DIRECTORY else self.save_dir - buffer = ctypes.create_string_buffer(value) - self.option_buffers.append(buffer) - ctypes.cast(data, ctypes.POINTER(ctypes.c_char_p))[0] = ctypes.cast(buffer, ctypes.c_char_p) - return True - if cmd == ENV_SET_PIXEL_FORMAT: - fmt = ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[0] - if fmt not in PIXEL_BYTES: - return False - self.pixel_format = fmt - return True - if cmd == ENV_SET_VARIABLES: - array = ctypes.cast(data, ctypes.POINTER(RetroVariable)) - index = 0 - while array[index].key: - key, desc = array[index].key, (array[index].value or b"").decode("utf-8", "replace") - values = desc.split(";", 1)[-1].strip().split("|") - self.declared[key.decode()] = values - self.defaults[key] = values[0].encode() - index += 1 - return True - if cmd == ENV_GET_VARIABLE: - var = ctypes.cast(data, ctypes.POINTER(RetroVariable))[0] - value = self.options.get(var.key, self.defaults.get(var.key)) - if value is None: - return False - buffer = ctypes.create_string_buffer(value) - self.option_buffers.append(buffer) - ctypes.cast(data, ctypes.POINTER(RetroVariable))[0].value = ctypes.cast(buffer, ctypes.c_char_p) - return True - if cmd == ENV_GET_VARIABLE_UPDATE: - ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = False - return True - if cmd == ENV_SET_SUPPORT_NO_GAME: - return True - if cmd == ENV_GET_LOG_INTERFACE: - ctypes.cast(data, ctypes.POINTER(RetroLogCallback))[0] = self.log_callback - return True - if cmd == ENV_GET_CORE_OPTIONS_VERSION: - ctypes.cast(data, ctypes.POINTER(ctypes.c_uint))[0] = 0 - return True + handler = self.env_handlers.get(cmd) + if handler: + return handler(cmd, data) self.unanswered[cmd] = self.unanswered.get(cmd, 0) + 1 return False + def env_can_dupe(self, cmd: int, data: int) -> bool: + ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = True + return True + + def env_directory(self, cmd: int, data: int) -> bool: + value = self.system_dir if cmd == ENV_GET_SYSTEM_DIRECTORY else self.save_dir + buffer = ctypes.create_string_buffer(value) + self.option_buffers.append(buffer) + ctypes.cast(data, ctypes.POINTER(ctypes.c_char_p))[0] = ctypes.cast(buffer, ctypes.c_char_p) + return True + + def env_pixel_format(self, cmd: int, data: int) -> bool: + fmt = ctypes.cast(data, ctypes.POINTER(ctypes.c_int))[0] + if fmt not in PIXEL_BYTES: + return False + self.pixel_format = fmt + return True + + def env_set_variables(self, cmd: int, data: int) -> bool: + array = ctypes.cast(data, ctypes.POINTER(RetroVariable)) + index = 0 + while array[index].key: + key, desc = array[index].key, (array[index].value or b"").decode("utf-8", "replace") + values = desc.split(";", 1)[-1].strip().split("|") + self.declared[key.decode()] = values + self.defaults[key] = values[0].encode() + index += 1 + return True + + def env_get_variable(self, cmd: int, data: int) -> bool: + var = ctypes.cast(data, ctypes.POINTER(RetroVariable))[0] + value = self.options.get(var.key, self.defaults.get(var.key)) + if value is None: + return False + buffer = ctypes.create_string_buffer(value) + self.option_buffers.append(buffer) + ctypes.cast(data, ctypes.POINTER(RetroVariable))[0].value = ctypes.cast(buffer, ctypes.c_char_p) + return True + + def env_variable_update(self, cmd: int, data: int) -> bool: + ctypes.cast(data, ctypes.POINTER(ctypes.c_bool))[0] = False + return True + + def env_log_interface(self, cmd: int, data: int) -> bool: + ctypes.cast(data, ctypes.POINTER(RetroLogCallback))[0] = self.log_callback + return True + + def env_core_options_version(self, cmd: int, data: int) -> bool: + ctypes.cast(data, ctypes.POINTER(ctypes.c_uint))[0] = 0 + return True + def video_refresh(self, data: int, width: int, height: int, pitch: int) -> None: if data and data != ctypes.c_void_p(-1).value: row = width * PIXEL_BYTES[self.pixel_format] @@ -530,7 +549,15 @@ def run_worker(spec: dict) -> dict: os.environ.clear() os.environ.update(spec["env"]) core = ctypes.CDLL(spec["core"]) - front = Frontend(spec) + # What a run showed so far, one JSON line per event, flushed at once: + # a core that kills the worker leaves its logs and frames behind. + events_path = spec.get("events") + with (open(events_path, "a", encoding="utf-8", buffering=1) if events_path + else contextlib.nullcontext()) as events: + return drive_core(core, Frontend(spec, events), spec) + + +def drive_core(core: ctypes.CDLL, front: Frontend, spec: dict) -> dict: for name, fn in zip(("retro_set_environment", "retro_set_video_refresh", "retro_set_audio_sample", "retro_set_audio_sample_batch", "retro_set_input_poll", "retro_set_input_state"), front.callbacks): @@ -578,7 +605,7 @@ def run_worker(spec: dict) -> dict: if spec.get("state_out"): Path(spec["state_out"]).write_bytes(state) state_vars = mednafen_state_vars(state) - observables = { + observables: dict[str, object] = { "frame_sha1": hashlib.sha1(front.last_frame).hexdigest(), "video_sha1": front.video.hexdigest(), "audio_sha1": front.audio.hexdigest(), @@ -697,13 +724,20 @@ class Synthetic: def label(self, dest: str) -> str: if self.kind == "zeros": return f"{dest}-zeros-{self.size}" - return f"{dest}-head-{self.size}-of-{self.source.name}" + return f"{dest}-head-{self.size}-of-{self.head_source.name}" + + @property + def head_source(self) -> Path: + """The file a head is cut from: parse() refuses a head without one.""" + if self.source is None: + raise ValueError(f"@head:{self.size} names no file") + return self.source def write(self, out: Path) -> None: if self.kind == "zeros": out.write_bytes(bytes(self.size)) return - with self.source.open("rb") as handle: + with self.head_source.open("rb") as handle: out.write_bytes(handle.read(self.size)) @@ -889,7 +923,7 @@ def exit_description(returncode: int) -> dict: def partial_result(events: Path, spec: dict) -> dict: """A repetition rebuilt from the events a worker wrote before it died.""" - lines = [] + lines: list[dict] = [] if events.is_file(): for line in events.read_text(encoding="utf-8", errors="replace").splitlines(): with contextlib.suppress(ValueError): @@ -1034,7 +1068,8 @@ def run_variant(args: argparse.Namespace, base: dict[str, Path], variant: Varian reference = reps[0].get("observables") for index, rep in enumerate(reps[1:], 1): if rep.get("observables") != reference: - differing = sorted(k for k in (reference or {}) if (rep.get("observables") or {}).get(k) != reference[k]) + shown = reference or {} + differing = sorted(k for k in shown if (rep.get("observables") or {}).get(k) != shown[k]) flags.append(f"repetition {index} disagrees with repetition 0 on {', '.join(differing)}") out = { "label": variant.label, @@ -1153,15 +1188,14 @@ def not_a_checkout_root(directory: Path) -> str | None: return None -def validate_args(args: argparse.Namespace) -> list[str]: +def _input_problems(args: argparse.Namespace) -> list[str]: problems: list[str] = [] if not Path(args.core).is_file(): problems.append(f"--core {args.core}: not a file") if args.content and not Path(args.content).is_file(): problems.append(f"--content {args.content}: not a file") - for dest, src in args.system_file: - if not Path(src).is_file(): - problems.append(f"--system-file {dest}={src}: not a file") + problems.extend(f"--system-file {dest}={src}: not a file" + for dest, src in args.system_file if not Path(src).is_file()) if args.repeat < 1: problems.append("--repeat must be >= 1") if args.frames < 1 or args.warmup < 0: @@ -1176,13 +1210,18 @@ def validate_args(args: argparse.Namespace) -> list[str]: # A library the loader cannot find is skipped without a word, and # the run would record a fixed clock it never had. Only a file that # exists is bound into the sandbox and recorded by sha256. - for library in value.replace(":", " ").split(): - if not (Path(library).is_absolute() and Path(library).is_file()): - problems.append(f"--env LD_PRELOAD: {library} is not an absolute path to a file") + problems.extend(f"--env LD_PRELOAD: {library} is not an absolute path to a file" + for library in value.replace(":", " ").split() + if not (Path(library).is_absolute() and Path(library).is_file())) if args.oracle and not Path(args.oracle).is_file(): problems.append(f"--oracle {args.oracle}: not a file") if args.png_dir and not args.frame_hash_every: problems.append("--png-dir needs --frame-hash-every") + return problems + + +def _record_problems(args: argparse.Namespace) -> list[str]: + problems: list[str] = [] if args.record: wrong = not_a_checkout_root(Path(args.record)) if wrong: @@ -1199,26 +1238,40 @@ def validate_args(args: argparse.Namespace) -> list[str]: problems.append(f"{flag} {value!r}: lowercase letters, digits, - and _ only") if args.mode == "bench" and args.record and args.repeat < MIN_BENCH_REPETITIONS: problems.append(f"a recorded benchmark needs --repeat >= {MIN_BENCH_REPETITIONS}") + return problems + + +def _vary_problem(dest: str, src: str) -> str: + if src.startswith("@"): + try: + made = Synthetic.parse(src) + except argparse.ArgumentTypeError as exc: + return f"--vary {dest}: {exc}" + if made.source and not made.source.is_file(): + return f"--vary {dest}={src}: {made.source} is not a file" + elif src and not Path(src).is_file(): + return f"--vary {dest}={src}: not a file" + return "" + + +def _check_mode_problems(args: argparse.Namespace) -> list[str]: + problems: list[str] = [] + dests = {dest for dest, _ in args.vary} + if len(dests) != 1: + problems.append("--vary must name the same DEST in every occurrence") + problems.extend(problem for dest, src in args.vary if (problem := _vary_problem(dest, src))) + names = set(BASE_OBSERVABLES) | {f"state:{v}" for v in args.state_var} + if args.frame_hash_every: + names.update(("frame_hashes", "uniform_frames")) + if args.observable not in names: + problems.append(f"--observable {args.observable}: not one of {', '.join(sorted(names))}") + return problems + + +def validate_args(args: argparse.Namespace) -> list[str]: + problems = _input_problems(args) + _record_problems(args) if args.mode == "check": - dests = {dest for dest, _ in args.vary} - if len(dests) != 1: - problems.append("--vary must name the same DEST in every occurrence") - for dest, src in args.vary: - if src.startswith("@"): - try: - made = Synthetic.parse(src) - except argparse.ArgumentTypeError as exc: - problems.append(f"--vary {dest}: {exc}") - continue - if made.source and not made.source.is_file(): - problems.append(f"--vary {dest}={src}: {made.source} is not a file") - elif src and not Path(src).is_file(): - problems.append(f"--vary {dest}={src}: not a file") - names = set(BASE_OBSERVABLES) | {f"state:{v}" for v in args.state_var} - if args.frame_hash_every: - names.update(("frame_hashes", "uniform_frames")) - if args.observable not in names: - problems.append(f"--observable {args.observable}: not one of {', '.join(sorted(names))}") + problems += _check_mode_problems(args) return problems diff --git a/scripts/game_rules.py b/scripts/game_rules.py index 5cee18b39..12014f947 100644 --- a/scripts/game_rules.py +++ b/scripts/game_rules.py @@ -186,10 +186,10 @@ class Checker: self._files(where, entry["profile"], profile, entry.get("files") or []) header = (entry.get("trigger") or {}).get("header") if header and self.readers is not None: - self._header(where, header) + self._header(where, header, self.readers) - def _header(self, where: str, header: dict) -> None: - reader = self.readers.get(header["reader"]) + def _header(self, where: str, header: dict, readers: dict[str, dict]) -> None: + reader = readers.get(header["reader"]) if reader is None: self.errors.append(f"{where}: games/headers.yml has no reader {header['reader']}") return diff --git a/scripts/generate_games_index.py b/scripts/generate_games_index.py index 0b99a5220..959ffce22 100644 --- a/scripts/generate_games_index.py +++ b/scripts/generate_games_index.py @@ -31,38 +31,37 @@ Nothing here is written by hand: a second run writes the same bytes. from __future__ import annotations import argparse +import functools import gzip import hashlib import json import posixpath import sys -from collections.abc import Iterable -from dataclasses import dataclass +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) -from common import ( # noqa: E402 +from common import ( load_emulator_profiles, load_platform_config, native_layer, repository_output_lock, run_cli, ) -from region import normalize_declared # noqa: E402 -from romfolders import ( # noqa: E402 +from region import normalize_declared +from romfolders import ( ProfileResolver, Resolution, SystemResolver, folder_names, load_setups, ) -from artifacts import write_text_atomic # noqa: E402 -from safeparse import yaml_load # noqa: E402 +from artifacts import write_text_atomic +from safeparse import yaml_load -import install # noqa: E402 +import install FORMAT_VERSION = 1 OUTPUT = Path("install") / "games" @@ -221,9 +220,8 @@ def fallback_set( platform_required.get((s, base), True) for s in systems & wanted ) else: - if systems: - if not systems & wanted: - continue + if systems and not systems & wanted: + continue declared = profiles.entries_named(profile or "", base) if not systems and not any(profiles.serves(profile or "", e, system) for e in declared): continue @@ -333,6 +331,104 @@ def emulator_profile(row: dict, platform: str, cores: ProfileResolver, return candidate if any(resolver.equivalents(sid) & declared for sid in systems) else None +@dataclass +class _FallbackTables: + """The fallback sets of a folder's systems under one core, computed + once per platform.""" + + profiles: Profiles + tables: dict[str, dict[str, dict]] = field(default_factory=dict) + narrowed: dict = field(default_factory=dict) + + def keys(self, platform: str, manifest: dict, required: dict[tuple[str, str], bool], + systems: list[str], chosen: str | None) -> list[str]: + keys = [] + table = self.tables.setdefault(platform, {}) + for system in systems: + key = f"{system}|{chosen or ''}" + if key not in table: + table[key] = fallback_set(manifest, required, self.profiles, system, chosen, self.narrowed) + keys.append(key) + return keys + + +@dataclass +class _SetupContext: + resolver: SystemResolver + cores: ProfileResolver + profiles: Profiles + arcade: set[str] + inputs: Inputs + fallbacks: _FallbackTables + manifests: dict[str, dict] = field(default_factory=dict) + required: dict[str, dict[tuple[str, str], bool]] = field(default_factory=dict) + + def manifest(self, platform: str) -> dict | None: + if platform and platform not in self.manifests: + path = self.inputs.install / f"{platform}.json" + if path.exists(): + self.manifests[platform] = _load_json(path) + self.required[platform] = _platform_required(platform, self.inputs.platforms) + return self.manifests.get(platform) + + +def _board_defaults(ctx: _SetupContext, row: dict, + fallback_keys: Callable[[str | None], list[str]] | None) -> dict: + boards = {} + for board, spec in sorted((row.get("board_defaults") or {}).items()): + boards[board] = {"core": spec["core"]} + board_profile = ctx.cores.resolve(spec["core"]) + if board_profile: + boards[board]["profile"] = board_profile + if board_profile in ctx.arcade: + boards[board]["arcade"] = board_profile + if fallback_keys: + # A card moves between boards, and the installer reads + # it on a computer: each board's core has its set. + boards[board]["fallback"] = fallback_keys(board_profile) + return boards + + +def _publish_folder(ctx: _SetupContext, row: dict, platform: str, manifest: dict | None, + counts: dict[str, int]) -> dict: + counts["folders"] += 1 + profile = (ctx.cores.resolve(row.get("core")) + or emulator_profile(row, platform, ctx.cores, ctx.resolver, ctx.profiles)) + resolution = resolve_folder(row, platform, profile, ctx.resolver, ctx.profiles, ctx.arcade) + published: dict = { + "folder": row["folder"], + "systems": resolution.systems, + "basis": resolution.basis, + } + for key in ("name", "aliases", "extensions", "files", "core", "emulator", "note"): + if row.get(key): + published[key] = row[key] + if profile: + published["profile"] = profile + counts["profile"] += 1 + if resolution.systems: + counts["resolved"] += 1 + + fallback_keys = None + if manifest is not None and resolution.systems: + fallback_keys = functools.partial(ctx.fallbacks.keys, platform, manifest, ctx.required[platform], + resolution.systems) + boards = _board_defaults(ctx, row, fallback_keys) + if boards: + published["board_defaults"] = boards + if profile and profile in ctx.arcade: + published["arcade"] = profile + elif row.get("arcade"): + published["arcade"] = True + if fallback_keys: + keys = fallback_keys(profile) + published["fallback"] = keys + if any(ctx.fallbacks.tables[platform][k]["files"] for k in keys): + counts["fallback"] += 1 + published["source_ref"] = row["source_ref"] + return published + + def build_setups( setups: dict[str, dict], resolver: SystemResolver, @@ -342,80 +438,14 @@ def build_setups( inputs: Inputs, ) -> tuple[dict[str, dict], dict[str, dict], dict]: """Published setup documents, fallback tables per platform, coverage.""" - manifests: dict[str, dict] = {} - required: dict[str, dict] = {} - fallbacks: dict[str, dict[str, dict]] = {} - narrowed: dict = {} + ctx = _SetupContext(resolver, cores, profiles, arcade, inputs, _FallbackTables(profiles)) out: dict[str, dict] = {} coverage: dict[str, dict] = {} for setup, doc in sorted(setups.items()): platform = doc.get("platform") or "" - if platform and platform not in manifests: - path = inputs.install / f"{platform}.json" - if path.exists(): - manifests[platform] = _load_json(path) - required[platform] = _platform_required(platform, inputs.platforms) - manifest = manifests.get(platform) - folders: list[dict] = [] + manifest = ctx.manifest(platform) counts = {"folders": 0, "resolved": 0, "profile": 0, "fallback": 0} - for row in doc.get("folders", []): - counts["folders"] += 1 - profile = (cores.resolve(row.get("core")) - or emulator_profile(row, platform, cores, resolver, profiles)) - resolution = resolve_folder(row, platform, profile, resolver, profiles, arcade) - published: dict = { - "folder": row["folder"], - "systems": resolution.systems, - "basis": resolution.basis, - } - for key in ("name", "aliases", "extensions", "files", "core", "emulator", "note"): - if row.get(key): - published[key] = row[key] - if profile: - published["profile"] = profile - counts["profile"] += 1 - if resolution.systems: - counts["resolved"] += 1 - - def fallback_keys(chosen: str | None) -> list[str]: - """The fallback sets of the folder's systems under one core, - computed once per platform.""" - keys = [] - table = fallbacks.setdefault(platform, {}) - for system in resolution.systems: - key = f"{system}|{chosen or ''}" - if key not in table: - table[key] = fallback_set(manifest, required[platform], profiles, system, - chosen, narrowed) - keys.append(key) - return keys - - sets_known = manifest is not None and bool(resolution.systems) - boards = {} - for board, spec in sorted((row.get("board_defaults") or {}).items()): - boards[board] = {"core": spec["core"]} - board_profile = cores.resolve(spec["core"]) - if board_profile: - boards[board]["profile"] = board_profile - if board_profile in arcade: - boards[board]["arcade"] = board_profile - if sets_known: - # A card moves between boards, and the installer reads - # it on a computer: each board's core has its set. - boards[board]["fallback"] = fallback_keys(board_profile) - if boards: - published["board_defaults"] = boards - if profile and profile in arcade: - published["arcade"] = profile - elif row.get("arcade"): - published["arcade"] = True - if sets_known: - keys = fallback_keys(profile) - published["fallback"] = keys - if any(fallbacks[platform][k]["files"] for k in keys): - counts["fallback"] += 1 - published["source_ref"] = row["source_ref"] - folders.append(published) + folders = [_publish_folder(ctx, row, platform, manifest, counts) for row in doc.get("folders", [])] out[setup] = { "format_version": FORMAT_VERSION, "setup": setup, @@ -429,7 +459,7 @@ def build_setups( } coverage[setup] = counts published_fallbacks = { - platform: _shared_table(platform, table) for platform, table in sorted(fallbacks.items()) + platform: _shared_table(platform, table) for platform, table in sorted(ctx.fallbacks.tables.items()) } return out, published_fallbacks, coverage @@ -443,6 +473,32 @@ def _catalogs(directory: Path) -> Iterable[dict]: yield _load_json(path) +def _add_catalog(doc: dict, catalog: dict) -> None: + regions_table = catalog["regions"] + fields = catalog["fields"] + col = {name: i for i, name in enumerate(fields)} + ident = doc.setdefault("identify", {"sources": [], "regions": [], "games": [], "serials": {}}) + region_index: dict[tuple[str, ...], int] = { + tuple(r): i for i, r in enumerate(ident["regions"]) + } + + def reindex(i: int) -> int: + value = tuple(regions_table[i]) if i is not None and i >= 0 else () + if value not in region_index: + region_index[value] = len(ident["regions"]) + ident["regions"].append(list(value)) + return region_index[value] + + ident["sources"].append({ + k: catalog[k] for k in ("source", "dat", "version", "fetched_from", "licence", "serial_note") if k in catalog + }) + for row in catalog["games"]: + region = reindex(row[col["region"]]) + ident["games"].append([row[col["crc32"]], row[col["size"]], region, row[col["title"]]]) + for serial in row[col["serials"]] if "serials" in col else []: + ident["serials"].setdefault(serial, set()).add(region) + + def build_systems( resolver: SystemResolver, profiles: Profiles, @@ -467,30 +523,7 @@ def build_systems( return docs.setdefault(key, {"format_version": FORMAT_VERSION, "system": key}) for catalog in _catalogs(games / "catalogs"): - doc = doc_for(catalog["system"]) - regions_table = catalog["regions"] - fields = catalog["fields"] - col = {name: i for i, name in enumerate(fields)} - ident = doc.setdefault("identify", {"sources": [], "regions": [], "games": [], "serials": {}}) - region_index: dict[tuple[str, ...], int] = { - tuple(r): i for i, r in enumerate(ident["regions"]) - } - - def reindex(i: int) -> int: - value = tuple(regions_table[i]) if i is not None and i >= 0 else () - if value not in region_index: - region_index[value] = len(ident["regions"]) - ident["regions"].append(list(value)) - return region_index[value] - - ident["sources"].append({ - k: catalog[k] for k in ("source", "dat", "version", "fetched_from", "licence", "serial_note") if k in catalog - }) - for row in catalog["games"]: - region = reindex(row[col["region"]]) - ident["games"].append([row[col["crc32"]], row[col["size"]], region, row[col["title"]]]) - for serial in row[col["serials"]] if "serials" in col else []: - ident["serials"].setdefault(serial, set()).add(region) + _add_catalog(doc_for(catalog["system"]), catalog) for doc in docs.values(): ident = doc.get("identify") if ident: diff --git a/scripts/measurement_records.py b/scripts/measurement_records.py index a4dc7c802..26435f80c 100644 --- a/scripts/measurement_records.py +++ b/scripts/measurement_records.py @@ -156,9 +156,8 @@ def check_line(record: dict) -> list[str]: problems.append(f"{rid}: id does not hash the first-layout record ({digest})") elif record_id(record) != rid: problems.append(f"{rid}: id does not hash the record ({record_id(record)})") - for key in ("emulator", "subject"): - if not SLUG_PATTERN.match(str(record.get(key, ""))): - problems.append(f"{rid}: {key} {record.get(key)!r} is not a lowercase slug") + problems.extend(f"{rid}: {key} {record.get(key)!r} is not a lowercase slug" + for key in ("emulator", "subject") if not SLUG_PATTERN.match(str(record.get(key, "")))) return problems @@ -227,7 +226,7 @@ def read_records(root: Path) -> list[Stored]: continue if emulator in CAMPAIGN_FILES: continue - seen: set[str] = set() + seen: set[str | None] = set() try: records = parse_lines(files[path].read_text(encoding="utf-8"), path) except RecordError as exc: diff --git a/scripts/migrate.py b/scripts/migrate.py index ffa7248b5..52c62c0d3 100644 --- a/scripts/migrate.py +++ b/scripts/migrate.py @@ -252,55 +252,30 @@ def sha1_blob(data: bytes) -> str: return hashlib.sha1(data).hexdigest() -def classify_file(filepath: str) -> tuple: - """Determine (Manufacturer, Console) for a file path from a branch. +ARCADE_ROM_PREFIXES = ( + "roms/fba/", + "roms/fbneo/", + "roms/mame/", + "roms/mame-libretro/", + "roms/neogeo/", + "roms/naomi/", + "roms/atomiswave/", + "roms/macintosh/", +) - Returns None if the file should be skipped. - """ - name = os.path.basename(filepath) - if name in SKIP_FILES: - return None - ext = os.path.splitext(name)[1].lower() - if ext in SKIP_EXTENSIONS: +def _strip_branch_prefix(filepath: str) -> str | None: + """The path below its bios/ or arcade roms/ folder, None for any other + roms/ path.""" + if filepath.startswith("roms/") and not filepath.startswith(ARCADE_ROM_PREFIXES): return None + for prefix in ("bios/", "BIOS/", *ARCADE_ROM_PREFIXES): + if filepath.startswith(prefix): + return filepath[len(prefix) :] + return filepath - clean = filepath - for prefix in ( - "bios/", - "BIOS/", - "roms/fba/", - "roms/fbneo/", - "roms/mame/", - "roms/mame-libretro/", - "roms/neogeo/", - "roms/naomi/", - "roms/atomiswave/", - "roms/macintosh/", - ): - if clean.startswith(prefix): - clean = clean[len(prefix) :] - break - - if filepath.startswith("roms/") and not any( - filepath.startswith(p) - for p in ( - "roms/fba/", - "roms/fbneo/", - "roms/mame/", - "roms/mame-libretro/", - "roms/neogeo/", - "roms/naomi/", - "roms/atomiswave/", - "roms/macintosh/", - ) - ): - return None - - for prefix, target in PATH_PREFIX_MAP.items(): - if clean.startswith(prefix): - return target +def _classify_by_name(name: str, filepath: str) -> tuple[str, str] | None: if name in BIOS_FILE_MAP: return BIOS_FILE_MAP[name] @@ -324,19 +299,33 @@ def classify_file(filepath: str) -> tuple: if name.endswith(".zip") and filepath.startswith(("roms/", "BIOS/")): return ("Arcade", "Arcade") - - if "saves/" in filepath: - return None - - if name.endswith(".chd"): - return None - - if name.endswith((".img", ".lst", ".dat")) and "saves/" in filepath: - return None - return None +def classify_file(filepath: str) -> tuple[str, str] | None: + """Determine (Manufacturer, Console) for a file path from a branch. + + Returns None if the file should be skipped. + """ + name = os.path.basename(filepath) + + if name in SKIP_FILES: + return None + ext = os.path.splitext(name)[1].lower() + if ext in SKIP_EXTENSIONS: + return None + + clean = _strip_branch_prefix(filepath) + if clean is None: + return None + + for prefix, target in PATH_PREFIX_MAP.items(): + if clean.startswith(prefix): + return target + + return _classify_by_name(name, filepath) + + def get_subpath(filepath: str, manufacturer: str, console: str) -> str: """Get the sub-path within the console directory (for nested files like neocd/*).""" name = os.path.basename(filepath) @@ -373,7 +362,7 @@ def extract_from_branches(target: Path, dry_run: bool, existing_hashes: set) -> continue result = subprocess.run( - ["git", "ls-tree", "-r", "--name-only", ref], capture_output=True, text=True + ["git", "ls-tree", "-r", "--name-only", ref], capture_output=True, text=True, check=False ) files = result.stdout.strip().split("\n") print(f"\n Branch '{branch}': {len(files)} files") @@ -551,9 +540,8 @@ def main() -> None: ".gitignore", } for d in sorted(source.iterdir()): - if d.name not in known and not d.name.startswith("."): - if d.is_dir(): - print(f"\nWARNING: Unmapped directory: {d.name}") + if d.name not in known and not d.name.startswith(".") and d.is_dir(): + print(f"\nWARNING: Unmapped directory: {d.name}") print(f"\nTotal: {moved} files migrated, {len(existing_hashes)} unique hashes") diff --git a/scripts/pack_probe.py b/scripts/pack_probe.py index 14a84a29c..7cdff2b50 100644 --- a/scripts/pack_probe.py +++ b/scripts/pack_probe.py @@ -41,7 +41,6 @@ from __future__ import annotations import argparse import contextlib -import datetime as dt import fcntl import hashlib import json @@ -62,6 +61,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import autorun import campaign import measurement_records as mr +from autorun import now_iso from common import ( _norm_system_id, load_emulator_profiles, @@ -272,7 +272,7 @@ def so_names(name: str, profile: dict, buildbot: set[str], target: set[str] | No def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot: set[str], target: set[str] | None) -> list[CoreChoice]: wanted = _norm_system_id(system) - out = [] + out: list[CoreChoice] = [] for name in sorted(resolve_platform_cores(config, profiles, target)): profile = profiles[name] if wanted not in {_norm_system_id(s) for s in profile.get("systems") or ()}: @@ -389,9 +389,8 @@ def map_run(layout: Layout, staged: set[str], rep: dict, profile: dict) -> tuple else: kind = "missing_declared" if names else "missing_undeclared" findings.append({"kind": kind, "path": path, "declared_by": names, "paths": elsewhere}) - for item in opened: - if item["path"] in staged and item["entry"] is None: - findings.append({"kind": "unlisted", "path": item["path"], "declared_by": [], "paths": []}) + findings.extend({"kind": "unlisted", "path": item["path"], "declared_by": [], "paths": []} + for item in opened if item["path"] in staged and item["entry"] is None) return opened, findings @@ -456,10 +455,6 @@ def content_folder(content: campaign.Content, fetch: bool) -> Path: # One probe: a core, a game, a layout # -------------------------------------------------------------------------- -def now_iso() -> str: - return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat() - - def wait_idle(limit: float = IDLE_WAIT, poll: float = 30.0) -> None: """Wait for the load core_probe records under, a quarter of the CPUs. Extracting a pack loads the host itself for a minute or two.""" @@ -535,10 +530,22 @@ def subject_for(platform: str, install: str, system: str, so: str, content: str) return f"{mr.PACK_SUBJECT_PREFIX}{subject}" -def probe_one(layout: Layout, platform: str, config: dict, profile: dict, choice: CoreChoice, - core: dict, system: str, content: campaign.Content, load: Path, work: Path) -> dict: +@dataclass(frozen=True) +class ProbeTarget: + """One core of one system, on the game loaded for it.""" + + choice: CoreChoice + core: dict + system: str + content: campaign.Content + load: Path + + +def probe_one(layout: Layout, platform: str, config: dict, profile: dict, target: ProbeTarget, + work: Path) -> dict: """Run until the staging is closed. The first run is recorded, and when the staging grew, the closed one is recorded too and supersedes it.""" + choice, core, system, content, load = target.choice, target.core, target.system, target.content, target.load native = platform_system(config, system) dests = [f.get("destination") or f.get("name") for f in ((config.get("systems") or {}).get(native) or {}).get("files") or ()] @@ -626,7 +633,7 @@ def plan(platform: str, systems: set[str] | None, cores: set[str] | None, config = load_platform_config(platform, str(ROOT / "platforms")) profiles = load_emulator_profiles(str(ROOT / "emulators")) target = load_target_config(platform, TARGETS[platform], str(ROOT / "platforms")) - units = [] + units: list[Unit] = [] for system, contents in sorted(load_contents([campaign.CONTENT_FILE, PACK_CONTENT_FILE]).items()): if systems and system not in systems: continue @@ -668,8 +675,9 @@ def run(args: argparse.Namespace) -> int: continue for choice in unit.cores: core = fetch_core(choice.so_name, args.refresh_cores) - line = probe_one(layout, args.platform, config, profiles[choice.emulator], choice, - core, unit.system, unit.content, load, work / "runs") + target = ProbeTarget(choice, core, unit.system, unit.content, load) + line = probe_one(layout, args.platform, config, profiles[choice.emulator], target, + work / "runs") sealed = append_line(line) print(f"{args.platform} {install} {unit.system} {choice.so_name}: {line['verdict']}, " f"{len(line['files_opened'])} opened, {len(line['findings'])} findings, " diff --git a/scripts/pr_checks.py b/scripts/pr_checks.py index 5855469a3..6114c5513 100644 --- a/scripts/pr_checks.py +++ b/scripts/pr_checks.py @@ -82,9 +82,9 @@ def shown(step: Step) -> str: def execute(step: Step) -> int: env = {**os.environ, **step.env} if not step.then: - return subprocess.run(argv(step.command), cwd=ROOT, env=env).returncode - first = subprocess.run(argv(step.command), cwd=ROOT, env=env, stdout=subprocess.PIPE) - return subprocess.run(argv(step.then), cwd=ROOT, env=env, input=first.stdout).returncode + return subprocess.run(argv(step.command), cwd=ROOT, env=env, check=False).returncode + first = subprocess.run(argv(step.command), cwd=ROOT, env=env, stdout=subprocess.PIPE, check=False) + return subprocess.run(argv(step.then), cwd=ROOT, env=env, input=first.stdout, check=False).returncode def run(steps: tuple[Step, ...] = STEPS) -> int: diff --git a/scripts/profile_sync.py b/scripts/profile_sync.py index 06a50e567..49991c349 100644 --- a/scripts/profile_sync.py +++ b/scripts/profile_sync.py @@ -135,7 +135,7 @@ class PartResult: class RepoView: """One repository a profile cites, at the two revisions under comparison.""" - repo: object + repo: upstream.Repo pin: str head: str origin: str @@ -467,7 +467,8 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation] if kind == "ref": for label, ref in source_ref_values(value): citations.append(Citation( - field=field_name, kind="ref", ref=ref, entry=holder, + field=field_name, kind="ref", ref=ref, + entry=holder if isinstance(holder, dict) else None, holder=holder, key=key, label=label, )) if isinstance(value, str): @@ -512,11 +513,10 @@ def _find_all(haystack: list[str], needle: list[str]) -> list[int]: if not size or size > len(haystack): return [] first = needle[0] - hits = [] - for i in range(len(haystack) - size + 1): - if haystack[i] == first and haystack[i : i + size] == needle: - hits.append(i) - return hits + return [ + i for i in range(len(haystack) - size + 1) + if haystack[i] == first and haystack[i : i + size] == needle + ] def _map_index( @@ -753,6 +753,114 @@ def _written_against_head(part: RefPart, head_lines: list[str] | None) -> bool: TREE_TRUNCATED = "(HEAD tree truncated by the forge)" +def _unanchorable(part: RefPart) -> PartResult | None: + """The verdict on a part that cites no source path of a declared tree.""" + if is_binary_citation(part.path): + return PartResult( + part, "BINARY", None, None, None, [], + "cites a shipped binary, no source path to anchor", + ) + if is_external_citation(part.path): + return PartResult( + part, "EXTERNAL", None, None, None, [], + "names a project the profile does not declare", + ) + return None + + +def _rename_verdict( + part: RefPart, candidates: list[str], slug: str | None, url: str | None +) -> PartResult: + """What a part absent at HEAD reads as when no rename was found.""" + if candidates == [TREE_TRUNCATED]: + return PartResult( + part, "AMBIGUOUS", None, None, None, [], + "absent from a HEAD tree the forge truncated: " + "the file may still exist", + slug, url, + ) + if candidates: + return PartResult( + part, + "AMBIGUOUS", + None, + None, + None, + [], + f"{len(candidates)} candidates: {', '.join(candidates[:5])}", + slug, + url, + ) + return PartResult( + part, + "GONE", + None, + None, + None, + [], + "absent at HEAD, no rename found", + slug, + url, + ) + + +def _anchor_range( + part: RefPart, + start: int, + pin_lines: list[str], + head_lines: list[str], + tokens: Sequence[str], +) -> tuple[AnchorResult, str, str | None]: + """The cited range carried from the pin to HEAD: anchor, status, note.""" + end = part.last + anchored = anchor_block(pin_lines, head_lines, start, end) + note = anchored.reason + if anchored.status in REVIEW_STATUSES: + nudged = nudge_to_declared(pin_lines, start, end, tokens) + if nudged is not None: + retry = anchor_block(pin_lines, head_lines, *nudged) + if retry.status not in REVIEW_STATUSES: + anchored = retry + note = f"cited line was {nudged[0] - start:+d} off its subject" + status = anchored.status + if status in ("CHANGED", "GONE") and tokens: + located = locate_by_declared_value(head_lines, anchored, tokens) + if located is not None: + moved_start, moved_end, why = located + anchored = AnchorResult("MOVED", moved_start, moved_end, []) + status, note = "MOVED", why + return anchored, status, note + + +def _pin_missing( + part: RefPart, pin_lines: list[str] | None, head_lines: list[str], +) -> str | None: + """Why the pinned revision cannot carry the cited range, None when it can.""" + if pin_lines is None: + # Present at HEAD, absent at the pin, and the cited range fits the + # HEAD file: the ref was written against HEAD while source_commit + # still names an older revision. Saying "missing" sends the reader + # hunting for a move that never happened: the fix is the pin. + reason = "pin revision missing" + if _written_against_head(part, head_lines): + reason = "written against HEAD, pin names an older revision" + return reason + if part.last > len(pin_lines): + # The file is there and the line is not yet: the pinned revision is + # shorter than the one the ref was written against. nestopia cited + # the palette and database loads at 2041 and 2063, which is where + # HEAD carries them, over a pin four hundred lines shorter. A range + # that only ends past the file is no better: dolphin cited 239-323 in + # a 317-line NANDImporter.cpp, and the block found above the end + # anchored it. + return ( + "written against HEAD, pin names an older revision" + if _written_against_head(part, head_lines) + else "cited range ends past the end of the file" + ) + return None + + def anchor_part( part: RefPart, fetch: Callable[[str, str, int | None, Sequence[str]], list[str] | None], @@ -765,16 +873,9 @@ def anchor_part( `describe(path)` returns (repo slug, raw URL at HEAD) for the repository that owns the path, or (None, None) when the caller does not track it. """ - if is_binary_citation(part.path): - return PartResult( - part, "BINARY", None, None, None, [], - "cites a shipped binary, no source path to anchor", - ) - if is_external_citation(part.path): - return PartResult( - part, "EXTERNAL", None, None, None, [], - "names a project the profile does not declare", - ) + unanchorable = _unanchorable(part) + if unanchorable is not None: + return unanchorable slug, url, actual = ( describe(part.path, part.start, tokens) if describe else (None, None, part.path) @@ -786,36 +887,7 @@ def anchor_part( if head_lines is None: moved, candidates = rename_getter(part.path) if moved is None: - if candidates == [TREE_TRUNCATED]: - return PartResult( - part, "AMBIGUOUS", None, None, None, [], - "absent from a HEAD tree the forge truncated: " - "the file may still exist", - slug, url, - ) - if candidates: - return PartResult( - part, - "AMBIGUOUS", - None, - None, - None, - [], - f"{len(candidates)} candidates: {', '.join(candidates[:5])}", - slug, - url, - ) - return PartResult( - part, - "GONE", - None, - None, - None, - [], - "absent at HEAD, no rename found", - slug, - url, - ) + return _rename_verdict(part, candidates, slug, url) path = moved head_lines = fetch(HEAD, path, part.start, tokens) if head_lines is None: @@ -838,48 +910,11 @@ def anchor_part( # same resolved path usually holds at the pin. A genuine rename keeps # the old path at the pin, which is why that one is tried first. pin_lines = fetch(PIN, path, part.start, tokens) - if pin_lines is None: - # Present at HEAD, absent at the pin, and the cited range fits the - # HEAD file: the ref was written against HEAD while source_commit - # still names an older revision. Saying "missing" sends the reader - # hunting for a move that never happened: the fix is the pin. - reason = "pin revision missing" - if _written_against_head(part, head_lines): - reason = "written against HEAD, pin names an older revision" + reason = _pin_missing(part, pin_lines, head_lines) + if reason is not None or pin_lines is None: return PartResult(part, "GONE", None, None, None, [], reason, slug, url) - end = part.last - if end > len(pin_lines): - # The file is there and the line is not yet: the pinned revision is - # shorter than the one the ref was written against. nestopia cited - # the palette and database loads at 2041 and 2063, which is where - # HEAD carries them, over a pin four hundred lines shorter. A range - # that only ends past the file is no better: dolphin cited 239-323 in - # a 317-line NANDImporter.cpp, and the block found above the end - # anchored it. - reason = ( - "written against HEAD, pin names an older revision" - if _written_against_head(part, head_lines) - else "cited range ends past the end of the file" - ) - return PartResult(part, "GONE", None, None, None, [], reason, slug, url) - - anchored = anchor_block(pin_lines, head_lines, part.start, end) - note = anchored.reason - if anchored.status in REVIEW_STATUSES: - nudged = nudge_to_declared(pin_lines, part.start, end, tokens) - if nudged is not None: - retry = anchor_block(pin_lines, head_lines, *nudged) - if retry.status not in REVIEW_STATUSES: - anchored = retry - note = f"cited line was {nudged[0] - part.start:+d} off its subject" - status = anchored.status - if status in ("CHANGED", "GONE") and tokens: - located = locate_by_declared_value(head_lines, anchored, tokens) - if located is not None: - start, end, why = located - anchored = AnchorResult("MOVED", start, end, []) - status, note = "MOVED", why + anchored, status, note = _anchor_range(part, part.start, pin_lines, head_lines, tokens) if renamed and status in ("ANCHORED", "SHIFTED"): status = "RENAMED" return PartResult( @@ -969,7 +1004,10 @@ def refuse_collapsing_moves(parts: list[PartResult]) -> list[PartResult]: for part in parts: target = (part.new_path or part.part.path, part.start, part.end or part.start) own = (part.part.path, part.part.start, part.part.last) - if part.status in REBASE_STATUSES and target != own and target in cited: + if ( + part.status in REBASE_STATUSES and part.start is not None + and target != own and target in cited + ): part = replace( part, status="AMBIGUOUS", candidates=[part.start], reason="lands on a line another part of this ref already cites", @@ -1066,7 +1104,7 @@ class ProfileReport: def uncheckable(self) -> bool: """Whether the skip is a defect of the profile rather than its nature.""" - return bool(self.skipped) and self.skipped.startswith(self.UNCHECKABLE) + return bool(self.skipped and self.skipped.startswith(self.UNCHECKABLE)) def needs_review(self) -> int: counts = self.counts or {} @@ -1122,7 +1160,7 @@ def select_repo(profile: dict) -> upstream.Repo | None: def resolve_pin( profile: dict, repo: upstream.Repo, cache_dir: str, offline: bool, field: str = "source", mode: str = "", branch: str | None = None, -) -> tuple[str | None, str | None]: +) -> tuple[str, str] | tuple[None, None]: """Commit the profile was written at, and how it was obtained. `field` selects which declared pin applies: `source_commit` for the port @@ -1142,7 +1180,7 @@ def resolve_pin( if not date: return None, None sha = upstream.resolve_commit_at(repo, date, cache_dir, offline, branch) - return sha, (f"profiled_date {date}" if sha else None) + return (sha, f"profiled_date {date}") if sha else (None, None) def select_views( @@ -1188,7 +1226,7 @@ def select_views( pin, origin = resolve_pin( profile, repo, cache_dir, offline, pin_field, mode, branch ) - if not pin: + if not pin or origin is None: continue head = head or upstream.resolve_head(repo, cache_dir, offline, branch) except upstream.GoneError: @@ -1362,16 +1400,9 @@ def verify_at_pin( contains, so comparing the two says nothing. What can still be checked is self-consistency: does the cited range carry the value the entry declares? """ - if is_binary_citation(part.path): - return PartResult( - part, "BINARY", None, None, None, [], - "cites a shipped binary, no source path to anchor", - ) - if is_external_citation(part.path): - return PartResult( - part, "EXTERNAL", None, None, None, [], - "names a project the profile does not declare", - ) + unanchorable = _unanchorable(part) + if unanchorable is not None: + return unanchorable if pin_lines is None: return PartResult( part, "GONE", None, None, None, [], "absent at the pinned revision" @@ -1399,6 +1430,13 @@ def verify_at_pin( window = "\n".join(pin_lines[lo:hi]).lower() if any(token in window for token in tokens): return PartResult(part, "ANCHORED", None, None, None, []) + return _value_elsewhere(part, pin_lines, hash_tokens) + + +def _value_elsewhere( + part: RefPart, pin_lines: list[str], hash_tokens: Sequence[str] +) -> PartResult: + """A part whose cited window lacks the value, judged by where it is.""" # A ref that cites loading logic never spells the value out, so its absence # here proves nothing. Only finding the value somewhere else in the file # shows the ref points at the wrong place, and only a hash carries that @@ -1464,7 +1502,7 @@ def reconcile_self_check( ] -def version_tag_candidates(core_version: str, repo_name: str = "") -> list[str]: +def version_tag_candidates(core_version: object, repo_name: str = "") -> list[str]: """Tag spellings a declared core_version might use. Some projects prefix their own name and drop the separators, the way @@ -1687,17 +1725,16 @@ def _check_build_refs( return results -def build_report( - name: str, profile: dict, cache_dir: str, offline: bool = False, - text: str | None = None, -) -> ProfileReport: - """Confront one profile with its upstream.""" - report = ProfileReport(name=name, entries=[], counts={}) +def _gather_refs( + profile: dict, text: str | None +) -> tuple[list, list[tuple[Citation, dict]]]: + """The citations to anchor, and the refs read at a shipped build instead. - # One citation surface for the whole document. A prose citation carries - # no declared value, so it anchors on content alone: the nudge and - # relocation heuristics stay off rather than guess from a profile-wide - # token pool. + One citation surface for the whole document. A prose citation carries + no declared value, so it anchors on content alone: the nudge and + relocation heuristics stay off rather than guess from a profile-wide + token pool. + """ known = frozenset( repo.name.lower() for _, _, url in declared_repositories(profile) @@ -1713,7 +1750,7 @@ def build_report( deferred.append((citation, at_build[id(citation.holder)])) continue if citation.kind == "ref": - entry = citation.entry + entry = citation.entry or {} display = str(entry.get("name") or "") or citation.field if citation.label: display += f" [{citation.label}]" @@ -1740,21 +1777,12 @@ def build_report( citation.field, citation.ref, [], [], list(citation.parts), citation, )) - # A part that names no repository is looked up first where its path is - # cited elsewhere: a note citing `src/a.c:12` beside source_refs that - # all read `upstream src/a.c` means that tree. - # A path cited under both roles lends neither, and such a part is - # compared in every repository rather than in whichever comes first. - path_roles = _path_roles(refs) + return refs, deferred - def role_of(part: RefPart) -> str: - if part.role: - return part.role - lent = path_roles.get(part.path, ()) - return next(iter(lent)) if len(lent) == 1 else "" - # Directories the profile already cites, deepest first, to settle a bare - # filename that several trees of one repository carry. +def _cited_dirs(refs: list) -> set[str]: + """Directories the profile already cites, deepest first, to settle a bare + filename that several trees of one repository carry.""" cited_dirs: set[str] = set() for _, _, _, _, parts, _ in refs: for part in parts: @@ -1762,7 +1790,27 @@ def build_report( while directory: cited_dirs.add(directory) directory = posixpath.dirname(directory) + return cited_dirs + +def _unanswered_skip(profile: dict) -> str: + """Why a profile no declared repository answers for is skipped.""" + # A declared pin whose repository or branch does not answer is not a + # profile without a pin: pyxel's kitao/pyxel answers 404, and the + # message sent the reader looking for a missing source_commit. + return ( + "no declared repository answers (moved, removed, or a branch the " + "forge does not know)" + if profile.get("source_commit") or profile.get("upstream_commit") + else "no source_commit and no resolvable profiled_date " + "on any declared repository" + ) + + +def _readable_views( + profile: dict, report: ProfileReport, cache_dir: str, offline: bool +) -> list[RepoView] | None: + """The repositories to read, None once the report says why it is skipped.""" report.unread = [ url for _, _, url in declared_repositories(profile) @@ -1771,7 +1819,7 @@ def build_report( if select_repo(profile) is None: declared = str(profile.get("source") or profile.get("upstream") or "") report.skipped = f"unsupported host: {declared or 'none declared'}" - return report + return None stated_gone = str(profile.get("upstream_gone") or "").strip() @@ -1787,7 +1835,7 @@ def build_report( # a recorded fact, not an open problem: the refs describe the last # revision anyone can reach, and nothing further is possible. report.skipped = f"upstream gone (declared): {stated_gone}" - return report + return None raise if stated_gone and any(view.field != "source_mirror" for view in views): # Declared dead, yet it answered. A profile that keeps saying so stops @@ -1795,22 +1843,27 @@ def build_report( report.skipped = ( f"upstream_gone is declared but the forge answers: {stated_gone}" ) - return report + return None if not views and stated_gone: report.skipped = f"upstream gone (declared): {stated_gone}" - return report + return None if not views: - # A declared pin whose repository or branch does not answer is not a - # profile without a pin: pyxel's kitao/pyxel answers 404, and the - # message sent the reader looking for a missing source_commit. - report.skipped = ( - "no declared repository answers (moved, removed, or a branch the " - "forge does not know)" - if profile.get("source_commit") or profile.get("upstream_commit") - else "no source_commit and no resolvable profiled_date " - "on any declared repository" - ) - return report + report.skipped = _unanswered_skip(profile) + return None + return views + + +def _on_own_revision(view: RepoView, tagged: dict[tuple[str, str], str]) -> bool: + """Whether a view is read at its own revision: on HEAD, or on its tag.""" + return view.pin == view.head or (view.repo.host, view.repo.slug) in tagged + + +def _record_revisions( + profile: dict, report: ProfileReport, views: list[RepoView], + cache_dir: str, offline: bool, +) -> dict[tuple[str, str], str]: + """Put the revisions under comparison on the report, and return the views + read at their release tag.""" primary = views[0] report.repo, report.host = primary.repo.slug, primary.repo.host report.repos = [v.repo.slug for v in views] @@ -1843,33 +1896,217 @@ def build_report( None, ) - def on_own_revision(view: RepoView) -> bool: - return view.pin == view.head or (view.repo.host, view.repo.slug) in tagged - if not report.pinned_tag: # A tag or a held pin is off the tracked branch by design. report.orphaned = [ f"{view.repo.slug}: pin {view.pin[:8]} is no ancestor of {view.head[:8]}" for view in views - if not on_own_revision(view) + if not _on_own_revision(view, tagged) and upstream.compare( view.repo, view.pin, view.head, cache_dir, offline ).diverged ] + return tagged - # A profile carrying no source_ref still has a pin worth writing and a - # version worth checking, so the revisions above are resolved first. - if not refs: - report.skipped = NO_SOURCE_REF - return report - owners: dict[tuple[str, int | None], tuple[RepoView, str]] = {} - context: dict[str, object] = {} - truncated_trees: set[str] = set() - pin_trees: dict[str, list[str] | None] = {} +def _line_score(lines: list[str], start: int | None, tokens: tuple) -> int: + """How well a repository's cited line matches what the ref means. - def _locate( - path: str, start: int | None = None, tokens: tuple = (), wanted: str = "" + Two repositories can hold the same path with different contents: + `mame` cites files that both mamedev/mame and its libretro fork + carry, and the fork's tree is offset, so its line 5545 is a real + but unrelated statement. A line carrying the entry's own subject + beats a merely non-empty one, which in turn beats a blank. + """ + if start is None: + return 2 + if start > len(lines): + return 0 + # A blank cited line opens the block below it: lrps2's + # VMManager.cpp:418 is blank in the fork it was written for, and + # scored 0 it handed the ref to the upstream, where 418 is + # unrelated code that then decided the rebase target. + line = next( + (ln.lower() for ln in lines[start - 1:start - 1 + BLANK_LOOKAHEAD] + if ln.strip()), + "", + ) + # A set name sits between delimiters in a MAME declaration, so + # `pgm` matches `GAME( 1997, pgm,` but not `pgm_012_025_drgw2`, + # which is what tells the two repositories apart. + if tokens and any( + re.search(rf"\b{re.escape(tok)}\b", line) for tok in tokens + ): + return 3 + if tokens and any(tok in line for tok in tokens): + return 2 + return 1 if line.strip() else 0 + + +@dataclass +class _Resolver: + """Where each cited path lives across the declared repositories, and how + a part reads there, memoised for one profile.""" + + name: str + profile: dict + cache_dir: str + offline: bool + views: list[RepoView] + report: ProfileReport + tagged: dict[tuple[str, str], str] + # A part that names no repository is looked up first where its path is + # cited elsewhere: a note citing `src/a.c:12` beside source_refs that + # all read `upstream src/a.c` means that tree. + # A path cited under both roles lends neither, and such a part is + # compared in every repository rather than in whichever comes first. + path_roles: dict[str, set[str]] + cited_dirs: set[str] + owners: dict[tuple[str, int | None, tuple, str], tuple[RepoView, str]] = field( + default_factory=dict + ) + context: dict[str, tuple[CompareResult, list[str]]] = field(default_factory=dict) + truncated_trees: set[str] = field(default_factory=set) + pin_trees: dict[str, list[str]] = field(default_factory=dict) + mute: set[tuple[str, str]] = field(default_factory=set) + lines_cache: dict[ + tuple[str, str, int | None, tuple[str, ...], str | None, str], list[str] + ] = field(default_factory=dict) + + @property + def primary(self) -> RepoView: + return self.views[0] + + def role_of(self, part: RefPart) -> str: + if part.role: + return part.role + lent = self.path_roles.get(part.path, ()) + return next(iter(lent)) if len(lent) == 1 else "" + + def on_own_revision(self, view: RepoView) -> bool: + return _on_own_revision(view, self.tagged) + + def trees_in_order(self) -> Iterable[list[str] | None]: + """Pin trees before HEAD trees, each read only when reached.""" + return itertools.chain( + map(self.pin_tree_for, self.views), + (self.context_for(v)[1] for v in self.views), + ) + + def gitlinks_in_order(self) -> Iterable[Iterable[str]]: + return ( + upstream.list_gitlinks(v.repo, v.pin, self.cache_dir, self.offline) + for v in self.views + ) + + def _add_bare_name_matches(self, path: str, candidates: list[str]) -> None: + # A bare filename, the way prose cites files. Resolved against the + # pin before HEAD: the ref was written at the pin, and a file that + # moved since would otherwise be resolved to a HEAD path that does + # not exist at the pin, reporting GONE for the one reason it never + # should. The rename search then carries the pin path to HEAD. + for view in self.views: + for tree in (self.pin_tree_for(view), self.context_for(view)[1]): + matches = [ + p for p in tree or [] + if posixpath.basename(p) == path + ] + if len(matches) > 1: + matches = narrow_by_cited(matches, self.cited_dirs) + # A few survivors are told apart by the cited line below: a + # 266-line Windows configure.ac cannot carry line 754. + if len(matches) <= 4: + candidates.extend( + m for m in matches if m not in candidates + ) + if matches: + break + + def _add_suffix_matches(self, path: str, candidates: list[str]) -> None: + # A path written from a subproject directory of a monorepo: + # `src/main/Main.cc` in emu-ex-plus-alpha is PCE.emu/src/main/Main.cc + # for one profile and C64.emu/src/main/Main.cc for another. The + # tree is searched by suffix and the cited directories decide. + suffix = "/" + path + for view in self.views: + _, tree = self.context_for(view) + matches = [p for p in tree or [] if p.endswith(suffix)] + if len(matches) > 1: + matches = narrow_by_cited(matches, self.cited_dirs) + if len(matches) <= 4: + candidates.extend(m for m in matches if m not in candidates) + + def _candidate_paths(self, path: str) -> list[str]: + """The paths a cited path may stand for, as written first.""" + candidates = [path] + head, _, tail = path.partition("/") + if tail and any(head == v.repo.name for v in self.views): + candidates.append(tail) + if "/" not in path: + self._add_bare_name_matches(path, candidates) + elif not any( + self.fetch_from(v.repo, sha, path) is not None + for v in self.views for sha in (v.pin, v.head) + ): + self._add_suffix_matches(path, candidates) + return candidates + + def _upstream_on_line( + self, candidate: str, at_pin: bool, start: int | None, tokens: tuple + ) -> RepoView | None: + """The upstream holding the entry's value on the cited line too.""" + for other in self.views: + if _view_role(other) != "upstream": + continue + sha = other.pin if at_pin else other.head + theirs = self.fetch_from(other.repo, sha, candidate) + if theirs is not None and _line_score(theirs, start, tokens) == 3: + return other + return None + + def _try_candidate( + self, + candidate: str, + ordered: list[RepoView], + start: int | None, + tokens: tuple, + wanted: str, + best: tuple[int, RepoView, str] | None, + ) -> tuple[tuple[RepoView, str] | None, tuple[int, RepoView, str] | None]: + """The owner one candidate path settles, else the best seen so far.""" + for at_pin in (True, False): + for view in ordered: + sha = view.pin if at_pin else view.head + found = self.fetch_from(view.repo, sha, candidate) + if found is None: + continue + target = symlink_target(candidate, found) + if target: + found = self.fetch_from(view.repo, sha, target) + if found is None: + continue + candidate = target + rank = _line_score(found, start, tokens) + if rank and _answers(view, wanted) and view.mode: + # An entry of one build mode is that build's code: + # xenia-edge's standalone xbox.xex refs scored higher + # in the libretro tree, whose same file is offset. + return (view, candidate), best + if rank == 3 and not wanted and _view_role(view) == "source": + # The port carries a copy of the emulator: when the + # original holds the same value on the cited line, + # the code asking for the file is the emulator's. + other = self._upstream_on_line(candidate, at_pin, start, tokens) + if other is not None: + return (other, candidate), best + if rank == 3: + return (view, candidate), best + if best is None or rank > best[0]: + best = (rank, view, candidate) + return None, best + + def locate( + self, path: str, start: int | None = None, tokens: tuple = (), wanted: str = "" ) -> tuple[RepoView, str]: """Repository and real path carrying a cited path, HEAD before pin. @@ -1883,144 +2120,42 @@ def build_report( libretro fork carry today, but only the upstream pin holds them. The fork's pin is an older tree where they lived elsewhere. """ - candidates = [path] - head, _, tail = path.partition("/") - if tail and any(head == v.repo.name for v in views): - candidates.append(tail) - if "/" not in path: - # A bare filename, the way prose cites files. Resolved against the - # pin before HEAD: the ref was written at the pin, and a file that - # moved since would otherwise be resolved to a HEAD path that does - # not exist at the pin, reporting GONE for the one reason it never - # should. The rename search then carries the pin path to HEAD. - for view in views: - for tree in (_pin_tree_for(view), _context_for(view)[1]): - matches = [ - p for p in tree or [] - if posixpath.basename(p) == path - ] - if len(matches) > 1: - matches = narrow_by_cited(matches, cited_dirs) - # A few survivors are told apart by the cited line below: a - # 266-line Windows configure.ac cannot carry line 754. - if len(matches) <= 4: - candidates.extend( - m for m in matches if m not in candidates - ) - if matches: - break - elif not any( - fetch_from(v.repo, sha, path) is not None - for v in views for sha in (v.pin, v.head) - ): - # A path written from a subproject directory of a monorepo: - # `src/main/Main.cc` in emu-ex-plus-alpha is PCE.emu/src/main/Main.cc - # for one profile and C64.emu/src/main/Main.cc for another. The - # tree is searched by suffix and the cited directories decide. - suffix = "/" + path - for view in views: - _, tree = _context_for(view) - matches = [p for p in tree or [] if p.endswith(suffix)] - if len(matches) > 1: - matches = narrow_by_cited(matches, cited_dirs) - if len(matches) <= 4: - candidates.extend(m for m in matches if m not in candidates) - - def score(lines: list[str]) -> int: - """How well a repository's cited line matches what the ref means. - - Two repositories can hold the same path with different contents: - `mame` cites files that both mamedev/mame and its libretro fork - carry, and the fork's tree is offset, so its line 5545 is a real - but unrelated statement. A line carrying the entry's own subject - beats a merely non-empty one, which in turn beats a blank. - """ - if start is None: - return 2 - if start > len(lines): - return 0 - # A blank cited line opens the block below it: lrps2's - # VMManager.cpp:418 is blank in the fork it was written for, and - # scored 0 it handed the ref to the upstream, where 418 is - # unrelated code that then decided the rebase target. - line = next( - (ln.lower() for ln in lines[start - 1:start - 1 + BLANK_LOOKAHEAD] - if ln.strip()), - "", - ) - # A set name sits between delimiters in a MAME declaration, so - # `pgm` matches `GAME( 1997, pgm,` but not `pgm_012_025_drgw2`, - # which is what tells the two repositories apart. - if tokens and any( - re.search(rf"\b{re.escape(tok)}\b", line) for tok in tokens - ): - return 3 - if tokens and any(tok in line for tok in tokens): - return 2 - return 1 if line.strip() else 0 - + candidates = self._candidate_paths(path) # A part that names its repository is looked up there first. In a # profile keyed by build mode, a part naming none belongs to the # first build declared, as _realign_part decides a shared path: the # libretro tree of xenia-edge carries emulator.cc offset, and its # better-scored line hid a standalone ref that had moved. - if not wanted and primary.mode: - wanted = primary.mode - ordered = sorted(views, key=lambda v: not _answers(v, wanted)) if wanted else views - best = None + if not wanted and self.primary.mode: + wanted = self.primary.mode + ordered = ( + sorted(self.views, key=lambda v: not _answers(v, wanted)) if wanted + else self.views + ) + best: tuple[int, RepoView, str] | None = None for candidate in candidates: - for sha_of in (lambda v: v.pin, lambda v: v.head): - for view in ordered: - found = fetch_from(view.repo, sha_of(view), candidate) - if found is None: - continue - target = symlink_target(candidate, found) - if target: - found = fetch_from(view.repo, sha_of(view), target) - if found is None: - continue - candidate = target - rank = score(found) - if rank and _answers(view, wanted) and view.mode: - # An entry of one build mode is that build's code: - # xenia-edge's standalone xbox.xex refs scored higher - # in the libretro tree, whose same file is offset. - return view, candidate - if rank == 3 and not wanted and _view_role(view) == "source": - # The port carries a copy of the emulator: when the - # original holds the same value on the cited line, - # the code asking for the file is the emulator's. - for other in views: - if _view_role(other) != "upstream": - continue - theirs = fetch_from(other.repo, sha_of(other), candidate) - if theirs is not None and score(theirs) == 3: - return other, candidate - if rank == 3: - return view, candidate - if best is None or rank > best[0]: - best = (rank, view, candidate) - return (best[1], best[2]) if best else (primary, path) + found, best = self._try_candidate(candidate, ordered, start, tokens, wanted, best) + if found is not None: + return found + return (best[1], best[2]) if best else (self.primary, path) def resolve_path( - path: str, start: int | None = None, tokens: tuple = (), role: str = "" + self, path: str, start: int | None = None, tokens: tuple = (), role: str = "" ) -> tuple[RepoView, str]: key = (path, start, tokens, role) - if key not in owners: - owners[key] = _locate(path, start, tokens, role) - return owners[key] + if key not in self.owners: + self.owners[key] = self.locate(path, start, tokens, role) + return self.owners[key] - def _pin_tree_for(view: RepoView) -> list[str] | None: + def pin_tree_for(self, view: RepoView) -> list[str]: """Tree at the revision the refs were written against, memoised.""" key = view.repo.slug - if key not in pin_trees: - tree, _ = upstream.list_tree(view.repo, view.pin, cache_dir, offline) - pin_trees[key] = tree - return pin_trees[key] + if key not in self.pin_trees: + tree, _ = upstream.list_tree(view.repo, view.pin, self.cache_dir, self.offline) + self.pin_trees[key] = tree + return self.pin_trees[key] - mute: set[tuple[str, str]] = set() - - def fetch_from(repo: upstream.Repo, sha: str, wanted: str) -> list[str] | None: + def fetch_from(self, repo: upstream.Repo, sha: str, wanted: str) -> list[str] | None: """Read a file, treating a repository that refuses as one that lacks it. A profile can name several repositories, and a mirror exists exactly @@ -2034,56 +2169,58 @@ def build_report( # Keyed by host as well as slug: a mirror carries the same slug on # another forge, and muting one must not silence the other. key = (repo.host, repo.slug) - if key in mute: + if key in self.mute: return None try: - found = upstream.fetch_file(repo, sha, wanted, cache_dir, offline) + found = upstream.fetch_file(repo, sha, wanted, self.cache_dir, self.offline) if found is None and "/" in wanted: # A file of a submodule is read at the commit its gitlink # pins in this revision, so a bump moves it with the port. - inner = upstream.through_gitlink(repo, sha, wanted, cache_dir, offline) + inner = upstream.through_gitlink( + repo, sha, wanted, self.cache_dir, self.offline + ) if inner is not None: - found = upstream.fetch_file(*inner, cache_dir, offline) + found = upstream.fetch_file(*inner, self.cache_dir, self.offline) return found except (upstream.RateLimitError, upstream.NotCachedError): raise except upstream.UpstreamError as exc: - mute.add(key) - print(f"{name}: {repo.host}/{repo.slug} muted, {exc}", file=sys.stderr) + self.mute.add(key) + print(f"{self.name}: {repo.host}/{repo.slug} muted, {exc}", file=sys.stderr) return None - def _context_for(view: RepoView) -> tuple[CompareResult, list[str]]: + def context_for(self, view: RepoView) -> tuple[CompareResult, list[str]]: key = view.repo.slug - if key not in context: + if key not in self.context: comparison = upstream.compare( - view.repo, view.pin, view.head, cache_dir, offline + view.repo, view.pin, view.head, self.cache_dir, self.offline ) tree, truncated = upstream.list_tree( - view.repo, view.head, cache_dir, offline + view.repo, view.head, self.cache_dir, self.offline ) - context[key] = (comparison, tree) + self.context[key] = (comparison, tree) if truncated: - truncated_trees.add(key) + self.truncated_trees.add(key) if truncated and tree: print( - f"{name}: {key} HEAD tree truncated by the forge, " + f"{self.name}: {key} HEAD tree truncated by the forge, " "rename search is partial", file=sys.stderr, ) - return context[key] + return self.context[key] - def rename_getter(path: str, role: str = "") -> tuple[str | None, list[str]]: + def rename_getter(self, path: str, role: str = "") -> tuple[str | None, list[str]]: """Resolved only when a cited file has vanished, then memoised. Every declared repository is searched, not just the one that owns the path: a profile citing both a port and its upstream may point at a file that only the other one carries. """ - owner, actual = resolve_path(path, role=role) - ordered = [owner] + [v for v in views if v is not owner] + owner, actual = self.resolve_path(path, role=role) + ordered = [owner] + [v for v in self.views if v is not owner] candidates: list[str] = [] for view in ordered: - comparison, tree = _context_for(view) + comparison, tree = self.context_for(view) found, near = resolve_rename(comparison, actual, tree) if found: return found, [] @@ -2091,24 +2228,12 @@ def build_report( # across repositories turns a resolvable path into an ambiguous one. if view is owner: candidates = near - if not candidates and any(v.repo.slug in truncated_trees for v in ordered): + if not candidates and any(v.repo.slug in self.truncated_trees for v in ordered): return None, [TREE_TRUNCATED] return None, candidates - # Pin trees before HEAD trees, each read only when reached. - refs = _resolve_project_words( - refs, - lambda: itertools.chain( - map(_pin_tree_for, views), map(lambda v: _context_for(v)[1], views) - ), - lambda: ( - upstream.list_gitlinks(v.repo, v.pin, cache_dir, offline) for v in views - ), - ) - - lines_cache: dict[tuple[str, str, int | None], list[str] | None] = {} - def fetch( + self, which: str, path: str, start: int | None = None, @@ -2122,24 +2247,25 @@ def build_report( on identity. """ tokens = tuple(tokens) - key = (which, path, start, tokens, forced and forced.repo.slug, role) - if key not in lines_cache: + key = (which, path, start, tokens, forced.repo.slug if forced else None, role) + if key not in self.lines_cache: view, actual = ( (forced, path) if forced - else resolve_path(path, start, tokens, role) + else self.resolve_path(path, start, tokens, role) ) sha = view.pin if which == PIN else view.head - found = fetch_from(view.repo, sha, actual) + found = self.fetch_from(view.repo, sha, actual) if found is None: # Not cached: the miss may be a repository that has just been # muted, and the next call resolves the path to a mirror that # does carry it. upstream.fetch_file holds its own cache, so # asking again costs a lookup rather than a request. return None - lines_cache[key] = found - return lines_cache[key] + self.lines_cache[key] = found + return self.lines_cache[key] def describe( + self, path: str, start: int | None = None, tokens: Iterable[str] = (), @@ -2148,12 +2274,12 @@ def build_report( ) -> tuple[str | None, str, str]: view, actual = ( (forced, path) if forced - else resolve_path(path, start, tuple(tokens), role) + else self.resolve_path(path, start, tuple(tokens), role) ) - slug = view.repo.slug if view is not primary else None + slug = view.repo.slug if view is not self.primary else None return slug, upstream.raw_url(view.repo, view.head, actual), actual - def anchor_across_views(part: RefPart, tokens: Sequence[str]) -> PartResult: + def anchor_across_views(self, part: RefPart, tokens: Sequence[str]) -> PartResult: """Judge a part against every repository that carries its path. A ref is only broken when it fails everywhere. `mame` cites files that @@ -2164,35 +2290,31 @@ def build_report( repository carries the path: hypseus-singe cites lair.cpp under `source` for one entry and `upstream` for the next. """ - owner, _actual = resolve_path( - part.path, part.start, tuple(tokens), role_of(part) - ) + role = self.role_of(part) + owner, _actual = self.resolve_path(part.path, part.start, tuple(tokens), role) carrying = [ - view for view in views - if fetch_from(view.repo, view.pin, part.path) is not None + view for view in self.views + if self.fetch_from(view.repo, view.pin, part.path) is not None ] # Judged in the build it belongs to: the best outcome across the # builds of a keyed profile let the libretro tree vouch for a # standalone ref that had moved (xenia-edge's emulator.cc). - meant = part.role or primary.mode + meant = part.role or self.primary.mode named = [view for view in carrying if _answers(view, meant)] if meant and named: carrying = named live = { id(view) for view in carrying - if fetch_from(view.repo, view.head, part.path) is not None + if self.fetch_from(view.repo, view.head, part.path) is not None } - best = None + renames = functools.partial(self.rename_getter, role=role) + best: tuple[int, PartResult] | None = None for view in carrying: result = anchor_part( part, - lambda which, path, start=None, toks=(), _v=view: fetch( - which, path, start, toks, _v - ), - lambda path: rename_getter(path, role_of(part)), - lambda path, start=None, toks=(), _v=view: describe( - path, start, toks, _v - ), + functools.partial(self.fetch, forced=view), + renames, + functools.partial(self.describe, forced=view), tokens, ) if ( @@ -2211,32 +2333,72 @@ def build_report( best = (rank, result) return best[1] if best else anchor_part( part, - lambda which, path, start=None, toks=(): fetch( - which, path, start, toks, role=role_of(part) - ), - lambda path: rename_getter(path, role_of(part)), - lambda path, start=None, toks=(): describe( - path, start, toks, role=role_of(part) - ), + functools.partial(self.fetch, role=role), + renames, + functools.partial(self.describe, role=role), tokens, ) - # Comparing a revision with itself anchors every ref whatever it cites, so - # a part whose repository already sits on HEAD is judged on - # self-consistency instead. Decided per part, by the repository that owns - # it: a primary on HEAD says nothing about an upstream that moved on. - def self_checked(part: RefPart, tokens: Sequence[str]) -> bool: - if report.pinned_tag: + def self_checked(self, part: RefPart, tokens: Sequence[str]) -> bool: + """Whether a part is judged on self-consistency rather than compared. + + Comparing a revision with itself anchors every ref whatever it cites, + so a part whose repository already sits on HEAD is judged on + self-consistency instead. Decided per part, by the repository that + owns it: a primary on HEAD says nothing about an upstream that moved on. + """ + if self.report.pinned_tag: return True - if not part.role and len(path_roles.get(part.path, ())) > 1: - return all(on_own_revision(view) for view in views) - view, _ = resolve_path(part.path, part.start, tuple(tokens), role_of(part)) - return on_own_revision(view) + if not part.role and len(self.path_roles.get(part.path, ())) > 1: + return all(self.on_own_revision(view) for view in self.views) + view, _ = self.resolve_path(part.path, part.start, tuple(tokens), self.role_of(part)) + return self.on_own_revision(view) + + def _elsewhere_at_own_revision( + self, part: RefPart, owner: RepoView, tokens: Sequence[str], hashes: Sequence[str], + ) -> PartResult | None: + """The verdict of another repository read at its own revision.""" + for view in self.views: + if view is owner or not self.on_own_revision(view): + continue + lines = self.fetch_from(view.repo, view.pin, part.path) + if lines is None: + continue + found = verify_at_pin(part, lines, tokens, hashes) + if found.status != "GONE": + return replace( + found, + repo=None if view is self.primary else view.repo.slug, + ) + return None + + def _judge_at_pin( + self, part: RefPart, tokens: Sequence[str], hashes: Sequence[str] + ) -> PartResult: + role = self.role_of(part) + result = verify_at_pin( + part, + self.fetch(PIN, part.path, part.start, tokens, role=role), + tokens, hashes, + ) + # Checked at its own revision, the part still lies in one tree: + # the report names it, as a comparison does. + owner, _actual = self.resolve_path(part.path, part.start, tuple(tokens), role) + if result.repo is None and owner is not self.primary: + result = replace(result, repo=owner.repo.slug) + if result.status == "GONE": + # The owner is chosen on the cited first line alone. hatari's + # port carries a longer src/paths.c than the upstream that a + # source_ref attributes the path to, and prose citing the + # port's 305-356 read past the end of the upstream's 345 + # lines. As in a comparison, a ref fails only everywhere. + result = self._elsewhere_at_own_revision(part, owner, tokens, hashes) or result + return result def judge( - part: RefPart, flag: bool, tokens: Sequence[str], hashes: Sequence[str] + self, part: RefPart, flag: bool, tokens: Sequence[str], hashes: Sequence[str] ) -> PartResult: - other = cites_another_version(part, profile.get("core_version")) + other = cites_another_version(part, self.profile.get("core_version")) if other: # ti99sim cites v0.0.11 beside its v0.16.0 pin: no revision of # the pinned repository holds that program, so it cannot anchor. @@ -2245,48 +2407,18 @@ def build_report( f"annotated for version {other}, not the documented one", ) if flag: - result = verify_at_pin( - part, - fetch(PIN, part.path, part.start, tokens, role=role_of(part)), - tokens, hashes, - ) - # Checked at its own revision, the part still lies in one tree: - # the report names it, as a comparison does. - owner, _actual = resolve_path( - part.path, part.start, tuple(tokens), role_of(part) - ) - if result.repo is None and owner is not primary: - result = replace(result, repo=owner.repo.slug) - if result.status == "GONE": - # The owner is chosen on the cited first line alone. hatari's - # port carries a longer src/paths.c than the upstream that a - # source_ref attributes the path to, and prose citing the - # port's 305-356 read past the end of the upstream's 345 - # lines. As in a comparison, a ref fails only everywhere. - for view in views: - if view is owner or not on_own_revision(view): - continue - lines = fetch_from(view.repo, view.pin, part.path) - if lines is None: - continue - found = verify_at_pin(part, lines, tokens, hashes) - if found.status != "GONE": - result = replace( - found, - repo=None if view is primary else view.repo.slug, - ) - break + result = self._judge_at_pin(part, tokens, hashes) else: - result = anchor_across_views(part, tokens) + result = self.anchor_across_views(part, tokens) # A forge that refused the request said nothing about the file: # git.eden-emu.dev answers 403 to scripts, and nine citations of # eden-nightly read "absent at HEAD" for a file that exists. - owner, _actual = resolve_path( - part.path, part.start, tuple(tokens), role_of(part) + owner, _actual = self.resolve_path( + part.path, part.start, tuple(tokens), self.role_of(part) ) if ( result.status in ("GONE", "AMBIGUOUS") - and (owner.repo.host, owner.repo.slug) in mute + and (owner.repo.host, owner.repo.slug) in self.mute ): return PartResult( part, "UNCHECKED", None, None, None, [], @@ -2294,13 +2426,14 @@ def build_report( ) return result - report.build_refs = _check_build_refs(profile, deferred, views, fetch_from) +def _judge_refs(resolver: _Resolver, refs: list, report: ProfileReport) -> None: + """Judge every ref and put its entry on the report.""" staged = [] for entry_name, ref, tokens, hashes, ref_parts, citation in refs: - flags = [self_checked(part, tokens) for part in ref_parts] + flags = [resolver.self_checked(part, tokens) for part in ref_parts] judged = [ - judge(part, flag, tokens, hashes) + resolver.judge(part, flag, tokens, hashes) for part, flag in zip(ref_parts, flags) ] staged.append((entry_name, ref, citation, reconcile_self_check(judged, flags))) @@ -2314,6 +2447,36 @@ def build_report( )) report.counts[status] = report.counts.get(status, 0) + 1 + +def build_report( + name: str, profile: dict, cache_dir: str, offline: bool = False, + text: str | None = None, +) -> ProfileReport: + """Confront one profile with its upstream.""" + report = ProfileReport(name=name, entries=[], counts={}) + refs, deferred = _gather_refs(profile, text) + path_roles = _path_roles(refs) + cited_dirs = _cited_dirs(refs) + + views = _readable_views(profile, report, cache_dir, offline) + if views is None: + return report + tagged = _record_revisions(profile, report, views, cache_dir, offline) + + # A profile carrying no source_ref still has a pin worth writing and a + # version worth checking, so the revisions above are resolved first. + if not refs: + report.skipped = NO_SOURCE_REF + return report + + resolver = _Resolver( + name, profile, cache_dir, offline, views, report, tagged, path_roles, cited_dirs + ) + refs = _resolve_project_words( + refs, resolver.trees_in_order, resolver.gitlinks_in_order + ) + report.build_refs = _check_build_refs(profile, deferred, views, resolver.fetch_from) + _judge_refs(resolver, refs, report) return report @@ -2368,8 +2531,8 @@ def _part_line(part: PartResult) -> str: return f" {_original_part(part)} {detail}" -def format_report(report: ProfileReport, changed_only: bool = False) -> str: - """Human-readable report for one profile.""" +def _report_header(report: ProfileReport) -> list[str]: + """Repository, revisions and version lines heading one report.""" slugs = " + ".join(report.repos) if report.repos else (report.repo or "") lines = [f"{report.name} {slugs}".rstrip()] if report.pin and report.head: @@ -2389,12 +2552,9 @@ def format_report(report: ProfileReport, changed_only: bool = False) -> str: f" upstream pinned to tag {report.upstream_tag}: checked against " "its own revision, not against HEAD" ) - for url in report.unread or []: - lines.append(f" not read (unsupported host): {url}") - for line in report.orphaned: - lines.append(f" orphaned pin: {line}") - for line in report.moved_repos: - lines.append(f" moved repository: {line}") + lines.extend(f" not read (unsupported host): {url}" for url in report.unread or []) + lines.extend(f" orphaned pin: {line}" for line in report.orphaned) + lines.extend(f" moved repository: {line}" for line in report.moved_repos) if report.declared_version or report.page_version: lines.append( f" version page: declared {report.declared_version or '-'}, " @@ -2412,21 +2572,22 @@ def format_report(report: ProfileReport, changed_only: bool = False) -> str: ) if report.version_warning: lines.append(f" {report.version_warning}") - if report.skipped: - lines.append(f" skipped: {report.skipped}") - return "\n".join(lines) + return lines + + +def _report_body(report: ProfileReport, changed_only: bool) -> list[str]: + """Ref, prose and build lines of one report that was read.""" + lines = [] for entry in report.entries: if changed_only and entry.status not in REVIEW_STATUSES: continue lines.append(f" {entry.name} {entry.source_ref}") - for part in entry.parts: - lines.append(_part_line(part)) + lines.extend(_part_line(part) for part in entry.parts) summary = ", ".join( f"{count} {status.lower()}" for status, count in sorted(report.counts.items()) ) lines.append(f" {len(report.entries)} refs: {summary}") - for line in report.stale_prose or (): - lines.append(f" prose under an older pin: {line}") + lines.extend(f" prose under an older pin: {line}" for line in report.stale_prose or ()) for ref in report.build_refs: if changed_only and ref["status"] == "BUILD_OK": continue @@ -2436,7 +2597,16 @@ def format_report(report: ProfileReport, changed_only: bool = False) -> str: f"{ref['revision'][:12] or '-'} {ref['ref']}{detail}" ) lines.append(f" {report.needs_review()} to review") - return "\n".join(lines) + return lines + + +def format_report(report: ProfileReport, changed_only: bool = False) -> str: + """Human-readable report for one profile.""" + lines = _report_header(report) + if report.skipped: + lines.append(f" skipped: {report.skipped}") + return "\n".join(lines) + return "\n".join(lines + _report_body(report, changed_only)) def report_to_dict(report: ProfileReport) -> dict: @@ -2714,14 +2884,16 @@ def watch_hashes(added_lines: list[str], known: set[str]) -> list[tuple[str, str for line in added_lines: strong = bool(_SHA1_RE.search(line) or _MD5_RE.search(line)) for pattern, kind in ((_SHA1_RE, "sha1"), (_MD5_RE, "md5")): - for value in pattern.findall(line): - if value.lower() not in known: - found.append((kind, value.lower())) + found.extend( + (kind, value.lower()) for value in pattern.findall(line) + if value.lower() not in known + ) if strong or not _FILE_RE.search(line): continue - for value in _CRC_RE.findall(line): - if value.lower() not in known: - found.append(("crc32", value.lower())) + found.extend( + ("crc32", value.lower()) for value in _CRC_RE.findall(line) + if value.lower() not in known + ) return found @@ -2774,9 +2946,11 @@ def drift_score( DRIFT_WEIGHTS["SHIFTED" if line.startswith("would recale") else "AMBIGUOUS"] for line in report.stale_prose or () ) - if version is not None and not version.tag_matches_declared: - if version.latest_release and version.latest_release != version.declared: - score += 10 + if ( + version is not None and not version.tag_matches_declared + and version.latest_release and version.latest_release != version.declared + ): + score += 10 # A pin off its branch or a repository answering under another name is # set again before any ref can be read, so each outranks a GONE ref: # pcem ranked last at 0 with an orphaned upstream_commit. @@ -2953,6 +3127,8 @@ def set_version_fields(text: str, version: object, basis: dict | None) -> str: if old is not None: del lines[old[0]:old[1]] after = _top_block(lines, "core_version") + if after is None: + raise YamlWriteError("version_basis: core_version not found to write it after") lines[after[1]:after[1]] = _render_basis(basis) return "\n".join(lines) + ("\n" if text.endswith("\n") else "") @@ -3155,6 +3331,182 @@ def scalar_windows( return windows +def _scalar(holder: object, key: object) -> object: + """The value a citation's holder keeps under its key.""" + if isinstance(holder, list) and isinstance(key, int): + return holder[key] + if isinstance(holder, dict): + return holder[key] + raise TypeError(f"no scalar under {key!r} in a {type(holder).__name__}") + + +def _set_scalar(holder: object, key: object, value: str) -> None: + """Replace the value a citation's holder keeps under its key.""" + if isinstance(holder, dict): + holder[key] = value + return + if not isinstance(holder, list) or not isinstance(key, int): + raise TypeError(f"no scalar under {key!r} in a {type(holder).__name__}") + holder[key] = value + + +Span = tuple[int, int, str] + + +@dataclass +class _ProseEdits: + """Replacements gathered over a file and its loaded scalars, and what + was written or left.""" + + lines: list[str] + windows: dict[tuple[int, object], tuple[int, int]] + whole: tuple[int, int] + file_edits: dict[int, list[Span]] = field(default_factory=dict) + value_edits: dict[tuple[int, object], dict[int, list[Span]]] = field(default_factory=dict) + holders: dict[tuple[int, object], tuple[object, object]] = field(default_factory=dict) + applied: list[str] = field(default_factory=list) + left: list[str] = field(default_factory=list) + + +def _prose_replacements( + citation: Citation, moves: dict[int, tuple[int, int, str | None]] +) -> list[Span]: + """The tokens of one run a recale rewrites, measured on its line.""" + replacements: list[Span] = [ + (*citation.spans[index], f"{start}" if end == start else f"{start}-{end}") + for index, (start, end, _) in moves.items() + ] + new_path = next((m[2] for m in moves.values() if m[2]), None) + if new_path: + replacements.append((*citation.path_span, new_path)) + return replacements + + +def _edit_comment_run( + edits: _ProseEdits, citation: Citation, replacements: list[Span], recaled: str +) -> None: + # The comment is read again from the text being written: a run + # whose tokens no longer sit at the collected offsets is left. + lines = edits.lines + line = lines[citation.line] if citation.line < len(lines) else "" + expected = [p.raw for p in citation.parts] + [citation.ref.split(":", 1)[0]] + spans = list(citation.spans) + [citation.path_span] + if any(line[lo:hi] != token for (lo, hi), token in zip(spans, expected)): + edits.left.append(f"{citation.field}: {citation.ref} (comment changed)") + return + edits.file_edits.setdefault(citation.line, []).extend(replacements) + edits.applied.append(f"{citation.field}: {citation.ref} -> {recaled}") + + +def _split_by_line( + citation: Citation, value_lines: list[str], last: int, replacements: list[Span] +) -> dict[int, list[Span]] | None: + """Replacements by the scalar line holding them, None when a token + spans the line break.""" + # A wrapped run puts its spans back on the two scalar lines it + # joined: playdiaemu wrote `content.rs` and `:111-199` one line apart. + by_line: dict[int, list[Span]] = {} + for lo, hi, new in replacements: + if citation.wrapped and lo >= citation.joined_at: + following = value_lines[last] + indent = len(following) - len(following.lstrip()) + shift = indent - citation.joined_at + by_line.setdefault(last, []).append((lo + shift, hi + shift, new)) + elif citation.wrapped and hi > citation.joined_at: + return None + else: + by_line.setdefault(citation.line, []).append((lo, hi, new)) + return by_line + + +def _lines_apart(located: dict[int, int | None], first: int, last: int) -> bool: + """Whether the two lines of a wrapped run are not found together.""" + if None in located.values(): + return True + if len(located) != 2: + return False + low, high = located[first], located[last] + return low is None or high is None or high != low + 1 + + +def _edit_folded_run( + edits: _ProseEdits, citation: Citation, value_lines: list[str], + window: tuple[int, int], recaled: str, +) -> bool: + """Rewrite a run whose scalar is folded, False when it is left.""" + # A folded scalar has no physical line carrying its logical one. + # The run itself is a single word, which folding never breaks: + # when the whole file carries it exactly once, that occurrence + # is the citation, and the run is rewritten as one token. The + # match is delimited, or `x.c:481` would also hit inside a + # neighbouring `x.c:481-482`. + lines = edits.lines + pattern = re.compile( + rf"(? None: + value = str(_scalar(citation.holder, citation.key)) + value_lines = value.splitlines() + last = citation.line + (1 if citation.wrapped else 0) + if last >= len(value_lines): + edits.left.append(f"{citation.field}: {citation.ref} (scalar changed)") + return + by_line = _split_by_line(citation, value_lines, last, replacements) + if by_line is None: + edits.left.append(f"{citation.field}: {citation.ref} (a token spans the line break)") + return + window = edits.windows.get((id(citation.holder), citation.key), edits.whole) + located = { + number: _unique_line(edits.lines, value_lines[number], window) + for number in by_line + } + if citation.wrapped and _lines_apart(located, citation.line, last): + edits.left.append( + f"{citation.field}: {citation.ref} " + "(wrapped, and its two lines are not found together in the file)" + ) + return + placed = {number: hit for number, hit in located.items() if hit is not None} + if len(placed) == len(located): + for number, line_edits in by_line.items(): + hit = placed[number] + offset = edits.lines[hit].index(value_lines[number]) + edits.file_edits.setdefault(hit, []).extend( + (offset + lo, offset + hi, new) for lo, hi, new in line_edits + ) + elif not _edit_folded_run(edits, citation, value_lines, window, recaled): + return + slot = (id(citation.holder), citation.key) + edits.holders[slot] = (citation.holder, citation.key) + for number, line_edits in by_line.items(): + edits.value_edits.setdefault(slot, {}).setdefault(number, []).extend(line_edits) + edits.applied.append(f"{citation.field}: {citation.ref} -> {recaled}") + + def _apply_prose_edits( text: str, jobs: list[tuple[Citation, dict]], document: object = None ) -> tuple[str, list[str], list[str]]: @@ -3169,134 +3521,32 @@ def _apply_prose_edits( """ lines = text.splitlines() trailing = "\n" if text.endswith("\n") else "" - file_edits: dict[int, list[tuple[int, int, str]]] = {} - value_edits: dict[tuple[int, object], dict[int, list]] = {} - holders: dict[tuple[int, object], tuple] = {} - applied: list[str] = [] - left: list[str] = [] - windows = scalar_windows(text, document) if document is not None else {} - whole = (0, len(lines) - 1) + edits = _ProseEdits( + lines, + scalar_windows(text, document) if document is not None else {}, + (0, len(lines) - 1), + ) for citation, moves in jobs: - replacements = [] - for index, (start, end, _) in moves.items(): - lo, hi = citation.spans[index] - replacements.append( - (lo, hi, f"{start}" if end == start else f"{start}-{end}") - ) - new_path = next((m[2] for m in moves.values() if m[2]), None) - if new_path: - replacements.append((*citation.path_span, new_path)) + replacements = _prose_replacements(citation, moves) recaled = _run_after_moves(citation.parts, moves, citation.ref) - if citation.in_comment: - # The comment is read again from the text being written: a run - # whose tokens no longer sit at the collected offsets is left. - line = lines[citation.line] if citation.line < len(lines) else "" - expected = [p.raw for p in citation.parts] + [citation.ref.split(":", 1)[0]] - spans = list(citation.spans) + [citation.path_span] - if any(line[lo:hi] != token for (lo, hi), token in zip(spans, expected)): - left.append(f"{citation.field}: {citation.ref} (comment changed)") - continue - file_edits.setdefault(citation.line, []).extend(replacements) - applied.append(f"{citation.field}: {citation.ref} -> {recaled}") - continue - - value = str(citation.holder[citation.key]) - value_lines = value.splitlines() - last = citation.line + (1 if citation.wrapped else 0) - if last >= len(value_lines): - left.append(f"{citation.field}: {citation.ref} (scalar changed)") - continue - # A wrapped run puts its spans back on the two scalar lines it - # joined: playdiaemu wrote `content.rs` and `:111-199` one line apart. - by_line: dict[int, list[tuple[int, int, str]]] = {} - straddles = False - for lo, hi, new in replacements: - if citation.wrapped and lo >= citation.joined_at: - following = value_lines[last] - indent = len(following) - len(following.lstrip()) - shift = indent - citation.joined_at - by_line.setdefault(last, []).append((lo + shift, hi + shift, new)) - elif citation.wrapped and hi > citation.joined_at: - straddles = True - else: - by_line.setdefault(citation.line, []).append((lo, hi, new)) - if straddles: - left.append(f"{citation.field}: {citation.ref} (a token spans the line break)") - continue - window = windows.get((id(citation.holder), citation.key), whole) - located = { - number: _unique_line(lines, value_lines[number], window) - for number in by_line - } - if citation.wrapped and ( - None in located.values() - or (len(located) == 2 and located[last] != located[citation.line] + 1) - ): - left.append( - f"{citation.field}: {citation.ref} " - "(wrapped, and its two lines are not found together in the file)" - ) - continue - if None not in located.values(): - for number, edits in by_line.items(): - hit = located[number] - offset = lines[hit].index(value_lines[number]) - file_edits.setdefault(hit, []).extend( - (offset + lo, offset + hi, new) for lo, hi, new in edits - ) + _edit_comment_run(edits, citation, replacements, recaled) else: - # A folded scalar has no physical line carrying its logical one. - # The run itself is a single word, which folding never breaks: - # when the whole file carries it exactly once, that occurrence - # is the citation, and the run is rewritten as one token. The - # match is delimited, or `x.c:481` would also hit inside a - # neighbouring `x.c:481-482`. - pattern = re.compile( - rf"(? {recaled}") + _edit_scalar_run(edits, citation, replacements, recaled) - for number, replacements in file_edits.items(): - lines[number] = _replace_spans(lines[number], replacements) - for slot, edits in value_edits.items(): - holder, key = holders[slot] - value = str(holder[key]) + for number, spans in edits.file_edits.items(): + lines[number] = _replace_spans(lines[number], spans) + for slot, by_line in edits.value_edits.items(): + holder, key = edits.holders[slot] + value = str(_scalar(holder, key)) value_lines = value.splitlines() - for line_number, replacements in edits.items(): - value_lines[line_number] = _replace_spans( - value_lines[line_number], replacements - ) - holder[key] = "\n".join(value_lines) + ( + for line_number, spans in by_line.items(): + value_lines[line_number] = _replace_spans(value_lines[line_number], spans) + _set_scalar(holder, key, "\n".join(value_lines) + ( "\n" if value.endswith("\n") else "" - ) - return "\n".join(lines) + trailing, applied, left + )) + return "\n".join(lines) + trailing, edits.applied, edits.left def _replace_spans(line: str, replacements: list[tuple[int, int, str]]) -> str: @@ -3424,6 +3674,53 @@ def attribute_refs(path: Path, report: ProfileReport, profile: dict) -> list[str return applied +def _moved_by_hand(entry: EntryReport, statuses: tuple[str, ...]) -> bool: + """Whether a ref the writer cannot regenerate has a part to move.""" + return any( + part.status in statuses + and part.start is not None + and _rendered_part(part) != _original_part(part) + for part in entry.parts + ) + + +def _recaled_ref(entry: EntryReport, statuses: tuple[str, ...]) -> str | None: + """The source_ref with its moved parts rendered, None when none moves.""" + rendered = [] + touched = False + for part in entry.parts: + if part.status in statuses and part.start is not None: + recaled = _rendered_part(part) + if recaled != _original_part(part): + touched = True + rendered.append(recaled) + else: + rendered.append(_original_part(part)) + return ", ".join(rendered) if touched else None + + +def _recale_statuses( + path: Path, report: ProfileReport, accept_changed: bool +) -> tuple[str, ...] | None: + """The statuses a recale moves, None when the profile must not move.""" + if report.pinned_tag: + return None + statuses = REBASE_STATUSES + (("CHANGED",) if accept_changed else ()) + blocking = [s for s in REVIEW_STATUSES if s not in statuses] + if any((report.counts or {}).get(s) for s in blocking): + return None + blockers = pin_blockers(report, accept_changed) + if blockers: + # Something here will not move: an annotated ref, one under a mode + # key, or a prose run this pass cannot rewrite without guessing. + # bump_commit will refuse while it stands, and recaling the rest + # would leave the profile describing two revisions at once. All or + # nothing means the pin too, not only the refs. + _refuse_recale(path, blockers) + return None + return statuses + + def rebase_refs( path: Path, report: ProfileReport, accept_changed: bool = False ) -> list[str]: @@ -3436,20 +3733,8 @@ def rebase_refs( that only make sense at HEAD. Prose citations move with everything else: only their located tokens are rewritten, the sentence stays. """ - if report.pinned_tag: - return [] - statuses = REBASE_STATUSES + (("CHANGED",) if accept_changed else ()) - blocking = [s for s in REVIEW_STATUSES if s not in statuses] - if any((report.counts or {}).get(s) for s in blocking): - return [] - blockers = pin_blockers(report, accept_changed) - if blockers: - # Something here will not move: an annotated ref, one under a mode - # key, or a prose run this pass cannot rewrite without guessing. - # bump_commit will refuse while it stands, and recaling the rest - # would leave the profile describing two revisions at once. All or - # nothing means the pin too, not only the refs. - _refuse_recale(path, blockers) + statuses = _recale_statuses(path, report, accept_changed) + if statuses is None: return [] text = path.read_text(encoding="utf-8") document = yaml.safe_load(text) @@ -3478,40 +3763,23 @@ def rebase_refs( # The ref lives under a mode key, not on a source_ref line. The # entry name check also holds when the report and the document # disagree: a stale report must not touch a line it never read. - if any( - part.status in statuses - and part.start is not None - and _rendered_part(part) != _original_part(part) - for part in entry.parts - ): + if _moved_by_hand(entry, statuses): refused.append( f"{entry.name}: {entry.source_ref} (under a mode key, moved by hand)" ) continue - if not _is_rewritable(entry.source_ref): - # Rewriting would drop the author's annotations. Still consume - # the line so a later entry carrying the same ref cannot match it. + # Rewriting an annotated ref would drop the author's annotations. + # It, like a ref with nothing to move, still consumes its line so a + # later entry carrying the same ref cannot match it. + new_ref = _recaled_ref(entry, statuses) if _is_rewritable(entry.source_ref) else None + if new_ref is None: cursor = find_field_line(text, "source_ref", entry.source_ref, cursor) + 1 continue - rendered = [] - touched = False - for part in entry.parts: - if part.status in statuses and part.start is not None: - recaled = _rendered_part(part) - if recaled != _original_part(part): - touched = True - rendered.append(recaled) - else: - rendered.append(_original_part(part)) - if not touched: - cursor = find_field_line(text, "source_ref", entry.source_ref, cursor) + 1 - continue - new_ref = ", ".join(rendered) text, index = replace_field_line( text, "source_ref", entry.source_ref, new_ref, cursor ) cursor = index + 1 - citation.holder[citation.key] = new_ref + _set_scalar(citation.holder, citation.key, new_ref) applied.append(f"{entry.source_ref} -> {new_ref}") text, prose_applied, left = _apply_prose_edits(text, prose_jobs, document) @@ -3544,22 +3812,10 @@ def _citation_key(ref: str) -> str: return re.sub(r"\s+", "", ref) -def pending_recale( - report: ProfileReport, accept_changed: bool = False, text: str | None = None +def _pending_refs( + report: ProfileReport, movable: tuple[str, ...], document: dict | None ) -> int: - """Parts that ought to move but the writer has not moved. - - An annotated ref cannot be regenerated without losing its prose, so its - parts stay on the pinned line numbers. Advancing the pin while they do - would leave the profile describing two revisions at once. - - Prose runs are judged on the file as it stands: a run that should move - counts as pending until the document actually carries its recaled form, - so the pin cannot advance over prose that still describes the old - revision, whatever the reason it was not rewritten. - """ - movable = REBASE_STATUSES + (("CHANGED",) if accept_changed else ()) - document = yaml.safe_load(text) if text is not None else None + """Parts of structured refs that ought to move and have not.""" # A ref the writer regenerates is pending only while the file still # carries it as written: a bump run without the recale left lrps2's # SHIFTED refs on the old lines under the new pin. It is looked up at @@ -3587,14 +3843,19 @@ def pending_recale( and part.start is not None and _rendered_part(part) != _original_part(part) ) - if document is None: - return pending + return pending + +def _pending_prose( + report: ProfileReport, movable: tuple[str, ...], document: dict, text: str | None +) -> int: + """Prose runs that ought to move and that the file does not carry moved.""" pool: dict[tuple[str, str], int] = {} for citation in collect_citations(document, text): if citation.kind == "prose": slot = (citation.field, _citation_key(citation.ref)) pool[slot] = pool.get(slot, 0) + 1 + pending = 0 for entry in report.entries or []: if entry.kind != "prose": continue @@ -3602,15 +3863,7 @@ def pending_recale( if not moves: # Either nothing has to move, or the run cannot be written # without guessing, and the second case still blocks the pin. - if any( - part.status in movable - and part.start is not None - and ( - (part.start, part.end) != (part.part.start, part.part.end) - or part.new_path - ) - for part in entry.parts - ): + if any(_part_moves(part, movable) for part in entry.parts): pending += 1 continue rendered = _run_after_moves( @@ -3626,6 +3879,28 @@ def pending_recale( return pending +def pending_recale( + report: ProfileReport, accept_changed: bool = False, text: str | None = None +) -> int: + """Parts that ought to move but the writer has not moved. + + An annotated ref cannot be regenerated without losing its prose, so its + parts stay on the pinned line numbers. Advancing the pin while they do + would leave the profile describing two revisions at once. + + Prose runs are judged on the file as it stands: a run that should move + counts as pending until the document actually carries its recaled form, + so the pin cannot advance over prose that still describes the old + revision, whatever the reason it was not rewritten. + """ + movable = REBASE_STATUSES + (("CHANGED",) if accept_changed else ()) + document = yaml.safe_load(text) if text is not None else None + pending = _pending_refs(report, movable, document) + if document is None: + return pending + return pending + _pending_prose(report, movable, document, text) + + NO_SOURCE_REF = "no source_ref" @@ -3676,7 +3951,7 @@ def bump_commit( new revision. Four bulk advances moved 295 pins and no version: an advance whose version cannot be read is refused. """ - if _needs_review(report, accept_changed): + if not report.head or _needs_review(report, accept_changed): return False text = path.read_text(encoding="utf-8") if pending_recale(report, accept_changed, text): @@ -3747,7 +4022,7 @@ def bump_commit( new_text = _set_pin(text, document, "source_commit", report.head, "profiled_date") if document.get("pin_follows") and report.head: new_text, expected = _follow_config_reads(new_text, expected, document, report.head) - if upstream_moves: + if upstream_moves and report.upstream_head: expected["upstream_commit"] = report.upstream_head new_text = _set_pin( new_text, document, "upstream_commit", report.upstream_head, "source_commit" @@ -3949,7 +4224,7 @@ def _writing_pins( def _resolve_at( repo: upstream.Repo, sha: str, path: str, cache_dir: str, offline: bool -) -> tuple[str, object]: +) -> tuple[str, tuple[str, list[str]] | str | None]: """("found", (path, lines)) or ("unclear"|"missing", reason). Prose often cites a bare filename. The tree at the revision resolves it @@ -3988,7 +4263,7 @@ def _realign_part( cache_dir: str, offline: bool, pinned: Iterable[tuple[upstream.Repo, str]] = (), -) -> tuple[str, object] | None: +) -> tuple[str, tuple[int, int] | str] | None: """One range, anchored from its writing revision to the current pin. `pinned` lists every declared (repository, current pin). A path no moved @@ -4021,13 +4296,13 @@ def _realign_part( if repo not in moved and (not literal or index < first_moved) ): return None - unclear = None + unclear: tuple[str, list[str]] | str | None = None for repo, written, current in literal or pairs: state, payload = _resolve_at(repo, written, part.path, cache_dir, offline) if state == "unclear": unclear = payload continue - if state == "missing": + if not isinstance(payload, tuple): continue actual, old_lines = payload new_lines = upstream.fetch_file( @@ -4040,7 +4315,7 @@ def _realign_part( ) if anchored.status == "ANCHORED": return None - if anchored.status == "SHIFTED": + if anchored.status == "SHIFTED" and anchored.start is not None and anchored.end is not None: return "ok", (anchored.start, anchored.end) return "skip", f"{part.path}:{part.start} {anchored.status.lower()}" if unclear: @@ -4132,14 +4407,167 @@ def _realign_citation( outcome = next(iter(outcomes.values())) if outcome is None: continue - state, payload = outcome - if state == "ok": + _state, payload = outcome + if isinstance(payload, tuple): moves[index] = (payload[0], payload[1], None) else: blocked.append(payload) return moves, blocked +@dataclass(frozen=True) +class _ProseRepos: + """The repositories prose is read in, as realign_prose reads them.""" + + # (pin field, build mode, repository) for each declared repository. + repos: list[tuple[str, str, upstream.Repo]] + # A source declared gone, read through its mirror. + served: dict[upstream.Repo, upstream.Repo] + # Every declared (repository, current pin). + pinned: list[tuple[upstream.Repo, str]] + + +def _prose_repos(document: dict) -> _ProseRepos | None: + """The repositories the profile's prose is read in, None when it declares none.""" + # Every repository the profile declares, by build mode where it keys + # them so: eka2l1, mesence, supermodel and xemu pin a dict, and reading + # str(dict) found no repository at all, so their prose was never judged. + repos = [ + (field, mode, repo) + for field, mode, url in declared_repositories(document) + if field != "source_mirror" and (repo := upstream.parse_repo(url)) is not None + ] + if not repos: + return None + # A source declared gone is read through its mirror, which carries the + # same commits: teknoparrot's notes stayed blocked once + # teknogods/TeknoParrotUI answered 404, every reading of the old pin + # calling the files absent. + mirror = ( + upstream.parse_repo(str(document.get("source_mirror") or "")) + if document.get("upstream_gone") else None + ) + served = { + repo: mirror for field, _mode, repo in repos + if mirror is not None and field == "source" + } + pinned = [ + (served.get(repo, repo), pin) + for field, mode, repo in repos + if (pin := _pin_of(document, f"{field}_commit", mode)) + ] + return _ProseRepos(repos, served, pinned) + + +@dataclass +class _ProseHistory: + """Where each prose citation came into the profile's history.""" + + # The commit that introduced each citation's text, None when uncommitted. + intro: list[str | None] + revisions: list[tuple[str, dict]] = field(default_factory=list) + # Citations whose writing pin lies past a revision that cannot be read: + # where their text came in is unknown, so they are not moved. + unknown: dict[int, str] = field(default_factory=dict) + + +def _carried_by(past: dict) -> set[tuple[str, str]]: + return { + (c.field, _citation_key(c.ref)) + for c in collect_citations(past) if c.kind == "prose" + } + + +def _date_prose( + path: Path, document: dict, keys: list[tuple[str, str]], history: list[str] +) -> _ProseHistory: + """Follow each citation back through the commits that carry its text.""" + alive = [True] * len(keys) + found = _ProseHistory([None] * len(keys)) + # A revision that does not parse is passed over unless the pins differ + # on its two sides while the citation is absent across it: then the + # text may have come in there under either pin. Otherwise nothing + # it could hold changes the reading. lindbergh-loader + # committed invalid YAML once (df7346b3), fixed the same day, and every + # note older than that commit stayed blocked for good. + gap: str | None = None + for sha in history: + if not any(alive): + break + past = _git_file_at(path, sha) + if past is None: + gap = gap or sha + continue + held = _carried_by(past) + if gap: + newer = found.revisions[-1][1] if found.revisions else document + moved = any( + newer.get(pin) != past.get(pin) + for pin in ("source_commit", "upstream_commit") + ) + for index, live in enumerate(alive): + if live and moved and keys[index] not in held: + found.unknown[index] = gap + alive[index] = False + gap = None + found.revisions.append((sha, past)) + for index, live in enumerate(alive): + if not live: + continue + if keys[index] in held: + found.intro[index] = sha + else: + alive[index] = False + if gap: + # The oldest revisions do not parse: where the text came in is past + # what can be read. + found.unknown.update({index: gap for index, live in enumerate(alive) if live}) + return found + + +def _prose_jobs( + document: dict, + citations: list[Citation], + dated: _ProseHistory, + declared: _ProseRepos, + cache_dir: str, + offline: bool, +) -> tuple[list[str], list[tuple[Citation, dict]]]: + """The moves each dated citation needs, and the messages on the others.""" + messages: list[str] = [] + jobs: list[tuple[Citation, dict]] = [] + for index, citation in enumerate(citations): + if index in dated.unknown: + messages.append( + f"read again: {citation.field}: {citation.ref} " + f"(revision {dated.unknown[index][:8]} unreadable)" + ) + continue + intro_sha = dated.intro[index] + if intro_sha is None: + # The scalar is not committed yet: written now, under this pin. + continue + readings, ambiguous = _writing_pairs( + document, declared.repos, dated.revisions, intro_sha, declared.served + ) + if not any(readings): + continue + moves, blocked = _realign_citation( + citation, readings, ambiguous, cache_dir, offline, declared.pinned + ) + if blocked: + # Half a run must not move: the untouched ranges would read as + # already realigned when they were never even located. + messages.extend( + f"read again: {citation.field}: {citation.ref} ({reason})" + for reason in blocked + ) + continue + if moves: + jobs.append((citation, moves)) + return messages, jobs + + def realign_prose( path: Path, cache_dir: str, offline: bool = False, dry_run: bool = False ) -> list[str]: @@ -4159,33 +4587,9 @@ def realign_prose( citations = [c for c in collect_citations(document) if c.kind == "prose"] if not citations: return [] - # Every repository the profile declares, by build mode where it keys - # them so: eka2l1, mesence, supermodel and xemu pin a dict, and reading - # str(dict) found no repository at all, so their prose was never judged. - repos = [ - (field, mode, repo) - for field, mode, url in declared_repositories(document) - if field != "source_mirror" and (repo := upstream.parse_repo(url)) is not None - ] - if not repos: + declared = _prose_repos(document) + if declared is None: return [] - # A source declared gone is read through its mirror, which carries the - # same commits: teknoparrot's notes stayed blocked once - # teknogods/TeknoParrotUI answered 404, every reading of the old pin - # calling the files absent. - mirror = ( - upstream.parse_repo(str(document.get("source_mirror") or "")) - if document.get("upstream_gone") else None - ) - served = { - repo: mirror for field, _mode, repo in repos - if mirror is not None and field == "source" - } - pinned = [ - (served.get(repo, repo), pin) - for field, mode, repo in repos - if (pin := _pin_of(document, f"{field}_commit", mode)) - ] history = _git_history(path) if history is None: return [f"read again: {path.name}: git history unreadable"] @@ -4197,89 +4601,8 @@ def realign_prose( # from that commit put idtech4a++'s untouched Game.java:69-72 under the # current pin, so the stale range was never offered again. keys = [(c.field, _citation_key(c.ref)) for c in citations] - alive = [True] * len(citations) - intro: list[str | None] = [None] * len(citations) - revisions: list[tuple[str, dict]] = [] - # Citations whose writing pin lies past a revision that cannot be read: - # where their text came in is unknown, so they are not moved. - unknown: dict[int, str] = {} - # A revision that does not parse is passed over unless the pins differ - # on its two sides while the citation is absent across it: then the - # text may have come in there under either pin. Otherwise nothing - # it could hold changes the reading. lindbergh-loader - # committed invalid YAML once (df7346b3), fixed the same day, and every - # note older than that commit stayed blocked for good. - gap: str | None = None - - def carried_by(past: dict) -> set[tuple[str, str]]: - return { - (c.field, _citation_key(c.ref)) - for c in collect_citations(past) if c.kind == "prose" - } - - for sha in history: - if not any(alive): - break - past = _git_file_at(path, sha) - if past is None: - gap = gap or sha - continue - held = carried_by(past) - if gap: - newer = revisions[-1][1] if revisions else document - moved = any( - newer.get(pin) != past.get(pin) - for pin in ("source_commit", "upstream_commit") - ) - for index, live in enumerate(alive): - if live and moved and keys[index] not in held: - unknown[index] = gap - alive[index] = False - gap = None - revisions.append((sha, past)) - for index, live in enumerate(alive): - if not live: - continue - if keys[index] in held: - intro[index] = sha - else: - alive[index] = False - if gap: - # The oldest revisions do not parse: where the text came in is past - # what can be read. - unknown.update({index: gap for index, live in enumerate(alive) if live}) - - messages: list[str] = [] - jobs: list[tuple[Citation, dict]] = [] - for index, citation in enumerate(citations): - if index in unknown: - messages.append( - f"read again: {citation.field}: {citation.ref} " - f"(revision {unknown[index][:8]} unreadable)" - ) - continue - intro_sha = intro[index] - if intro_sha is None: - # The scalar is not committed yet: written now, under this pin. - continue - readings, ambiguous = _writing_pairs( - document, repos, revisions, intro_sha, served - ) - if not any(readings): - continue - moves, blocked = _realign_citation( - citation, readings, ambiguous, cache_dir, offline, pinned - ) - if blocked: - # Half a run must not move: the untouched ranges would read as - # already realigned when they were never even located. - messages.extend( - f"read again: {citation.field}: {citation.ref} ({reason})" - for reason in blocked - ) - continue - if moves: - jobs.append((citation, moves)) + dated = _date_prose(path, document, keys, history) + messages, jobs = _prose_jobs(document, citations, dated, declared, cache_dir, offline) if dry_run: messages.extend( @@ -4700,6 +5023,50 @@ def _backfill( print(f"{name}: source_commit {report.pin[:7]}") +def _write_attributions( + args: argparse.Namespace, name: str, profile: dict, report: ProfileReport, path: Path +) -> None: + if report.skipped: + return + with tempfile.TemporaryDirectory() as scratch: + target = Path(scratch) / path.name + target.write_bytes(path.read_bytes()) + verb = "would attribute " if args.dry_run else "" + for line in attribute_refs(target, report, profile): + print(f"{name}: {verb}{line}") + if not args.dry_run: + path.write_bytes(target.read_bytes()) + + +def _promote( + args: argparse.Namespace, name: str, path: Path, target: Path, moved: bool +) -> bool: + """Write the edited copy over the profile, False when it was put back.""" + original = path.read_bytes() + path.write_bytes(target.read_bytes()) + # The guard above read the prose under the pins the profile held. + # A bump that moves upstream_commit can leave prose the report + # judged in the fork under the new upstream pin (dolphin-mmjr2, + # hatari, xenios): read it again on what was written. It reads + # the profile's own history, so it runs on the real path, and a + # read that fails (offline, rate limit) puts the profile back. + try: + left = realign_prose(path, args.cache_dir, args.offline, dry_run=True) + except BaseException: + path.write_bytes(original) + raise + if moved and left: + path.write_bytes(original) + print( + f"{name}: the bump would leave {len(left)} prose citation(s) " + "under an older pin, nothing was written. Read them first.", + file=sys.stderr, + ) + return False + _WRITTEN.add(name) + return True + + def _apply_writes( args: argparse.Namespace, name: str, profile: dict, report: ProfileReport ) -> None: @@ -4709,16 +5076,7 @@ def _apply_writes( if args.backfill_commits: _backfill(args, name, profile, report, path) if getattr(args, "attribute_refs", False): - if report.skipped: - return - with tempfile.TemporaryDirectory() as scratch: - target = Path(scratch) / path.name - target.write_bytes(path.read_bytes()) - verb = "would attribute " if args.dry_run else "" - for line in attribute_refs(target, report, profile): - print(f"{name}: {verb}{line}") - if not args.dry_run: - path.write_bytes(target.read_bytes()) + _write_attributions(args, name, profile, report, path) return # A backfill has just written a pin: the report's reading predates it. known = None if args.backfill_commits else report.stale_prose @@ -4766,29 +5124,11 @@ def _apply_writes( f"{name}: {bumped}{pin} -> {str(after[pin])[:7]}" for pin in pins_changed(before, after) ] - if not args.dry_run and (applied or moved): - original = path.read_bytes() - path.write_bytes(target.read_bytes()) - # The guard above read the prose under the pins the profile held. - # A bump that moves upstream_commit can leave prose the report - # judged in the fork under the new upstream pin (dolphin-mmjr2, - # hatari, xenios): read it again on what was written. It reads - # the profile's own history, so it runs on the real path, and a - # read that fails (offline, rate limit) puts the profile back. - try: - left = realign_prose(path, args.cache_dir, args.offline, dry_run=True) - except BaseException: - path.write_bytes(original) - raise - if moved and left: - path.write_bytes(original) - print( - f"{name}: the bump would leave {len(left)} prose citation(s) " - "under an older pin, nothing was written. Read them first.", - file=sys.stderr, - ) - return - _WRITTEN.add(name) + if ( + not args.dry_run and (applied or moved) + and not _promote(args, name, path, target, moved) + ): + return for message in messages: print(message) @@ -4952,7 +5292,7 @@ def _attach_version( report.version_warning = version_warning(version, report.pin, relation, passed) or ( f"{'release' if version.latest_release else 'tag'} {newer} is newer than core_version {version.declared} and the pin: " "profile it, or hold the pin with pin_frozen and the reason" - if newer else None + if newer and version else None ) @@ -5409,33 +5749,13 @@ def main() -> None: if writes and not args.dry_run and not args.force: _refuse_dirty_tree(args.emulators_dir, list(selected)) + if args.realign_prose: + _run_realign(args, selected) + return + # A profile that could not be compared or written is not a profile with # nothing to review: it stays in every output and fails the run. failed: set[str] = set() - if args.realign_prose: - for name in selected: - profile_path = Path(args.emulators_dir) / f"{name}.yml" - if not profile_path.is_file(): - continue - try: - before = profile_path.read_bytes() - for line in realign_prose( - profile_path, args.cache_dir, args.offline, args.dry_run - ): - print(f"{name}: {line}") - if profile_path.read_bytes() != before: - _WRITTEN.add(name) - except upstream.UpstreamError as exc: - print(f"{name}: {exc}", file=sys.stderr) - failed.add(name) - except YamlWriteError as exc: - print(f"{name}: write refused: {exc}", file=sys.stderr) - failed.add(name) - _refresh_source_paths(args) - if failed: - raise SystemExit(1) - return - reports: list[ProfileReport] = [] quiet = args.offline or len(selected) < 2 if not quiet: @@ -5472,6 +5792,32 @@ def main() -> None: raise SystemExit(1) +def _run_realign(args: argparse.Namespace, selected: dict) -> None: + """--realign-prose over the selected profiles, exit 1 when one failed.""" + failed: set[str] = set() + for name in selected: + profile_path = Path(args.emulators_dir) / f"{name}.yml" + if not profile_path.is_file(): + continue + try: + before = profile_path.read_bytes() + for line in realign_prose( + profile_path, args.cache_dir, args.offline, args.dry_run + ): + print(f"{name}: {line}") + if profile_path.read_bytes() != before: + _WRITTEN.add(name) + except upstream.UpstreamError as exc: + print(f"{name}: {exc}", file=sys.stderr) + failed.add(name) + except YamlWriteError as exc: + print(f"{name}: write refused: {exc}", file=sys.stderr) + failed.add(name) + _refresh_source_paths(args) + if failed: + raise SystemExit(1) + + def _read_one( args: argparse.Namespace, name: str, diff --git a/scripts/refresh_stale.py b/scripts/refresh_stale.py index 2007e6109..96bc37319 100755 --- a/scripts/refresh_stale.py +++ b/scripts/refresh_stale.py @@ -56,6 +56,7 @@ import re import subprocess import sys import time +from collections.abc import Callable from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait from dataclasses import dataclass from functools import lru_cache @@ -220,7 +221,7 @@ def plan_jobs( for finding in findings: status = finding.get("status") - area = finding.get("area") + area = str(finding.get("area") or "") subject = str(finding.get("subject") or "") if status == "ERROR": @@ -360,6 +361,96 @@ def _export_refresh(platform: str) -> list[str]: return [sys.executable, "scripts/export_native.py", "--platform", platform] +def _platform_command(subject: str, registry: dict[str, dict]) -> list[str] | None: + entry = registry.get(subject) or {} + scraper = entry.get("scraper") + if not scraper: + return None + return [ + sys.executable, + "-m", + f"scripts.scraper.{scraper}_scraper", + "-o", + f"platforms/{subject}.yml", + *(str(a) for a in entry.get("rescrape_args") or ()), + ] + + +def _target_command(subject: str, registry: dict[str, dict]) -> list[str] | None: + # " cores" rows list buildbot names without a profile. No + # scraper fixes that, a human writes `cores:` or _overrides.yml. + if subject.endswith(" cores"): + return None + entry = registry.get(subject) or {} + module = entry.get("target_scraper") + if not module: + return None + return [ + sys.executable, + "-m", + f"scripts.scraper.targets.{module}_scraper", + "-o", + f"platforms/targets/{subject}.yml", + ] + + +def _data_command(subject: str, registry: dict[str, dict]) -> list[str] | None: + if subject not in _data_dir_keys(): + # "_data_dirs.yml" and "buildbot system" name the registry and + # what it does not track yet: a human adds the entry. + return None + return [ + sys.executable, + "scripts/refresh_data_dirs.py", + "--key", + subject, + "--force", + ] + + +def _catalog_command(subject: str, registry: dict[str, dict]) -> list[str] | None: + if subject == "mame recipes": + return [ + sys.executable, + "-m", + "scripts.scraper.romset_dat_importer", + "--source", + "mame", + "--fetch", + ] + if subject == "fbneo recipes": + return [ + sys.executable, + "-m", + "scripts.scraper.romset_dat_importer", + "--source", + "fbneo", + "--fetch", + ] + if subject in ("no-intro games", "redump games"): + # The game DATs download without a browser, unlike the BIOS ones. + return [ + sys.executable, + "-m", + "scripts.scraper.game_dat_importer", + "--source", + subject.split()[0], + "--fetch", + "--refresh", + "--floor", + ] + # redump / no-intro / tosec need manual DAT download. + return None + + +_AREA_COMMANDS: dict[str, Callable[[str, dict[str, dict]], list[str] | None]] = { + "platforms": _platform_command, + "targets": _target_command, + "data": _data_command, + "catalogs": _catalog_command, +} + + def _command_for( area: str, subject: str, registry: dict[str, dict] ) -> list[str] | None: @@ -369,87 +460,13 @@ def _command_for( # truth comes first and the original follows (Job.then). return _truth_refresh(subject) - if area == "platforms": - entry = registry.get(subject) or {} - scraper = entry.get("scraper") - if not scraper: - return None - return [ - sys.executable, - "-m", - f"scripts.scraper.{scraper}_scraper", - "-o", - f"platforms/{subject}.yml", - *(str(a) for a in entry.get("rescrape_args") or ()), - ] - - if area == "targets": - # " cores" rows list buildbot names without a profile. No - # scraper fixes that, a human writes `cores:` or _overrides.yml. - if subject.endswith(" cores"): - return None - entry = registry.get(subject) or {} - module = entry.get("target_scraper") - if not module: - return None - return [ - sys.executable, - "-m", - f"scripts.scraper.targets.{module}_scraper", - "-o", - f"platforms/targets/{subject}.yml", - ] - - if area == "data": - if subject not in _data_dir_keys(): - # "_data_dirs.yml" and "buildbot system" name the registry and - # what it does not track yet: a human adds the entry. - return None - return [ - sys.executable, - "scripts/refresh_data_dirs.py", - "--key", - subject, - "--force", - ] - if area == "ci" and subject == "install.py pin": # The pin is the hash of the committed install.py, nothing to judge. return [sys.executable, "scripts/pin_installer.py"] - if area == "catalogs": - if subject == "mame recipes": - return [ - sys.executable, - "-m", - "scripts.scraper.romset_dat_importer", - "--source", - "mame", - "--fetch", - ] - if subject == "fbneo recipes": - return [ - sys.executable, - "-m", - "scripts.scraper.romset_dat_importer", - "--source", - "fbneo", - "--fetch", - ] - if subject in ("no-intro games", "redump games"): - # The game DATs download without a browser, unlike the BIOS ones. - return [ - sys.executable, - "-m", - "scripts.scraper.game_dat_importer", - "--source", - subject.split()[0], - "--fetch", - "--refresh", - "--floor", - ] - # redump / no-intro / tosec need manual DAT download. - return None + builder = _AREA_COMMANDS.get(area) + if builder: + return builder(subject, registry) # coreinfo, ci, profiles: never auto-refresh. return None diff --git a/scripts/region_check.py b/scripts/region_check.py index b33bbf77e..a9ee7c49c 100644 --- a/scripts/region_check.py +++ b/scripts/region_check.py @@ -91,8 +91,7 @@ def plan_variants(entries: Iterable[dict], region: str, local: Callable[[dict], Path | None]) -> dict[str, dict[str, Path]]: """The staged files of `full`, `own` and `others`, dest -> file. An entry the collection does not hold is left out of every variant.""" - held = [(entry, local(entry)) for entry in entries] - held = [(entry, path) for entry, path in held if path] + held = [(entry, path) for entry in entries if (path := local(entry))] full = {entry_dest(e): p for e, p in held} own = {entry_dest(e): p for e, p in held if region in regions_of(e)} others = {entry_dest(e): p for e, p in held if region not in regions_of(e)} diff --git a/scripts/release_notes.py b/scripts/release_notes.py index db3572ed2..d0541f49f 100644 --- a/scripts/release_notes.py +++ b/scripts/release_notes.py @@ -53,12 +53,6 @@ SITE = "https://abdess.github.io/retrobios/" HANDHELD_PAGE = "wiki/installer/#on-a-handheld-the-retrobios-port" -def _size(count: int) -> str: - if count >= 1024**3: - return f"{count / 1024**3:.1f} GB" - return f"{count / 1024**2:.0f} MB" - - def _display(pack: str) -> str: """RetroArch_Lakka_v1.22.2_BIOS_Pack.zip reads as RetroArch Lakka v1.22.2.""" return pack.split("_BIOS_Pack", 1)[0].replace("_", " ") @@ -273,7 +267,7 @@ def render(record: dict, platforms_dir: str, whats_new: str, folder = folders.get(name) lines.append( f"| {_display(name)} | {_link(pack, tag)} |" - f" {_size(pack['extracted_size'])} | {pack['files']:,} |" + f" {release_record.size_text(pack['extracted_size'])} | {pack['files']:,} |" f" {f'`{folder}`' if folder else '-'} |" ) lines += [ diff --git a/scripts/release_record.py b/scripts/release_record.py index 6a064d60f..c36b1a920 100644 --- a/scripts/release_record.py +++ b/scripts/release_record.py @@ -196,7 +196,7 @@ def manifest_mismatches(record: dict, install_dir: str | Path) -> list[str]: return found -def _size(count: int) -> str: +def size_text(count: int) -> str: if count >= 1024**3: return f"{count / 1024**3:.1f} GB" return f"{count / 1024**2:.0f} MB" @@ -230,8 +230,8 @@ def main() -> int: return 1 for name, pack in record["packs"].items(): print( - f"{name:<44} download {_size(pack['download_size']):>8}" - f" extracted {_size(pack['extracted_size']):>8}" + f"{name:<44} download {size_text(pack['download_size']):>8}" + f" extracted {size_text(pack['extracted_size']):>8}" f" {pack['files']:,} files {len(pack['assets'])} asset(s)" ) mismatches = manifest_mismatches(record, args.install_dir) diff --git a/scripts/romdir.py b/scripts/romdir.py index 9504a4e58..180727ed1 100644 --- a/scripts/romdir.py +++ b/scripts/romdir.py @@ -57,6 +57,23 @@ def _name_is(name: bytes, wanted: bytes, compared: int) -> bool: return True +def _after_reset(data: bytes, reset_compare: int, missing_reset: str) -> int | None: + """The offset past the RESET entry, or past the last entry searched when + the walk goes on without one, None where the code gives up.""" + pos = 0 + for _ in range(SEARCH_ENTRIES): + if pos + ENTRY_SIZE > len(data): + return None + name = data[pos:pos + NAME_SIZE] + pos += ENTRY_SIZE + if _name_is(name, b"RESET", reset_compare): + break + else: + if missing_reset == REJECT: + return None + return pos + + def walk(data: bytes, spec: dict) -> Romdir | None: """The ROM directory walk one fork's LoadBiosVersion runs, or None. @@ -84,18 +101,10 @@ def walk(data: bytes, spec: dict) -> Romdir | None: missing_reset = spec.get("missing_reset", ENDS_WALK) offset_mask = (1 << int(spec.get("offset_width", 64))) - 1 - pos = 0 - for _ in range(SEARCH_ENTRIES): - if pos + ENTRY_SIZE > size: - return None - name = data[pos:pos + NAME_SIZE] - pos += ENTRY_SIZE - if _name_is(name, b"RESET", reset_compare): - break - else: - if missing_reset == REJECT: - return None - + found = _after_reset(data, reset_compare, missing_reset) + if found is None: + return None + pos = found entry = data[pos - ENTRY_SIZE:pos] offset = 0 romver: bytes | None = None diff --git a/scripts/scraper/__init__.py b/scripts/scraper/__init__.py index 00868fe76..02cec78a7 100644 --- a/scripts/scraper/__init__.py +++ b/scripts/scraper/__init__.py @@ -17,11 +17,10 @@ from pathlib import Path # they share helpers with the rest of scripts/. Putting that directory on the # path once here is what lets every submodule say `from common import ...` # instead of carrying its own bootstrap. -_SCRIPTS_DIR = str(Path(__file__).resolve().parent.parent) -if _SCRIPTS_DIR not in sys.path: +if (_SCRIPTS_DIR := str(Path(__file__).resolve().parent.parent)) not in sys.path: sys.path.insert(0, _SCRIPTS_DIR) -from .base_scraper import BaseScraper # noqa: E402 +from .base_scraper import BaseScraper _scrapers: dict[str, type] = {} @@ -33,7 +32,7 @@ def discover_scrapers() -> dict[str, type]: package_dir = Path(__file__).parent - for finder, name, ispkg in pkgutil.iter_modules([str(package_dir)]): + for _finder, name, _ispkg in pkgutil.iter_modules([str(package_dir)]): if not name.endswith("_scraper"): continue diff --git a/scripts/scraper/_hash_merge.py b/scripts/scraper/_hash_merge.py index b83531a83..4ce66daba 100644 --- a/scripts/scraper/_hash_merge.py +++ b/scripts/scraper/_hash_merge.py @@ -461,6 +461,82 @@ def _patch_scalar(text: str, key: str, value: str) -> str: ) +def _owned_end(lines: list[str], start_line: int) -> int: + """The last "owned" line of the entry starting at start_line. + + Owned = indented with 4+ spaces (field lines of this entry). + """ + last_owned = start_line + for j in range(start_line + 1, len(lines)): + stripped = lines[j].strip() + if not stripped: + break # blank line = end of entry + if stripped.startswith("#"): + break # comment = belongs to next entry + if re.match(r"^ - ", lines[j]): + break # next list item + if re.match(r"^ ", lines[j]) or re.match(r"^ \w", lines[j]): + last_owned = j + else: + break + return last_owned + + +def _patch_source_ref(lines: list[str], start_line: int, last_owned: int, source_ref: str) -> int: + """Patch source_ref in-place, or add it. Returns the new last owned line.""" + for j in range(start_line + 1, last_owned + 1): + if re.match(r"^ source_ref:", lines[j]): + lines[j] = f' source_ref: "{source_ref}"' + return last_owned + lines.insert(last_owned + 1, f' source_ref: "{source_ref}"') + return last_owned + 1 + + +def _drop_contents(lines: list[str], start_line: int, last_owned: int) -> int: + """Remove an existing contents block. Returns the new last owned line.""" + contents_start = None + contents_end = None + for j in range(start_line + 1, last_owned + 1): + if re.match(r"^ contents:", lines[j]): + contents_start = j + elif contents_start is not None: + if re.match(r"^ ", lines[j]): + contents_end = j + else: + break + if contents_start is None: + return last_owned + if contents_end is None: + contents_end = contents_start + del lines[contents_start : contents_end + 1] + return last_owned - (contents_end - contents_start + 1) + + +def _patch_entry(lines: list[str], start_line: int, fe: dict) -> None: + contents = fe.get("contents", []) + source_ref = fe.get("source_ref", "") + + last_owned = _owned_end(lines, start_line) + + if source_ref: + last_owned = _patch_source_ref(lines, start_line, last_owned, source_ref) + + # The source settles required for a set the machine runs without + if "required" in fe: + for j in range(start_line + 1, last_owned + 1): + if re.match(r"^ required:", lines[j]): + lines[j] = f" required: {str(fe['required']).lower()}" + break + + last_owned = _drop_contents(lines, start_line, last_owned) + + # Insert new contents after last owned line + if contents: + new_lines = _format_contents(contents).split("\n") + for k, cl in enumerate(new_lines): + lines.insert(last_owned + 1 + k, cl) + + def _patch_bios_entries(text: str, files: list[dict]) -> str: """Patch contents, source_ref and required of bios_zip entries in-place. @@ -469,8 +545,6 @@ def _patch_bios_entries(text: str, files: list[dict]) -> str: lines that follow (4+ spaces), stopping at blank lines, comments, or the next `- name:`. """ - import re - patches: dict[str, dict] = {} for fe in files: if fe.get("category") != "bios_zip": @@ -491,71 +565,8 @@ def _patch_bios_entries(text: str, files: list[dict]) -> str: # Process in reverse so line insertions don't shift indices for idx in range(len(entry_starts) - 1, -1, -1): start_line, entry_name = entry_starts[idx] - if entry_name not in patches: - continue - - fe = patches[entry_name] - contents = fe.get("contents", []) - source_ref = fe.get("source_ref", "") - - # Find the last "owned" line of this entry - # Owned = indented with 4+ spaces (field lines of this entry) - last_owned = start_line - for j in range(start_line + 1, len(lines)): - stripped = lines[j].strip() - if not stripped: - break # blank line = end of entry - if stripped.startswith("#"): - break # comment = belongs to next entry - if re.match(r"^ - ", lines[j]): - break # next list item - if re.match(r"^ ", lines[j]) or re.match(r"^ \w", lines[j]): - last_owned = j - else: - break - - # Patch source_ref in-place - if source_ref: - found_sr = False - for j in range(start_line + 1, last_owned + 1): - if re.match(r"^ source_ref:", lines[j]): - lines[j] = f' source_ref: "{source_ref}"' - found_sr = True - break - if not found_sr: - lines.insert(last_owned + 1, f' source_ref: "{source_ref}"') - last_owned += 1 - - # The source settles required for a set the machine runs without - if "required" in fe: - for j in range(start_line + 1, last_owned + 1): - if re.match(r"^ required:", lines[j]): - lines[j] = f" required: {str(fe['required']).lower()}" - break - - # Remove existing contents block if present - contents_start = None - contents_end = None - for j in range(start_line + 1, last_owned + 1): - if re.match(r"^ contents:", lines[j]): - contents_start = j - elif contents_start is not None: - if re.match(r"^ ", lines[j]): - contents_end = j - else: - break - if contents_end is None and contents_start is not None: - contents_end = contents_start - - if contents_start is not None: - del lines[contents_start : contents_end + 1] - last_owned -= contents_end - contents_start + 1 - - # Insert new contents after last owned line - if contents: - new_lines = _format_contents(contents).split("\n") - for k, cl in enumerate(new_lines): - lines.insert(last_owned + 1 + k, cl) + if entry_name in patches: + _patch_entry(lines, start_line, patches[entry_name]) return "\n".join(lines) diff --git a/scripts/scraper/amberelec_launchers.py b/scripts/scraper/amberelec_launchers.py index f4f7819a0..feeb59230 100644 --- a/scripts/scraper/amberelec_launchers.py +++ b/scripts/scraper/amberelec_launchers.py @@ -21,28 +21,16 @@ import re from collections.abc import Callable from typing import Any -try: - from .configgen_launchers import Launcher, Source - from .shell_launchers import ( - LauncherPatternMissing, - Script, - config_placement, - describe_keys, - evidence_fields, - settings, - source_ref, - ) -except ImportError: - from configgen_launchers import Launcher, Source # type: ignore[no-redef] - from shell_launchers import ( # type: ignore[no-redef] - LauncherPatternMissing, - Script, - config_placement, - describe_keys, - evidence_fields, - settings, - source_ref, - ) +from .configgen_launchers import Launcher, Source +from .shell_launchers import ( + LauncherPatternMissing, + Script, + config_placement, + describe_keys, + evidence_fields, + settings, + source_ref, +) BIOS = "/storage/roms/bios" RUNEMU = "packages/amberelec/sources/scripts/runemu.py" diff --git a/scripts/scraper/arcade_parent_importer.py b/scripts/scraper/arcade_parent_importer.py index 952847e30..da9a231c3 100644 --- a/scripts/scraper/arcade_parent_importer.py +++ b/scripts/scraper/arcade_parent_importer.py @@ -37,8 +37,8 @@ from __future__ import annotations import argparse import ast +import functools import hashlib -import io import json import re import sys @@ -48,6 +48,7 @@ from collections import Counter from collections.abc import Callable, Iterator from dataclasses import dataclass, field from pathlib import Path +from typing import IO from ..artifacts import write_if_changed from ..common import load_emulator_profiles, run_cli @@ -137,7 +138,7 @@ def _attrs(raw: bytes) -> dict[str, str]: return {k.decode(): v.decode() for k, v in _ATTR.findall(raw)} -def iter_sets(stream: io.BufferedIOBase) -> Iterator[SetEntry]: +def iter_sets(stream: IO[bytes]) -> Iterator[SetEntry]: """Every machine or game element of a DAT or -listxml, streamed. Attributes come in any order (mame2003 writes `` def fbneo_sets( - openers: list[Callable[[], io.BufferedIOBase]], names: dict[str, set[str]] + openers: list[Callable[[], IO[bytes]]], names: dict[str, set[str]] ) -> tuple[dict[str, SetEntry], dict[str, str]]: """Every set of FBNeo's DATs keyed by its driver, and the archive of each set whose driver name is not its archive name. @@ -634,55 +635,72 @@ class _Preprocessor: out.append(line) continue word, rest = directive.groups() - if word in ("if", "ifdef", "ifndef"): - if not active: - stack.append((False, True, False)) - continue - if word == "if": - value = bool(_condition_value(rest, defines)) - else: - value = (rest.split()[0] in defines) == (word == "ifdef") - stack.append((True, value, value)) - active = value - elif word in ("elif", "else"): - if not stack: - raise DriverSourceError(f"{path}: #{word} without #if") - outer, taken, _ = stack[-1] - value = ( - outer and not taken - and (word == "else" or bool(_condition_value(rest, defines))) - ) - stack[-1] = (outer, taken or value, value) - active = value - elif word == "endif": - if not stack: - raise DriverSourceError(f"{path}: #endif without #if") - stack.pop() - active = stack[-1][2] if stack else True - elif not active: - continue - elif word == "define": - head = _MACRO_HEAD.match(rest) - if head: - defines[head.group(1)] = head.group(3) - if local is not None: - params = head.group(2) - local[head.group(1)] = ( - [a.strip() for a in params[1:-1].split(",")] if params else None, - head.group(3), - ) - elif word == "undef": - defines.pop(rest.strip(), None) - elif word == "include": - target = _INCLUDE.match(rest) - header = self._resolve(target.group(1), path) if target else None - if header and header not in seen: - seen.add(header) - self.run(header, self.headers[header], defines, None, seen) + if word in _CONDITIONALS: + active = _branch(path, word, rest, defines, stack, active) + elif active: + self._define(path, word, rest, defines, local, seen) if stack: raise DriverSourceError(f"{path}: #if without #endif") return "\n".join(out) + def _define( + self, path: str, word: str, rest: str, defines: dict[str, str], + local: dict[str, tuple[list[str] | None, str]] | None, seen: set[str], + ) -> None: + """#define, #undef and #include in an active region.""" + if word == "define": + head = _MACRO_HEAD.match(rest) + if head: + defines[head.group(1)] = head.group(3) + if local is not None: + params = head.group(2) + local[head.group(1)] = ( + [a.strip() for a in params[1:-1].split(",")] if params else None, + head.group(3), + ) + elif word == "undef": + defines.pop(rest.strip(), None) + elif word == "include": + target = _INCLUDE.match(rest) + header = self._resolve(target.group(1), path) if target else None + if header and header not in seen: + seen.add(header) + self.run(header, self.headers[header], defines, None, seen) + + +_CONDITIONALS = frozenset({"if", "ifdef", "ifndef", "elif", "else", "endif"}) + + +def _branch( + path: str, word: str, rest: str, defines: dict[str, str], + stack: list[tuple[bool, bool, bool]], active: bool, +) -> bool: + """Apply one conditional directive to *stack*. Returns the new active state.""" + if word in ("if", "ifdef", "ifndef"): + if not active: + stack.append((False, True, False)) + return active + if word == "if": + value = bool(_condition_value(rest, defines)) + else: + value = (rest.split()[0] in defines) == (word == "ifdef") + stack.append((True, value, value)) + return value + if word in ("elif", "else"): + if not stack: + raise DriverSourceError(f"{path}: #{word} without #if") + outer, taken, _ = stack[-1] + value = ( + outer and not taken + and (word == "else" or bool(_condition_value(rest, defines))) + ) + stack[-1] = (outer, taken or value, value) + return value + if not stack: + raise DriverSourceError(f"{path}: #endif without #if") + stack.pop() + return stack[-1][2] if stack else True + def _dumped(args: list[str]) -> bool: """A ROM_LOAD whose ROM was dumped: 0.78 writes ``NO_DUMP`` in the hash @@ -693,6 +711,10 @@ def _dumped(args: list[str]) -> bool: return not re.fullmatch(r"0[xX]0+|0", crc.strip()) +def _argument(values: dict[str, str], match: re.Match[str]) -> str: + return values.get(match.group(0), match.group(0)) + + def _expand_declarations(text: str, local: dict[str, tuple[list[str] | None, str]]) -> str: """Calls of a file's own function-like macros that write a ROM_START or a GAME line, expanded (pgm.c builds every DoDonPachi II set through @@ -716,7 +738,7 @@ def _expand_declarations(text: str, local: dict[str, tuple[list[str] | None, str raise DriverSourceError(f"{match.group(1)} called with {len(args)} arguments") values = dict(zip(params, args)) out.append(text[position : match.start()]) - out.append(_IDENTIFIER.sub(lambda m: values.get(m.group(0), m.group(0)), body)) + out.append(_IDENTIFIER.sub(functools.partial(_argument, values), body)) position = end out.append(text[position:]) return "".join(out) @@ -732,6 +754,50 @@ def compiled_drivers(driver_c: str, preprocessor: _Preprocessor) -> list[str]: return [n for n in _DRIVER_ENTRY.findall(text) if n != "NAME"] +def _holds_roms( + body: str, local: dict[str, tuple[list[str] | None, str]], known: dict[str, bool], + seen: frozenset[str] = frozenset(), +) -> bool: + for match in _ROM_LOAD.finditer(body): + if _dumped(_call_args(body, match.end())): + return True + # A ROM list shared through a macro of the same file (a BIOS + # block every game of the board pulls in). + for word in set(_IDENTIFIER.findall(body)) - seen: + if word in local: + if word not in known: + known[word] = _holds_roms(local[word][1], local, known, seen | {word}) + if known[word]: + return True + return False + + +def _read_driver( + path: str, source: str, preprocessor: _Preprocessor, + declared: dict[str, tuple[str | None, bool]], roms: dict[str, tuple[bool, bool]], +) -> None: + """The ROM_START blocks and GAME declarations of one driver file.""" + local: dict[str, tuple[list[str] | None, str]] = {} + text = _expand_declarations(preprocessor.run(path, source, {}, local, set()), local) + known: dict[str, bool] = {} + for match in _ROM_START.finditer(text): + body = match.group(2) + roms.setdefault( + match.group(1), (_holds_roms(body, local, known), bool(_DISK_IMAGE.search(body))) + ) + for match in _GAME_MACRO.finditer(text): + args = _call_args(text, match.end()) + if len(args) < 9: + raise DriverSourceError(f"{path}: {match.group(1)} with {len(args)} arguments") + name, parent = args[1], args[2] + if name in declared: + raise DriverSourceError(f"{path}: {name} declared twice") + declared[name] = ( + None if parent == "0" else parent, + any("NOT_A_DRIVER" in a for a in args[3:]), + ) + + def driver_source_sets( driver_c: str, drivers: dict[str, str], headers: dict[str, str] ) -> dict[str, SetEntry]: @@ -746,38 +812,7 @@ def driver_source_sets( declared: dict[str, tuple[str | None, bool]] = {} roms: dict[str, tuple[bool, bool]] = {} for path, source in sorted(drivers.items()): - local: dict[str, tuple[list[str] | None, str]] = {} - text = _expand_declarations(preprocessor.run(path, source, {}, local, set()), local) - known: dict[str, bool] = {} - - def holds_roms(body: str, seen: frozenset[str] = frozenset()) -> bool: - for match in _ROM_LOAD.finditer(body): - if _dumped(_call_args(body, match.end())): - return True - # A ROM list shared through a macro of the same file (a BIOS - # block every game of the board pulls in). - for word in set(_IDENTIFIER.findall(body)) - seen: - if word in local: - if word not in known: - known[word] = holds_roms(local[word][1], seen | {word}) - if known[word]: - return True - return False - - for match in _ROM_START.finditer(text): - body = match.group(2) - roms.setdefault(match.group(1), (holds_roms(body), bool(_DISK_IMAGE.search(body)))) - for match in _GAME_MACRO.finditer(text): - args = _call_args(text, match.end()) - if len(args) < 9: - raise DriverSourceError(f"{path}: {match.group(1)} with {len(args)} arguments") - name, parent = args[1], args[2] - if name in declared: - raise DriverSourceError(f"{path}: {name} declared twice") - declared[name] = ( - None if parent == "0" else parent, - any("NOT_A_DRIVER" in a for a in args[3:]), - ) + _read_driver(path, source, preprocessor, declared, roms) compiled = compiled_drivers(driver_c, preprocessor) undeclared = [n for n in compiled if n not in declared] if undeclared: @@ -973,7 +1008,11 @@ def _cached_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tup return destination, git_blob_sha(destination.read_bytes()) -def _xml_streams(path: Path) -> Iterator[Callable[[], io.BufferedIOBase]]: +def _file_opener(path: Path) -> Callable[[], IO[bytes]]: + return lambda: path.open("rb") + + +def _xml_streams(path: Path) -> Iterator[Callable[[], IO[bytes]]]: """Openers for the XML documents a file holds: itself, or each XML or DAT member of a ZIP.""" if path.suffix.lower() != ".zip": @@ -984,16 +1023,15 @@ def _xml_streams(path: Path) -> Iterator[Callable[[], io.BufferedIOBase]]: n for n in archive.namelist() if n.lower().endswith((".xml", ".dat")) ) for member in names: - def opener(member: str = member) -> io.BufferedIOBase: - archive = zipfile.ZipFile(path) - stream = archive.open(member) - stream.close_archive = archive # keep the archive alive - return stream + def opener(member: str = member) -> IO[bytes]: + # The member keeps the archive alive: its shared file closes + # through the archive's own _fpclose. + return zipfile.ZipFile(path).open(member) yield opener -def read_sets(openers: list[Callable[[], io.BufferedIOBase]]) -> dict[str, SetEntry]: +def read_sets(openers: list[Callable[[], IO[bytes]]]) -> dict[str, SetEntry]: """Every set of several documents. A set read twice keeps its first reading: FBNeo's Arcade and Neogeo DATs both carry the neogeo BIOS.""" sets: dict[str, SetEntry] = {} @@ -1024,6 +1062,8 @@ def import_profile( commit = str(data.get("source_commit") or "") source_url = str(data.get("source") or "") kind = spec["kind"] + source: dict[str, object] + openers: list[Callable[[], IO[bytes]]] if kind == "listxml": tag = "mame" + str(data["core_version"]).replace(".", "").zfill(4) if offline: @@ -1060,9 +1100,7 @@ def import_profile( FBNEO_DRIVERLIST: listing_sha, }, } - openers = [ - (lambda p=folder / name: p.open("rb")) for name in sorted(blobs) - ] + openers = [_file_opener(folder / name) for name in sorted(blobs)] sets, archives = fbneo_sets(openers, fbneo_drivers(listing.read_text(encoding="utf-8"))) index = build_index(sets, spec["marker"], archives) elif kind == "source": diff --git a/scripts/scraper/base_scraper.py b/scripts/scraper/base_scraper.py index dcda281de..e81a2515e 100644 --- a/scripts/scraper/base_scraper.py +++ b/scripts/scraper/base_scraper.py @@ -2,6 +2,7 @@ from __future__ import annotations +import argparse import inspect import json import re @@ -14,7 +15,7 @@ import yaml from abc import ABC, abstractmethod from dataclasses import dataclass, field from pathlib import Path -from typing import Callable, NoReturn +from typing import Callable, NoReturn, Protocol from common import github_token, write_text_atomic, yaml_load @@ -130,12 +131,16 @@ def requirement_entry(req: BiosRequirement) -> dict: return entry -def _read_limited(resp: object, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes: +class _Readable(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + + +def _read_limited(resp: _Readable, max_bytes: int = MAX_RESPONSE_SIZE) -> bytes: """Read an HTTP response with a size limit to prevent OOM.""" chunks: list[bytes] = [] total = 0 while True: - chunk = resp.read(65536) # type: ignore[union-attr] + chunk = resp.read(65536) if not chunk: break total += len(chunk) @@ -382,12 +387,114 @@ def _exit_on_scrape_error(error: Exception) -> NoReturn: sys.exit(1) +def _print_dry_run(reqs: list[BiosRequirement]) -> None: + by_system: dict[str, list] = {} + for req in reqs: + by_system.setdefault(req.system, []).append(req) + for system, files in sorted(by_system.items()): + req_count = sum(1 for f in files if f.required) + opt_count = len(files) - req_count + print(f" {system}: {req_count} required, {opt_count} optional") + print(f"\nTotal: {len(reqs)} BIOS entries across {len(by_system)} systems") + + +def _print_json(reqs: list[BiosRequirement]) -> None: + data = [ + { + "name": r.name, + "system": r.system, + "sha1": r.sha1, + "md5": r.md5, + "size": r.size, + "required": r.required, + } + for r in reqs + ] + print(json.dumps(data, indent=2)) + + +def _generic_config(reqs: list[BiosRequirement]) -> dict: + """Generic fallback: just systems from requirements.""" + config: dict = {"systems": {}} + for req in reqs: + sys_id = req.system + if sys_id not in config["systems"]: + sys_entry: dict = {"files": []} + if req.native_id: + sys_entry["native_id"] = req.native_id + config["systems"][sys_id] = sys_entry + entry = { + "name": req.name, + "destination": req.destination or req.name, + "required": req.required, + } + if req.sha1: + entry["sha1"] = req.sha1 + if req.md5: + entry["md5"] = req.md5 + if req.zipped_file: + entry["zipped_file"] = req.zipped_file + config["systems"][sys_id]["files"].append(entry) + return config + + +def _keep_existing(config: dict, output_path: Path) -> None: + """Merge into existing YAML: preserve fields the scraper doesn't generate + (data_directories, case_insensitive_fs, manually added metadata). + The scraper replaces systems + files, everything else is preserved.""" + with open(output_path) as f: + existing = yaml_load(f) or {} + # Preserve existing keys not generated by the scraper. + # Only keys present in the NEW config are considered scraper-generated. + # Everything else in the existing file is preserved. + for key, val in existing.items(): + if key not in config: + config[key] = val + # Preserve per-system fields not generated by the scraper + # (data_directories, native_id from manual additions, etc.) + existing_systems = existing.get("systems", {}) + for sys_id, sys_data in config.get("systems", {}).items(): + old_sys = existing_systems.get(sys_id, {}) + for field_name in ("data_directories",): + if field_name in old_sys and field_name not in sys_data: + sys_data[field_name] = old_sys[field_name] + + +def _write_output( + scraper: BaseScraper, scraper_class: type, reqs: list[BiosRequirement], output: str +) -> None: + # Use scraper's generate_platform_yaml() if available (includes + # platform metadata, cores list, standalone_cores, etc.) + generate = getattr(scraper, "generate_platform_yaml", None) + if generate is not None: + try: + config = generate() + except (OSError, ValueError, RuntimeError) as e: + _exit_on_scrape_error(e) + else: + config = _generic_config(reqs) + if scraper.lists_files and not any( + (system or {}).get("files") for system in (config.get("systems") or {}).values() + ): + _exit_on_scrape_error(RuntimeError( + f"{scraper_class.__module__}: the generated platform lists no file" + )) + output_path = Path(output) + if output_path.exists(): + _keep_existing(config, output_path) + # Written whole or not at all: a reader in the middle of a streamed + # dump parsed a valid platform with a fraction of its systems. + write_text_atomic(output_path, yaml.dump( + config, Dumper=_PlatformDumper, + default_flow_style=False, allow_unicode=True, sort_keys=False, + )) + print(f"Written {len(reqs)} entries to {output}") + + def scraper_cli( scraper_class: type, description: str = "Scrape BIOS requirements" ) -> None: """Shared CLI entry point for all scrapers. Eliminates main() boilerplate.""" - import argparse - parser = argparse.ArgumentParser(allow_abbrev=False, description=description) parser.add_argument("--dry-run", action="store_true", help="Show scraped data") parser.add_argument("--output", "-o", help="Output YAML file") @@ -413,100 +520,13 @@ def scraper_cli( )) if args.dry_run: - by_system: dict[str, list] = {} - for req in reqs: - by_system.setdefault(req.system, []).append(req) - for system, files in sorted(by_system.items()): - req_count = sum(1 for f in files if f.required) - opt_count = len(files) - req_count - print(f" {system}: {req_count} required, {opt_count} optional") - print(f"\nTotal: {len(reqs)} BIOS entries across {len(by_system)} systems") - return - - if args.json: - data = [ - { - "name": r.name, - "system": r.system, - "sha1": r.sha1, - "md5": r.md5, - "size": r.size, - "required": r.required, - } - for r in reqs - ] - print(json.dumps(data, indent=2)) - return - - if args.output: - import yaml - - # Use scraper's generate_platform_yaml() if available (includes - # platform metadata, cores list, standalone_cores, etc.) - if hasattr(scraper, "generate_platform_yaml"): - try: - config = scraper.generate_platform_yaml() - except (OSError, ValueError, RuntimeError) as e: - _exit_on_scrape_error(e) - else: - # Generic fallback: just systems from requirements - config = {"systems": {}} - for req in reqs: - sys_id = req.system - if sys_id not in config["systems"]: - sys_entry: dict = {"files": []} - if req.native_id: - sys_entry["native_id"] = req.native_id - config["systems"][sys_id] = sys_entry - entry = { - "name": req.name, - "destination": req.destination or req.name, - "required": req.required, - } - if req.sha1: - entry["sha1"] = req.sha1 - if req.md5: - entry["md5"] = req.md5 - if req.zipped_file: - entry["zipped_file"] = req.zipped_file - config["systems"][sys_id]["files"].append(entry) - if scraper.lists_files and not any( - (system or {}).get("files") for system in (config.get("systems") or {}).values() - ): - _exit_on_scrape_error(RuntimeError( - f"{scraper_class.__module__}: the generated platform lists no file" - )) - # Merge into existing YAML: preserve fields the scraper doesn't generate - # (data_directories, case_insensitive_fs, manually added metadata). - # The scraper replaces systems + files, everything else is preserved. - output_path = Path(args.output) - if output_path.exists(): - with open(output_path) as f: - existing = yaml_load(f) or {} - # Preserve existing keys not generated by the scraper. - # Only keys present in the NEW config are considered scraper-generated. - # Everything else in the existing file is preserved. - for key, val in existing.items(): - if key not in config: - config[key] = val - # Preserve per-system fields not generated by the scraper - # (data_directories, native_id from manual additions, etc.) - existing_systems = existing.get("systems", {}) - for sys_id, sys_data in config.get("systems", {}).items(): - old_sys = existing_systems.get(sys_id, {}) - for field in ("data_directories",): - if field in old_sys and field not in sys_data: - sys_data[field] = old_sys[field] - # Written whole or not at all: a reader in the middle of a streamed - # dump parsed a valid platform with a fraction of its systems. - write_text_atomic(output_path, yaml.dump( - config, Dumper=_PlatformDumper, - default_flow_style=False, allow_unicode=True, sort_keys=False, - )) - print(f"Written {len(reqs)} entries to {args.output}") - return - - print(f"Scraped {len(reqs)} requirements. Use --dry-run, --json, or --output.") + _print_dry_run(reqs) + elif args.json: + _print_json(reqs) + elif args.output: + _write_output(scraper, scraper_class, reqs, args.output) + else: + print(f"Scraped {len(reqs)} requirements. Use --dry-run, --json, or --output.") def fetch_github_latest_tag(repo: str, prefix: str = "") -> str: diff --git a/scripts/scraper/batocera_launchers.py b/scripts/scraper/batocera_launchers.py index b336287c3..4216783ba 100644 --- a/scripts/scraper/batocera_launchers.py +++ b/scripts/scraper/batocera_launchers.py @@ -15,6 +15,7 @@ launcher looks for nothing". from __future__ import annotations import ast +import posixpath import re from collections.abc import Callable, Iterable from typing import Any @@ -23,6 +24,8 @@ from .configgen_launchers import ( Launcher, LauncherShapeError, Source, + assigned_value, + end_line, _assigned_name, _calls, _enclosing_test, @@ -56,7 +59,7 @@ def _config_option(node: ast.AST) -> tuple[str, Any] | None: return None second = node.args[1] if len(node.args) > 1 else None default = second.value if isinstance(second, ast.Constant) else None - return node.args[0].value, default + return str(node.args[0].value), default def _option_names(node: ast.AST) -> list[str]: @@ -86,10 +89,11 @@ def path_constants(source: Source) -> dict[str, str]: """batoceraPaths' module constants that are plain paths.""" constants: dict[str, str] = {} for node in source.tree.body: - name = _assigned_name(node) - if name is None: + assigned = assigned_value(node) + if assigned is None: continue - value = _path_value(node.value, constants) # type: ignore[union-attr] + name, expr = assigned + value = _path_value(expr, constants) if value is not None: constants[name] = value if "BIOS" not in constants: @@ -104,8 +108,6 @@ def configs_root(cg: Configgen) -> dict[str, str]: starts an emulator from (shadPS4's configs/shadps4), with the lines that build it and BIOS. """ - import posixpath - src = cg.source(f"{cg.generators.rsplit('/', 1)[0]}/batoceraPaths.py") if "CONFIGS" not in cg.paths: src.fail("no CONFIGS path constant") @@ -227,10 +229,10 @@ class Configgen: value = node.value.strip('"') prefix = self.bios.rstrip("/") + "/" return value[len(prefix):] if value.startswith(prefix) else None - value = _path_value(node, self.paths) + path = _path_value(node, self.paths) prefix = self.bios.rstrip("/") + "/" - if value is not None and value.startswith(prefix): - return value[len(prefix):] + if path is not None and path.startswith(prefix): + return path[len(prefix):] return None def option_name(self, node: ast.AST) -> tuple[str, str] | None: @@ -252,7 +254,7 @@ class Configgen: return option[1], option[0] -def _raise_message(source: Source, scope: ast.AST, guard: str) -> str: +def _raise_message(source: Source, scope: ast.AST, guard: str | None) -> str: """The message of `if not : raise X("...")` in scope.""" for node in ast.walk(scope): if ( @@ -266,7 +268,7 @@ def _raise_message(source: Source, scope: ast.AST, guard: str) -> str: exc = node.body[0].exc if isinstance(exc, ast.Call) and exc.args and isinstance(exc.args[0], ast.Constant): return str(exc.args[0].value) - source.fail(f"no `if not {guard}: raise` with a message") + return source.fail(f"no `if not {guard}: raise` with a message") def _string_lists(source: Source, node: ast.AST, what: str) -> dict[str, list[str]]: @@ -291,13 +293,13 @@ def duckstation(cg: Configgen) -> list[Launcher]: lists = _string_lists(src, lists_node.value, "bios_lists") finder = src.function("find_bios") listed = [ - call for call in _calls(finder, attr="iterdir") - if isinstance(call.func.value, ast.Name) # type: ignore[attr-defined] + call.func.value.id for call in _calls(finder, attr="iterdir") + if isinstance(call.func, ast.Attribute) and isinstance(call.func.value, ast.Name) ] lowered = _calls(finder, attr="lower") if len(listed) != 1 or not lowered: src.fail("find_bios no longer lists the BIOS directory and compares lowercased names") - search_dir = cg.paths.get(listed[0].func.value.id) # type: ignore[attr-defined] + search_dir = cg.paths.get(listed[0]) if search_dir is None: src.fail("find_bios lists a directory that is not a batoceraPaths constant") @@ -320,7 +322,7 @@ def duckstation(cg: Configgen) -> list[Launcher]: src.assignment("region_mapping", generate).value, "region_mapping" ) branches = [ - node for node in ast.walk(generate) + (node, node.test.left.value) for node in ast.walk(generate) if isinstance(node, ast.If) and isinstance(node.test, ast.Compare) and isinstance(node.test.left, ast.Constant) @@ -329,9 +331,11 @@ def duckstation(cg: Configgen) -> list[Launcher]: ] if len(branches) != 1: src.fail(f"generate no longer branches once on a slot found in {found_var}") - branch = branches[0] + branch, branch_slot = branches[0] writes = _calls(branch, attr="set") - sections = {call.args[0].value for call in writes if isinstance(call.args[0], ast.Constant)} + sections = { + str(call.args[0].value) for call in writes if isinstance(call.args[0], ast.Constant) + } if len(sections) != 1 or not any( isinstance(call.args[1], ast.Subscript) and ast.unparse(call.args[1].value) == "region_mapping" @@ -340,16 +344,16 @@ def duckstation(cg: Configgen) -> list[Launcher]: src.fail("the region paths are not written to one config section through region_mapping") section = sections.pop() shared = { - branch.test.left.value: [ - call.args[1].value for stmt in branch.body for call in _calls(stmt, attr="set") + branch_slot: [ + str(call.args[1].value) for stmt in branch.body for call in _calls(stmt, attr="set") if isinstance(call.args[1], ast.Constant) ] } first, last = _run(body, index, lambda stmt: _mentions(stmt, {section}, {found_var})) ref = src.ref([ - (src.span(first)[0], last.end_lineno), - (finder.lineno, finder.end_lineno), + (src.span(first)[0], end_line(last)), + (finder.lineno, end_line(finder)), src.span(lists_node), ]) launchers = [] @@ -379,7 +383,10 @@ def duckstation_legacy(cg: Configgen) -> list[Launcher]: and isinstance(node.target, ast.Name) ): continue - test = node.body[0].test if isinstance(node.body[0], ast.If) else None + guard = node.body[0] + if not isinstance(guard, ast.If): + continue + test = guard.test if not ( isinstance(test, ast.Call) and isinstance(test.func, ast.Attribute) @@ -390,11 +397,11 @@ def duckstation_legacy(cg: Configgen) -> list[Launcher]: ): continue bound = { - _assigned_name(stmt): stmt for stmt in node.body[0].body + _assigned_name(stmt): stmt for stmt in guard.body if isinstance(stmt, ast.Assign) and ast.unparse(stmt.value) == node.target.id } flags = { - _assigned_name(stmt) for stmt in node.body[0].body + _assigned_name(stmt) for stmt in guard.body if isinstance(stmt, ast.Assign) and isinstance(stmt.value, ast.Constant) and stmt.value.value is True @@ -414,20 +421,30 @@ def duckstation_legacy(cg: Configgen) -> list[Launcher]: writes: dict[str, tuple[str, str]] = {} for call in _calls(generate, attr="set"): + if len(call.args) != 3: + continue + section_node, key_node, var_node = call.args if ( - len(call.args) == 3 - and all(isinstance(a, ast.Constant) for a in call.args[:2]) - and isinstance(call.args[2], ast.Name) + isinstance(section_node, ast.Constant) + and isinstance(key_node, ast.Constant) + and isinstance(var_node, ast.Name) ): - writes[call.args[2].id] = (call.args[0].value, call.args[1].value) + writes[var_node.id] = (str(section_node.value), str(key_node.value)) list_nodes = {name: src.assignment(name, generate) for name, _v, _f, _d in loops} - tracked = {*list_nodes, *(v for _l, v, _f, _d in loops), flag} - first_list = min(list_nodes.values(), key=lambda node: node.lineno) - body, index = _locate(generate, lambda stmt: stmt is first_list) # type: ignore[misc] + # A name never bound (None) is mentioned by no statement. + tracked = { + name for name in (*list_nodes, *(v for _l, v, _f, _d in loops), flag) + if name is not None + } + first_list = min(list_nodes.values(), key=lambda node: node.lineno).node + located = _locate(generate, lambda stmt: stmt is first_list) + if located is None: + src.fail(f"line {first_list.lineno} is outside generate") + body, index = located sections = {section for section, _key in writes.values()} first, last = _run(body, index, lambda stmt: _mentions(stmt, sections, tracked)) - ref = src.ref([(src.span(first)[0], last.end_lineno)]) + ref = src.ref([(src.span(first)[0], end_line(last))]) launchers = [] for list_name, var, _flag, _dir in loops: @@ -482,20 +499,8 @@ def _trace(body: list[ast.stmt], index: int) -> list[ast.stmt]: return sorted(kept, key=lambda stmt: stmt.lineno) -def hatari(cg: Configgen) -> list[Launcher]: - """findBestTos: per machine, each TOS version in each language.""" - module = "hatari.hatariGenerator" - src = cg.generator(module) - finder = src.function("findBestTos") - languages = src.literal(src.assignment("all_languages", finder).value, "all_languages") - machines = _string_lists( - src, src.assignment("all_machines_bios", finder).value, "all_machines_bios" - ) - if not ( - isinstance(languages, list) and languages and all(isinstance(x, str) for x in languages) - ): - src.fail("all_languages is not a list of strings") - +def _tos_name_parts(src: Source, finder: ast.FunctionDef) -> tuple[str, str, str]: + """(marker, prefix, suffix) of the names findBestTos builds.""" marker = prefix = suffix = None for node in ast.walk(finder): if ( @@ -513,7 +518,7 @@ def hatari(cg: Configgen) -> list[Launcher]: and isinstance(parts[0], ast.Constant) and isinstance(parts[1], ast.FormattedValue) ): - marker, prefix = node.test.left.value, parts[0].value + marker, prefix = str(node.test.left.value), str(parts[0].value) # Batocera: tos_path = biosdir / f"{biosversion}{v_language}.img". # KNULLI: filename = f"{biosversion}{v_language}.img". names_built = [] @@ -528,11 +533,55 @@ def hatari(cg: Configgen) -> list[Launcher]: and all(isinstance(p, ast.FormattedValue) for p in parts[:2]) and isinstance(parts[2], ast.Constant) ): - names_built.append(parts[2].value) + names_built.append(str(parts[2].value)) if len(names_built) == 1: suffix = names_built[0] if marker is None or prefix is None or suffix is None: src.fail("findBestTos no longer builds .img") + return marker, prefix, suffix + + +def _tos_command_args( + kept: list[ast.stmt], *, machine_var: str | None, tos_var: str | None, + search_dir: str, paths: dict[str, str], +) -> list[str]: + """The command-line additions of the traced statements, the TOS as .""" + args: list[str] = [] + for stmt in kept: + if isinstance(stmt, ast.AugAssign) and isinstance(stmt.value, ast.List): + for element in stmt.value.elts: + if isinstance(element, ast.Constant): + args.append(str(element.value)) + elif isinstance(element, ast.Name) and element.id == machine_var: + args.append("{machine}") + elif isinstance(element, ast.Name) and element.id == tos_var: + args.append("") + elif ( + isinstance(element, ast.BinOp) + and isinstance(element.right, ast.Name) + and element.right.id == tos_var + and _path_value(element.left, paths) == search_dir + ): + # KNULLI returns the bare name and joins it: BIOS / tos. + args.append("") + return args + + +def hatari(cg: Configgen) -> list[Launcher]: + """findBestTos: per machine, each TOS version in each language.""" + module = "hatari.hatariGenerator" + src = cg.generator(module) + finder = src.function("findBestTos") + languages = src.literal(src.assignment("all_languages", finder).value, "all_languages") + machines = _string_lists( + src, src.assignment("all_machines_bios", finder).value, "all_machines_bios" + ) + if not ( + isinstance(languages, list) and languages and all(isinstance(x, str) for x in languages) + ): + src.fail("all_languages is not a list of strings") + + marker, prefix, suffix = _tos_name_parts(src, finder) raised = [node for node in ast.walk(finder) if isinstance(node, ast.Raise)] exc = raised[0].exc if len(raised) == 1 else None if not (isinstance(exc, ast.Call) and exc.args and isinstance(exc.args[0], ast.JoinedStr)): @@ -548,34 +597,21 @@ def hatari(cg: Configgen) -> list[Launcher]: if located is None: src.fail("generate no longer calls findBestTos") body, index = located - call = body[index].value # type: ignore[attr-defined] + found = body[index] + if not (isinstance(found, ast.Assign) and isinstance(found.value, ast.Call)): + src.fail("generate no longer calls findBestTos") + call = found.value if not call.args or not isinstance(call.args[0], ast.Name) or call.args[0].id not in cg.paths: src.fail("findBestTos is not given a batoceraPaths directory") search_dir = cg.paths[call.args[0].id] kept = _trace(body, index) options = list(dict.fromkeys(name for stmt in kept for name in _option_names(stmt))) - spans = [src.span(stmt) for stmt in kept] + [(finder.lineno, finder.end_lineno)] - args: list[str] = [] + spans = [src.span(stmt) for stmt in kept] + [(finder.lineno, end_line(finder))] second = call.args[1] if len(call.args) > 1 else None - machine_var = second.id if isinstance(second, ast.Name) else None - tos_var = _assigned_name(body[index]) - for stmt in kept: - if isinstance(stmt, ast.AugAssign) and isinstance(stmt.value, ast.List): - for element in stmt.value.elts: - if isinstance(element, ast.Constant): - args.append(str(element.value)) - elif isinstance(element, ast.Name) and element.id == machine_var: - args.append("{machine}") - elif isinstance(element, ast.Name) and element.id == tos_var: - args.append("") - elif ( - isinstance(element, ast.BinOp) - and isinstance(element.right, ast.Name) - and element.right.id == tos_var - and _path_value(element.left, cg.paths) == search_dir - ): - # KNULLI returns the bare name and joins it: BIOS / tos. - args.append("") + args = _tos_command_args( + kept, machine_var=second.id if isinstance(second, ast.Name) else None, + tos_var=_assigned_name(found), search_dir=search_dir, paths=cg.paths, + ) if "" not in args: src.fail("the TOS findBestTos returns is not put on the command line") @@ -605,11 +641,14 @@ def _config_writes(cg: Configgen, src: Source, emulator: str) -> Launcher: """parser.set(section, key, ) calls of one module.""" writes = [] for call in _calls(src.tree, attr="set"): - if len(call.args) != 3 or not all(isinstance(a, ast.Constant) for a in call.args[:2]): + if len(call.args) != 3: continue - name = cg.bios_name(call.args[2]) + section_node, key_node, path = call.args + if not (isinstance(section_node, ast.Constant) and isinstance(key_node, ast.Constant)): + continue + name = cg.bios_name(path) if name is not None: - writes.append((call, call.args[0].value, call.args[1].value, name)) + writes.append((call, str(section_node.value), str(key_node.value), name)) if not writes: src.fail("writes no /userdata/bios path into its config") spans = [] @@ -666,27 +705,31 @@ def melonds(cg: Configgen) -> list[Launcher]: ] if len(console) != 1 or len(enabled) != 1: src.fail("generate no longer sets Emu.ConsoleType from an option with external BIOS on") - option = _option_names(console[0].value)[0] # type: ignore[attr-defined] + option = _option_names(console[0].value)[0] + enabled_key, enabled_value = enabled[0] + if enabled_key is None: + src.fail("base_config unpacks the section that enables the external BIOS") launchers = [] for key, value in zip(base.value.keys, base.value.values): if not isinstance(value, ast.Dict) or not isinstance(key, ast.Constant): continue - entries = [ - (k.value, cg.bios_name(v)) for k, v in zip(value.keys, value.values) + read = [ + (str(k.value), cg.bios_name(v)) for k, v in zip(value.keys, value.values) if isinstance(k, ast.Constant) ] - entries = [(k, name) for k, name in entries if name is not None] + entries = [(k, name) for k, name in read if name is not None] if not entries: continue + section = str(key.value) launchers.append(Launcher( emulator=cg.emulator(module), build="standalone", kind="fixed_name", names=[name for _k, name in entries], case_insensitive=False, search_dir=cg.bios, - passes_to=", ".join(f"{key.value}.{k}" for k, _n in entries), + passes_to=", ".join(f"{section}.{k}" for k, _n in entries), depends_on_option=option, source_ref=src.ref([ - (key.lineno, value.end_lineno), - (enabled[0][0].lineno, enabled[0][1].end_lineno), + (key.lineno, end_line(value)), + (enabled_key.lineno, end_line(enabled_value)), src.span(console[0]), ]), )) @@ -704,17 +747,20 @@ def x16emu(cg: Configgen) -> list[Launcher]: if isinstance(node, ast.List): for flag, value in zip(node.elts, node.elts[1:]): name = cg.bios_name(value) - is_flag = isinstance(flag, ast.Constant) and str(flag.value).startswith("-") - if is_flag and name is not None: - found.append((flag, value, name)) + if ( + isinstance(flag, ast.Constant) + and str(flag.value).startswith("-") + and name is not None + ): + found.append((flag, str(flag.value), value, name)) if not found: src.fail("the command line passes no /userdata/bios path") return [Launcher( emulator=cg.emulator(module), build="standalone", kind="fixed_name", - names=[name for _f, _v, name in found], case_insensitive=False, + names=[name for _f, _t, _v, name in found], case_insensitive=False, search_dir=cg.bios, - passes_to=", ".join(f"command line {f.value}" for f, _v, _n in found), - source_ref=src.ref([(f.lineno, v.end_lineno) for f, v, _n in found]), + passes_to=", ".join(f"command line {text}" for _f, text, _v, _n in found), + source_ref=src.ref([(f.lineno, end_line(v)) for f, _t, v, _n in found]), )] @@ -727,7 +773,7 @@ def gsplus(cg: Configgen) -> list[Launcher]: if len(call.args) == 2 and isinstance(call.args[0], ast.Constant): named = cg.option_name(call.args[1]) if named is not None: - found.append((call, call.args[0].value, *named)) + found.append((call, str(call.args[0].value), *named)) if len(found) != 1: src.fail(f"expected one ROM path built from an option, found {len(found)}") call, key, name, option = found[0] @@ -762,19 +808,29 @@ def _guard_message( ) -> tuple[ast.If, ast.JoinedStr]: """The `if not : raise X(f"...")` statement and its message.""" found = [ - node for node in ast.walk(scope) + (node, message) for node in ast.walk(scope) if isinstance(node, ast.If) and isinstance(node.test, ast.UnaryOp) and isinstance(node.test.op, ast.Not) and test(node.test.operand) - and isinstance(node.body[0], ast.Raise) - and isinstance(node.body[0].exc, ast.Call) - and node.body[0].exc.args - and isinstance(node.body[0].exc.args[0], ast.JoinedStr) + and (message := _raised_fstring(node)) is not None ] if len(found) != 1: src.fail(f"expected one `if not {what}: raise` with a message, found {len(found)}") - return found[0], found[0].body[0].exc.args[0] # type: ignore[attr-defined, no-any-return] + return found[0] + + +def _raised_fstring(node: ast.If) -> ast.JoinedStr | None: + """The f-string message of `raise X(f"...")` opening the if body.""" + first = node.body[0] + if ( + isinstance(first, ast.Raise) + and isinstance(first.exc, ast.Call) + and first.exc.args + and isinstance(first.exc.args[0], ast.JoinedStr) + ): + return first.exc.args[0] + return None def _render(message: ast.JoinedStr, var: str, value: str) -> str: @@ -782,10 +838,13 @@ def _render(message: ast.JoinedStr, var: str, value: str) -> str: for part in message.values: if isinstance(part, ast.Constant): parts.append(str(part.value)) - elif isinstance(part.value, ast.Name) and part.value.id == var: # type: ignore[attr-defined] + continue + # The other parts of an f-string are its {placeholders}. + expr = part.value if isinstance(part, ast.FormattedValue) else part + if isinstance(expr, ast.Name) and expr.id == var: parts.append(value) else: - parts.append(f"{{{ast.unparse(part.value)}}}") # type: ignore[attr-defined] + parts.append(f"{{{ast.unparse(expr)}}}") return "".join(parts) @@ -804,15 +863,17 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: generate = src.function("generate") command = [ - node for node in ast.walk(generate) - if _assigned_name(node) == "commandArray" - and isinstance(node.value, ast.List) # type: ignore[attr-defined] - and node.value.elts # type: ignore[attr-defined] - and isinstance(node.value.elts[0], ast.Name) # type: ignore[attr-defined] + (node, head.id) for node in ast.walk(generate) + if isinstance(node, (ast.Assign, ast.AnnAssign)) + and (assigned := assigned_value(node)) is not None + and assigned[0] == "commandArray" + and isinstance(assigned[1], ast.List) + and assigned[1].elts + and isinstance((head := assigned[1].elts[0]), ast.Name) ] if len(command) != 1: src.fail("generate no longer starts commandArray with the binary it runs") - binary = command[0].value.elts[0].id # type: ignore[attr-defined] + command_stmt, binary = command[0] exists, missing = _guard_message(src, generate, lambda test: ( isinstance(test, ast.Call) @@ -842,35 +903,37 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: launchers = [] for system, branch in _system_branches(generate): bound = { - name: (stmt, _path_value(stmt.value, constants)) # type: ignore[attr-defined] - for stmt in branch.body if (name := _assigned_name(stmt)) is not None + assigned[0]: (stmt, assigned[1], _path_value(assigned[1], constants)) + for stmt in branch.body if (assigned := assigned_value(stmt)) is not None } - if binary not in bound or not (bound[binary][1] or "").startswith(prefix): + if binary not in bound or not (bound[binary][2] or "").startswith(prefix): src.fail(f"the {system} branch binds {binary} to no path under {cg.bios}") library = [ name for name in bound if name != binary and _mentions(env_value, set(), {name}) ] - if len(library) != 1 or not (bound[library[0]][1] or "").startswith(prefix): + if len(library) != 1 or not (bound[library[0]][2] or "").startswith(prefix): src.fail(f"the {system} branch puts no /userdata/bios folder on LD_LIBRARY_PATH") - binary_stmt, path = bound[binary] - library_stmt, folder = bound[library[0]] + binary_stmt, binary_value, path = bound[binary] + library_stmt, _library_value, folder = bound[library[0]] + if path is None: + src.fail(f"the {system} branch binds {binary} to no path under {cg.bios}") test_line = src.span(branch.test) constant = next( - (defined[n.id] for n in ast.walk(binary_stmt.value) # type: ignore[attr-defined] + (defined[n.id] for n in ast.walk(binary_value) if isinstance(n, ast.Name) and n.id in defined), None, ) spans = [test_line, src.span(binary_stmt), src.span(exists), src.span(access), - src.span(command[0])] + src.span(command_stmt)] if constant is not None: spans.append(src.span(constant)) launchers.append(Launcher( emulator=cg.emulator(module), build="standalone", kind="fixed_name", - slot=system, names=[path[len(prefix):]], # type: ignore[index] + slot=system, names=[path[len(prefix):]], case_insensitive=False, search_dir=cg.bios, passes_to="exec", fails_when_missing=", ".join( - _render(message, binary, path) for message in (missing, not_executable) # type: ignore[arg-type] + _render(message, binary, path) for message in (missing, not_executable) ), source_ref=src.ref(spans), )) @@ -893,7 +956,7 @@ ENVIRONMENT_GENERATORS = (("flycast.flycastGenerator", "flycast/flycastPaths.py" def environment_directories(cg: Configgen) -> list[Launcher]: """Command(..., env={KEY: }) in the generator.""" - launchers = [] + launchers: list[Launcher] = [] for module, paths_module in ENVIRONMENT_GENERATORS: src = cg.generator(module) constants = dict(cg.paths) @@ -904,7 +967,7 @@ def environment_directories(cg: Configgen) -> list[Launcher]: constants[name] = value prefix = cg.bios.rstrip("/") found = [ - (key.value, value, key) + (str(key.value), value, key) for call in _calls(src.tree, attr="Command") for keyword in call.keywords if keyword.arg == "env" and isinstance(keyword.value, ast.Dict) @@ -919,7 +982,7 @@ def environment_directories(cg: Configgen) -> list[Launcher]: Launcher( emulator=cg.emulator(module), build="standalone", kind="passes_path", names=[], search_dir=value, passes_to=f"environment {key}", - source_ref=src.ref([(node.lineno, node.end_lineno)]), + source_ref=src.ref([(node.lineno, end_line(node))]), ) for key, value, node in found ) @@ -1032,7 +1095,7 @@ def core_file_options(cg: Configgen) -> list[Launcher]: cores: dict[str, list[str]] = {} for key, value in zip(table.keys, table.values): if isinstance(key, ast.Constant) and isinstance(value, ast.Name): - cores.setdefault(value.id, []).append(key.value) + cores.setdefault(value.id, []).append(str(key.value)) launchers = [] for function_name, setting in FILE_OPTIONS: function = src.function(function_name) @@ -1048,17 +1111,17 @@ def core_file_options(cg: Configgen) -> list[Launcher]: src.fail(f"{function_name} no longer sets {setting} once") call = calls[0] named = call.args[3] if len(call.args) > 3 else None - option = named.value if isinstance(named, ast.Constant) else setting + option = str(named.value) if isinstance(named, ast.Constant) else setting default = next((k.value for k in call.keywords if k.arg == "default"), None) if isinstance(default, ast.Constant): - names = [default.value] + names = [str(default.value)] condition = None elif ( isinstance(default, ast.IfExp) and isinstance(default.body, ast.Constant) and isinstance(default.orelse, ast.Constant) ): - names = [default.body.value, default.orelse.value] + names = [str(default.body.value), str(default.orelse.value)] condition = ast.unparse(default.test) else: src.fail(f"{setting} has no literal default") @@ -1127,10 +1190,7 @@ SEARCH_PATH_GENERATORS = ("mame/mameGenerator.py",) def search_paths(cg: Configgen) -> list[Launcher]: """Every /userdata/bios path a generator's command line names, read as KNULLI's generic reader reads its fork of the same generator.""" - try: - from .knulli_launchers import GenericSites, bios_sites - except ImportError: - from knulli_launchers import GenericSites, bios_sites # type: ignore[no-redef] + from .knulli_launchers import GenericSites, bios_sites # A boot disk image the command line names (the Macintosh's # /userdata/bios/.img) is a file, no search path. return [ diff --git a/scripts/scraper/batocera_scraper.py b/scripts/scraper/batocera_scraper.py index 49f797077..0b6e7d12f 100644 --- a/scripts/scraper/batocera_scraper.py +++ b/scripts/scraper/batocera_scraper.py @@ -333,18 +333,8 @@ def _resolve_truncated_md5(md5: str, md5_index: dict[str, str]) -> str: return md5 -def extract_systems_dict(raw: str) -> dict: - """The `systems` dict of a batocera-systems style script. - - Read with ast.literal_eval, never executed: the text is the platform's - code. A key written twice keeps its later value, as it does when Python - runs the script. - """ - match = re.search(r"^systems\s*=\s*\{", raw, re.MULTILINE) - if not match: - raise ValueError("no 'systems = {' in the script") - - start = match.start() + raw[match.start() :].index("{") +def _closing_brace(raw: str, start: int) -> int: + """Index of the brace closing the one at `start`, past strings and comments.""" depth = 0 i = start in_str = False @@ -370,35 +360,51 @@ def extract_systems_dict(raw: str) -> dict: while i < len(raw) and raw[i] != "\n": i += 1 i += 1 + return i - dict_str = raw[start : i + 1] - lines = [] - for line in dict_str.split("\n"): - in_string = False - string_char = None - clean = [] - j = 0 - while j < len(line): - ch = line[j] - if ch == "\\" and j + 1 < len(line): - clean.append(ch) - clean.append(line[j + 1]) - j += 2 - continue - if ch in ('"', "'") and not in_string: - in_string = True - string_char = ch - clean.append(ch) - elif ch == string_char and in_string: - in_string = False - clean.append(ch) - elif ch == "#" and not in_string: - break - else: - clean.append(ch) - j += 1 - lines.append("".join(clean)) +def _strip_comment(line: str) -> str: + """The line without a trailing # comment, strings kept whole.""" + in_string = False + string_char = None + clean = [] + j = 0 + while j < len(line): + ch = line[j] + if ch == "\\" and j + 1 < len(line): + clean.append(ch) + clean.append(line[j + 1]) + j += 2 + continue + if ch in ('"', "'") and not in_string: + in_string = True + string_char = ch + clean.append(ch) + elif ch == string_char and in_string: + in_string = False + clean.append(ch) + elif ch == "#" and not in_string: + break + else: + clean.append(ch) + j += 1 + return "".join(clean) + + +def extract_systems_dict(raw: str) -> dict: + """The `systems` dict of a batocera-systems style script. + + Read with ast.literal_eval, never executed: the text is the platform's + code. A key written twice keeps its later value, as it does when Python + runs the script. + """ + match = re.search(r"^systems\s*=\s*\{", raw, re.MULTILINE) + if not match: + raise ValueError("no 'systems = {' in the script") + + start = match.start() + raw[match.start() :].index("{") + dict_str = raw[start : _closing_brace(raw, start) + 1] + lines = [_strip_comment(line) for line in dict_str.split("\n")] clean_dict_str = "\n".join(lines) diff --git a/scripts/scraper/bizhawk_scraper.py b/scripts/scraper/bizhawk_scraper.py index dbfd7c4bf..e6fe727f9 100644 --- a/scripts/scraper/bizhawk_scraper.py +++ b/scripts/scraper/bizhawk_scraper.py @@ -20,22 +20,13 @@ from __future__ import annotations import re -try: - from .base_scraper import ( - requirement_entry, - BaseScraper, - BiosRequirement, - fetch_github_latest_version, - scraper_cli, - ) -except ImportError: - from base_scraper import ( - requirement_entry, - BaseScraper, - BiosRequirement, - fetch_github_latest_version, - scraper_cli, - ) +from .base_scraper import ( + requirement_entry, + BaseScraper, + BiosRequirement, + fetch_github_latest_version, + scraper_cli, +) PLATFORM_NAME = "bizhawk" diff --git a/scripts/scraper/configgen_launchers.py b/scripts/scraper/configgen_launchers.py index 0b6fa6067..62fb2ab0d 100644 --- a/scripts/scraper/configgen_launchers.py +++ b/scripts/scraper/configgen_launchers.py @@ -10,13 +10,30 @@ from __future__ import annotations import ast from collections.abc import Callable, Iterator from dataclasses import dataclass -from typing import Any, NoReturn +from typing import Any, NoReturn, Protocol class LauncherShapeError(ValueError): """A generator no longer has the shape its extractor reads.""" +class Located(Protocol): + """A node that carries source lines: a statement, an expression, an argument.""" + + @property + def lineno(self) -> int: ... + + @property + def end_lineno(self) -> int | None: ... + + +def end_line(node: Located) -> int: + """The last line of a parsed node, which ast.parse always sets.""" + if node.end_lineno is None: + raise LauncherShapeError(f"node at line {node.lineno} has no end line") + return node.end_lineno + + @dataclass class Launcher: """One thing a launcher looks for or hands over, as its code says it.""" @@ -60,6 +77,22 @@ class Launcher: return {key: getattr(self, key) for key in order if getattr(self, key) is not None} +@dataclass(frozen=True) +class Assignment: + """A single-name assignment statement and the value it binds.""" + + node: ast.Assign | ast.AnnAssign + value: ast.expr + + @property + def lineno(self) -> int: + return self.node.lineno + + @property + def end_lineno(self) -> int | None: + return self.node.end_lineno + + class Source: """One configgen file, parsed, with the lines its nodes span.""" @@ -83,27 +116,28 @@ class Source: self.fail(f"expected one function {name}, found {len(found)}") return found[0] - def assignment(self, name: str, scope: ast.AST | None = None) -> ast.Assign | ast.AnnAssign: + def assignment(self, name: str, scope: ast.AST | None = None) -> Assignment: found = [ - node for node in ast.walk(scope or self.tree) - if _assigned_name(node) == name + Assignment(node, assigned[1]) for node in ast.walk(scope or self.tree) + if isinstance(node, (ast.Assign, ast.AnnAssign)) + and (assigned := assigned_value(node)) is not None and assigned[0] == name ] if len(found) != 1: self.fail(f"expected one assignment to {name}, found {len(found)}") return found[0] - def literal(self, node: ast.AST | None, what: str) -> Any: + def literal(self, node: ast.AST, what: str) -> Any: try: - return ast.literal_eval(node) # type: ignore[arg-type] + return ast.literal_eval(node) except (ValueError, TypeError, SyntaxError) as e: self.fail(f"{what} is not a literal: {e}") - def span(self, node: ast.AST) -> tuple[int, int]: + def span(self, node: Located) -> tuple[int, int]: """Lines of a node, with the comment lines written right above it.""" - start = node.lineno # type: ignore[attr-defined] + start = node.lineno while start > 1 and self.lines[start - 2].strip().startswith("#"): start -= 1 - return start, node.end_lineno # type: ignore[attr-defined] + return start, end_line(node) def ref(self, spans: list[tuple[int, int]]) -> str: """`path:a-b, c-d`, ranges joined across blank and comment lines.""" @@ -123,14 +157,20 @@ class Source: ) -def _assigned_name(node: ast.AST) -> str | None: +def assigned_value(node: ast.AST) -> tuple[str, ast.expr] | None: + """The name a single-name assignment binds, and the value it binds.""" if isinstance(node, ast.Assign) and len(node.targets) == 1: - target = node.targets[0] + target, value = node.targets[0], node.value elif isinstance(node, ast.AnnAssign) and node.value is not None: - target = node.target + target, value = node.target, node.value else: return None - return target.id if isinstance(target, ast.Name) else None + return (target.id, value) if isinstance(target, ast.Name) else None + + +def _assigned_name(node: ast.AST) -> str | None: + assigned = assigned_value(node) + return assigned[0] if assigned is not None else None def _statement_lists(node: ast.AST) -> Iterator[list[ast.stmt]]: @@ -202,11 +242,11 @@ def _enclosing_test(scope: ast.AST, node: ast.AST) -> str | None: return None -def _innermost_function(src: Source, node: ast.AST) -> ast.FunctionDef: +def _innermost_function(src: Source, node: ast.stmt | ast.expr) -> ast.FunctionDef: holders = [ f for f in ast.walk(src.tree) if isinstance(f, ast.FunctionDef) and any(child is node for child in ast.walk(f)) ] if not holders: - src.fail(f"line {node.lineno} is outside any function") # type: ignore[attr-defined] + src.fail(f"line {node.lineno} is outside any function") return max(holders, key=lambda f: f.lineno) diff --git a/scripts/scraper/coreinfo_scraper.py b/scripts/scraper/coreinfo_scraper.py index d7bc1a499..e4e1eed6f 100644 --- a/scripts/scraper/coreinfo_scraper.py +++ b/scripts/scraper/coreinfo_scraper.py @@ -13,30 +13,26 @@ Complements libretro_scraper (System.dat) with: from __future__ import annotations +import importlib import json +import os import re import sys import urllib.error import urllib.request -try: - from .base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_github_latest_version, - github_headers, - ) -except ImportError: +if not __package__: # Allow running directly: python scripts/scraper/coreinfo_scraper.py - import os - sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) - from scraper.base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_github_latest_version, - github_headers, - ) + importlib.import_module("scraper") + __package__ = "scraper" + +from .base_scraper import ( + BaseScraper, + BiosRequirement, + fetch_github_latest_version, + github_headers, +) PLATFORM_NAME = "libretro_coreinfo" diff --git a/scripts/scraper/dat_pack_importer.py b/scripts/scraper/dat_pack_importer.py index 33dc62bb9..d89699da4 100644 --- a/scripts/scraper/dat_pack_importer.py +++ b/scripts/scraper/dat_pack_importer.py @@ -77,7 +77,7 @@ def import_pack(source: str, pack: Path) -> tuple[dict, list[dict], int]: dats = {} entries = [] skipped = 0 - for member, content in _iter_dat_contents(pack): + for _member, content in _iter_dat_contents(pack): try: dat = parse_logiqx(content) except (ValueError, SyntaxError): diff --git a/scripts/scraper/dat_parser.py b/scripts/scraper/dat_parser.py index 07160f9e1..6a2784b4a 100644 --- a/scripts/scraper/dat_parser.py +++ b/scripts/scraper/dat_parser.py @@ -61,7 +61,7 @@ def parse_dat(content: str) -> list[DatRom]: continue current_system = value - elif stripped.startswith("rom (") or stripped.startswith("rom("): + elif stripped.startswith(("rom (", "rom(")): rom = _parse_rom_line(stripped, current_system) if rom: roms.append(rom) diff --git a/scripts/scraper/emudeck_launchers.py b/scripts/scraper/emudeck_launchers.py index b8f42696f..0c3b5faff 100644 --- a/scripts/scraper/emudeck_launchers.py +++ b/scripts/scraper/emudeck_launchers.py @@ -14,28 +14,16 @@ import posixpath import re from collections.abc import Callable -try: - from .configgen_launchers import Launcher - from .shell_launchers import ( - LauncherPatternMissing, - RepoTree, - Script, - describe_keys, - settings, - source_ref, - words, - ) -except ImportError: - from configgen_launchers import Launcher - from shell_launchers import ( - LauncherPatternMissing, - RepoTree, - Script, - describe_keys, - settings, - source_ref, - words, - ) +from .configgen_launchers import Launcher +from .shell_launchers import ( + LauncherPatternMissing, + RepoTree, + Script, + describe_keys, + settings, + source_ref, + words, +) EMUSCRIPTS = "functions/EmuScripts" CONFIGS = "configs" @@ -170,7 +158,8 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> """ script = _script(tree, name) emulator = _emulator(name) - records: list[Launcher] = [] + # Each record with the config file it names. + records: list[tuple[Launcher, str]] = [] groups: dict[tuple[str, str], tuple[list[tuple[str, str]], list[str], set[int]]] = {} for file, section, key, value, lines in setters(script): config = posixpath.basename(file) @@ -189,7 +178,7 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> continue if key not in DIRECTORY_KINDS: raise script.missing(f"known directory key, got {key}") - records.append( + records.append(( Launcher( emulator=emulator, build="libretro" if emulator == "retroarch" else "standalone", @@ -198,10 +187,11 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> source_ref=source_ref([(script.path, lines)]), search_dir=value, passes_to=describe_keys(config, ((section, key),)), - ) - ) + ), + config, + )) for (config, folder), (keys, names, refs) in groups.items(): - records.append( + records.append(( Launcher( emulator=emulator, build="standalone", @@ -210,19 +200,22 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> source_ref=source_ref([(script.path, refs)]), search_dir=folder, passes_to=describe_keys(config, tuple(keys)), - ) - ) + ), + config, + )) if not records: raise script.missing(f"setter writing a path under {BIOS}") if option_key: - for record in records: - _add_option(tree, script, record, option_key) - return records + for record, config in records: + # passes_to starts with the config name, cut at its first space. + _add_option(tree, script, record, config.split(" ", 1)[0], option_key) + return [record for record, _config in records] -def _add_option(tree: RepoTree, script: Script, record: Launcher, option_key: str) -> None: +def _add_option( + tree: RepoTree, script: Script, record: Launcher, config: str, option_key: str +) -> None: """depends_on_option from the value the shipped config gives option_key.""" - config = record.passes_to.split(" ", 1)[0] file_var = script.assignment_ending("/" + config) if file_var is None: raise script.missing(f"config variable for {config}") @@ -395,7 +388,7 @@ def configured(tree: RepoTree) -> list[Launcher]: def links(tree: RepoTree) -> list[Launcher]: - records = [] + records: list[Launcher] = [] for name in LINK_SCRIPTS: script = _script(tree, name) found = script.links(BIOS) diff --git a/scripts/scraper/emudeck_scraper.py b/scripts/scraper/emudeck_scraper.py index aabb91611..f6f3d7f9b 100644 --- a/scripts/scraper/emudeck_scraper.py +++ b/scripts/scraper/emudeck_scraper.py @@ -17,28 +17,16 @@ import re import urllib.error import urllib.request -try: - from .base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_branch_head, - fetch_github_latest_version, - github_headers, - requirement_entry, - ) - from .emudeck_launchers import emulator_of_script, extract_launchers - from .shell_launchers import RepoTree -except ImportError: - from base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_branch_head, - fetch_github_latest_version, - github_headers, - requirement_entry, - ) - from emudeck_launchers import emulator_of_script, extract_launchers - from shell_launchers import RepoTree +from .base_scraper import ( + BaseScraper, + BiosRequirement, + fetch_branch_head, + fetch_github_latest_version, + github_headers, + requirement_entry, +) +from .emudeck_launchers import emulator_of_script, extract_launchers +from .shell_launchers import RepoTree PLATFORM_NAME = "emudeck" @@ -327,7 +315,7 @@ class Scraper(BaseScraper): def _parse_csv_bios(self, csv_text: str) -> list[dict]: """Parse BIOS file info from a cheat sheet CSV.""" - entries = [] + entries: list[dict] = [] if not csv_text.strip(): return entries reader = csv.DictReader(io.StringIO(csv_text)) @@ -414,17 +402,17 @@ class Scraper(BaseScraper): ) ) - for md5 in system_hashes: - requirements.append( - BiosRequirement( - name=f"{system}:{md5}", - system=system, - md5=md5, - destination="", - required=True, - native_id=system, - ) + requirements.extend( + BiosRequirement( + name=f"{system}:{md5}", + system=system, + md5=md5, + destination="", + required=True, + native_id=system, ) + for md5 in system_hashes + ) for sheet in CSV_SHEETS: csv_text = self._fetch_csv(sheet) diff --git a/scripts/scraper/emuelec_launchers.py b/scripts/scraper/emuelec_launchers.py index 98388983e..b26365884 100644 --- a/scripts/scraper/emuelec_launchers.py +++ b/scripts/scraper/emuelec_launchers.py @@ -89,9 +89,14 @@ class Runs: name = next( (posixpath.basename(w.text) for w in command if _SCRIPT.fullmatch(w.text)), None ) - if name is None or (emu is None and arm is None): + if name is None: + continue + if emu is not None: + names, at = [emu[0]], emu[1] + elif arm is not None: + names, at = arm + else: continue - names, at = ([emu[0]], emu[1]) if emu else arm # type: ignore[misc] entry = self.by_script.setdefault(name, Dispatch()) entry.emulators.extend(n for n in names if n not in entry.emulators) entry.lines |= {at, number} diff --git a/scripts/scraper/fbneo_hash_scraper.py b/scripts/scraper/fbneo_hash_scraper.py index 17ac95a43..1f1fea97c 100644 --- a/scripts/scraper/fbneo_hash_scraper.py +++ b/scripts/scraper/fbneo_hash_scraper.py @@ -196,12 +196,10 @@ def _format_diff( return "\n".join(lines) if show_added: - for label in added: - lines.append(f" + {label}") + lines.extend(f" + {label}" for label in added) elif added: lines.append(f" + {len(added)} new ROMs available (main profile only)") - for label in updated: - lines.append(f" ~ {label}") + lines.extend(f" ~ {label}" for label in updated) lines.append(f" = {diff['unchanged']} unchanged") if oos: lines.append(f" . {oos} out of scope") diff --git a/scripts/scraper/game_dat_importer.py b/scripts/scraper/game_dat_importer.py index ecff9f160..c4bb05605 100644 --- a/scripts/scraper/game_dat_importer.py +++ b/scripts/scraper/game_dat_importer.py @@ -36,16 +36,15 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -_SCRIPTS_DIR = str(Path(__file__).resolve().parents[1]) -if _SCRIPTS_DIR not in sys.path: +if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path: sys.path.insert(0, _SCRIPTS_DIR) -from artifacts import copy_stream_atomic, write_if_changed, write_text_atomic # noqa: E402 -from common import parse_untrusted_xml # noqa: E402 -from region import REGIONS, WORLD # noqa: E402 -from region_audit import NOINTRO # noqa: E402 +from artifacts import copy_stream_atomic, write_if_changed, write_text_atomic +from common import parse_untrusted_xml +from region import REGIONS, WORLD +from region_audit import NOINTRO -from .base_scraper import github_headers # noqa: E402 +from .base_scraper import github_headers SOURCES = ("no-intro", "redump") CACHE_DIR = Path(".cache") / "game-dats" diff --git a/scripts/scraper/knulli_launchers.py b/scripts/scraper/knulli_launchers.py index d2e464324..983af3c49 100644 --- a/scripts/scraper/knulli_launchers.py +++ b/scripts/scraper/knulli_launchers.py @@ -28,62 +28,32 @@ from typing import Any import yaml -try: - from .batocera_launchers import ( - PATH_PATCHES, - Configgen, - config_directories, - _path_value, - _render, - _system_branches, - duckstation, - duckstation_legacy, - environment_directories, - hatari, - melonds, - mupen64plus, - patched_paths, - x16emu, - working_directories, - xemu, - ) - from .configgen_launchers import ( - Launcher, - LauncherShapeError, - Source, - _assigned_name, - ) - from .shell_launchers import LauncherPatternMissing, Script, source_ref -except ImportError: - from batocera_launchers import ( # type: ignore[no-redef] - PATH_PATCHES, - Configgen, - config_directories, - _path_value, - _render, - _system_branches, - duckstation, - duckstation_legacy, - environment_directories, - hatari, - melonds, - mupen64plus, - patched_paths, - x16emu, - working_directories, - xemu, - ) - from configgen_launchers import ( # type: ignore[no-redef] - Launcher, - LauncherShapeError, - Source, - _assigned_name, - ) - from shell_launchers import ( # type: ignore[no-redef] - LauncherPatternMissing, - Script, - source_ref, - ) +from .batocera_launchers import ( + PATH_PATCHES, + Configgen, + config_directories, + _path_value, + _render, + _system_branches, + duckstation, + duckstation_legacy, + environment_directories, + hatari, + melonds, + mupen64plus, + patched_paths, + x16emu, + working_directories, + xemu, +) +from .configgen_launchers import ( + Launcher, + LauncherShapeError, + Source, + _assigned_name, + end_line, +) +from .shell_launchers import LauncherPatternMissing, Script, source_ref CONFIGGEN = "package/system/knulli-configgen/configgen/configgen" GENERATORS = f"{CONFIGGEN}/generators" @@ -166,7 +136,10 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: and isinstance(t.operand, ast.Call) and ast.unparse(t.operand.func).endswith(".exists"), "not .exists()", ) - binary = ast.unparse(missing.test.operand.func).removesuffix(".exists") # type: ignore[attr-defined] + tested = missing.test + if not (isinstance(tested, ast.UnaryOp) and isinstance(tested.operand, ast.Call)): + src.fail("not .exists() tests no call") + binary = ast.unparse(tested.operand.func).removesuffix(".exists") access, access_message = _error_guard( src, generate, lambda t: isinstance(t, ast.UnaryOp) and isinstance(t.op, ast.Not) @@ -184,12 +157,13 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: launchers = [] for system, branch in _system_branches(generate): bound = [ - stmt for stmt in branch.body - if _assigned_name(stmt) == binary and isinstance(_bound(stmt), ast.Name) + (stmt, held) for stmt in branch.body + if _assigned_name(stmt) == binary and isinstance((held := _bound(stmt)), ast.Name) ] if len(bound) != 1: src.fail(f"the {system} branch does not set {binary} once") - constant = ast.unparse(bound[0].value) # type: ignore[attr-defined] + bound_stmt, bound_value = bound[0] + constant = ast.unparse(bound_value) path = constants.get(constant) if path is None or not path.startswith(prefix): src.fail(f"{constant} is not a path under {cg.bios}") @@ -200,7 +174,7 @@ def lexaloffle(cg: Configgen) -> list[Launcher]: search_dir=cg.bios, passes_to="exec", fails_when_missing=", ".join(messages), source_ref=src.ref([ - src.span(defined[constant]), src.span(branch.test), src.span(bound[0]), + src.span(defined[constant]), src.span(branch.test), src.span(bound_stmt), _lines(missing), _lines(access), src.span(commands[0]), ]), @@ -463,8 +437,10 @@ class _Reader: if isinstance(part, ast.Constant): parts.append(str(part.value)) else: - inner = self.resolve(part.value) # type: ignore[attr-defined] - parts.append(inner if inner is not None else f"<{ast.unparse(part.value)}>") # type: ignore[attr-defined] + # The other parts of an f-string are its {placeholders}. + expr = part.value if isinstance(part, ast.FormattedValue) else part + inner = self.resolve(expr) + parts.append(inner if inner is not None else f"<{ast.unparse(expr)}>") return "".join(parts).strip('"') if ( isinstance(node, ast.BinOp) @@ -497,7 +473,7 @@ class _Reader: return (name.id, values) if values else None return None - def _literal_list(self, node: ast.AST, scope_of: ast.AST) -> list[str] | None: + def _literal_list(self, node: ast.AST | None, scope_of: ast.AST) -> list[str] | None: if isinstance(node, ast.List): return [str(e.value) for e in node.elts if isinstance(e, ast.Constant)] if isinstance(node, ast.Name): @@ -507,14 +483,15 @@ class _Reader: if _assigned_name(n) == node.id and isinstance(_bound(n), ast.List) ] if len(bound) == 1: - return self._literal_list(_bound(bound[0]), scope_of) # type: ignore[arg-type] + return self._literal_list(_bound(bound[0]), scope_of) return None def function_of(self, node: ast.AST) -> ast.FunctionDef | None: - while node is not None: - node = self.parents.get(id(node)) # type: ignore[assignment] - if isinstance(node, ast.FunctionDef): - return node + current: ast.AST | None = node + while current is not None: + current = self.parents.get(id(current)) + if isinstance(current, ast.FunctionDef): + return current return None def statement_of(self, node: ast.AST) -> ast.stmt: @@ -535,7 +512,7 @@ class _Reader: if written and isinstance(parent, ast.Call) and ast.unparse(parent.func).endswith(".write"): yield node, written.group(0) continue - if not self.under_bios(value): + if value is None or not self.under_bios(value): continue parent = self.parents.get(id(node)) if isinstance(parent, (ast.FormattedValue, ast.JoinedStr)): @@ -544,7 +521,7 @@ class _Reader: continue if isinstance(parent, ast.Call) and ast.unparse(parent.func) == "str": continue - yield node, value # type: ignore[misc] + yield node, value def conditions( self, node: ast.AST, guards: bool = False @@ -657,65 +634,77 @@ class _Reader: def consumer(self, node: ast.AST, value: str) -> tuple[str | None, str | None]: parent = self.parents.get(id(node)) - if isinstance(parent, ast.Attribute): - return None, None if isinstance(parent, (ast.List, ast.Tuple)): - holder = self.parents.get(id(parent)) - if isinstance(holder, (ast.For, ast.comprehension)): - return None, None - if not self._command_line(parent): - return None, None - index = next(i for i, e in enumerate(parent.elts) if e is node) - if isinstance(node, ast.JoinedStr) and isinstance(node.values[0], ast.Constant): - flag = str(node.values[0].value) - if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): - return f"command line {flag[:-1]}", None - previous = parent.elts[index - 1] if index else None - if isinstance(previous, ast.Constant) and str(previous.value).startswith("-"): - return f"command line {previous.value!s}", None - if index: - return f"command line argument {index}", None - return None, None + return self._listed_consumer(node, parent, value) if isinstance(parent, ast.Call): - func = parent.func - attr = func.attr if isinstance(func, ast.Attribute) else None - consts = [a.value for a in parent.args if isinstance(a, ast.Constant)] - if attr == "save" and len(parent.args) == 2 and parent.args[1] is node and consts: - return str(consts[0]), None - if attr == "set" and len(parent.args) == 3 and parent.args[2] is node and len(consts) >= 2: - return f"[{consts[0]!s}] {consts[1]!s}", None - receiver = func.value if isinstance(func, ast.Attribute) else None - if attr in ("copy", "copyfile", "copy2") and receiver is not None and ast.unparse(receiver) == "shutil": - source, target = parent.args[0], parent.args[1] - self.copy_sources[id(node)] = value if source is node else ( - self.resolve(source) or ast.unparse(source) - ) - return (value if target is node else self.resolve(target) or ast.unparse(target)), "copies" - if ( - attr == "append" - and isinstance(receiver, ast.Name) - and receiver.id in COMMAND_NAMES - and isinstance(node, ast.JoinedStr) - and isinstance(node.values[0], ast.Constant) - ): - flag = str(node.values[0].value) - if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): - return f"command line {flag[:-1]}", None - if attr == "write" and isinstance(node, ast.Constant): - return f"written: {str(node.value).strip()}", None - return None, None + return self._call_consumer(node, parent, value) if isinstance(parent, ast.Dict): - key = next( - (k for k, v in zip(parent.keys, parent.values) if v is node), None - ) - if isinstance(key, ast.Constant): - holder = self.parents.get(id(parent)) - is_env = ( - isinstance(holder, ast.keyword) and holder.arg == "env" - ) or _assigned_name(holder) == "env" # type: ignore[arg-type] - return (f"environment {key.value!s}" if is_env else str(key.value)), None + return self._dict_consumer(node, parent) return None, None + def _listed_consumer( + self, node: ast.AST, parent: ast.List | ast.Tuple, value: str + ) -> tuple[str | None, str | None]: + holder = self.parents.get(id(parent)) + if isinstance(holder, (ast.For, ast.comprehension)): + return None, None + if not self._command_line(parent): + return None, None + index = next(i for i, e in enumerate(parent.elts) if e is node) + if isinstance(node, ast.JoinedStr) and isinstance(node.values[0], ast.Constant): + flag = str(node.values[0].value) + if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): + return f"command line {flag[:-1]}", None + previous = parent.elts[index - 1] if index else None + if isinstance(previous, ast.Constant) and str(previous.value).startswith("-"): + return f"command line {previous.value!s}", None + if index: + return f"command line argument {index}", None + return None, None + + def _call_consumer( + self, node: ast.AST, parent: ast.Call, value: str + ) -> tuple[str | None, str | None]: + func = parent.func + attr = func.attr if isinstance(func, ast.Attribute) else None + consts = [a.value for a in parent.args if isinstance(a, ast.Constant)] + if attr == "save" and len(parent.args) == 2 and parent.args[1] is node and consts: + return str(consts[0]), None + if attr == "set" and len(parent.args) == 3 and parent.args[2] is node and len(consts) >= 2: + return f"[{consts[0]!s}] {consts[1]!s}", None + receiver = func.value if isinstance(func, ast.Attribute) else None + if attr in ("copy", "copyfile", "copy2") and receiver is not None and ast.unparse(receiver) == "shutil": + source, target = parent.args[0], parent.args[1] + self.copy_sources[id(node)] = value if source is node else ( + self.resolve(source) or ast.unparse(source) + ) + return (value if target is node else self.resolve(target) or ast.unparse(target)), "copies" + if ( + attr == "append" + and isinstance(receiver, ast.Name) + and receiver.id in COMMAND_NAMES + and isinstance(node, ast.JoinedStr) + and isinstance(node.values[0], ast.Constant) + ): + flag = str(node.values[0].value) + if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): + return f"command line {flag[:-1]}", None + if attr == "write" and isinstance(node, ast.Constant): + return f"written: {str(node.value).strip()}", None + return None, None + + def _dict_consumer(self, node: ast.AST, parent: ast.Dict) -> tuple[str | None, str | None]: + key = next( + (k for k, v in zip(parent.keys, parent.values) if v is node), None + ) + if not isinstance(key, ast.Constant): + return None, None + holder = self.parents.get(id(parent)) + is_env = ( + isinstance(holder, ast.keyword) and holder.arg == "env" + ) or (holder is not None and _assigned_name(holder) == "env") + return (f"environment {key.value!s}" if is_env else str(key.value)), None + def sites(self) -> list[_Site]: found: list[_Site] = [] guards: list[tuple[ast.AST, str]] = [] @@ -774,7 +763,7 @@ class _Reader: tests, spans = self.conditions(test) return _Site( value, f"presence sets {described}", None, - [(test.lineno, first.end_lineno), *spans], # type: ignore[list-item] + [(test.lineno, end_line(first)), *spans], tests, self.cores(test), self._expands(read), ) @@ -799,7 +788,7 @@ def _caller_cores(cg: Configgen, caller: tuple[str, str]) -> list[str]: for stmt in node.body for n in ast.walk(stmt) ): return _cores_of(node.test) - src.fail(f"no core test calls {function}") + return src.fail(f"no core test calls {function}") def bios_sites(cg: Configgen, spec: GenericSites) -> list[Launcher]: @@ -906,7 +895,7 @@ def relative_folders( and all(isinstance(a, ast.Constant) for a in call.args) ): continue - section, key, value = (str(a.value) for a in call.args) # type: ignore[attr-defined] + section, key, value = (str(a.value) for a in call.args if isinstance(a, ast.Constant)) if not value.startswith("../"): continue resolved = posixpath.normpath(posixpath.join(base, value)) diff --git a/scripts/scraper/libretro_scraper.py b/scripts/scraper/libretro_scraper.py index 74571c117..e42949c92 100644 --- a/scripts/scraper/libretro_scraper.py +++ b/scripts/scraper/libretro_scraper.py @@ -10,6 +10,7 @@ from __future__ import annotations import urllib.error import urllib.request +from typing import TypedDict from .base_scraper import ( BaseScraper, @@ -124,6 +125,15 @@ def _core_info_files() -> list[str]: return info_files +class _ExtraSystem(TypedDict): + """A system System.dat lacks, with the files RetroArch needs for it.""" + + files: list[dict[str, object]] + core: str + manufacturer: str + docs: str + + class Scraper(BaseScraper): """Scraper for libretro System.dat.""" @@ -234,6 +244,31 @@ class Scraper(BaseScraper): metadata = self.fetch_metadata() core_meta = self._fetch_core_metadata() + systems = self._system_entries(requirements, core_meta) + self._add_extra_systems(systems) + self._add_arcade_files(systems) + self._add_system_files(systems) + self._add_includes_and_data(systems) + + return { + "platform": "RetroArch", + "version": metadata["retroarch_version"] or "", + "dat_version": metadata["dat_version"] or "", + "homepage": "https://www.retroarch.com", + "source": ( + f"https://github.com/{DATABASE_REPO}/blob/" + f"{self.revision or 'master'}/dat/System.dat" + ), + "base_destination": "system", + "hash_type": "sha1", + "verification_mode": "existence", + "systems": systems, + } + + @staticmethod + def _system_entries( + requirements: list[BiosRequirement], core_meta: dict[str, dict] + ) -> dict[str, dict]: systems = {} for req in requirements: if req.system not in systems: @@ -252,10 +287,14 @@ class Scraper(BaseScraper): systems[req.system]["files"].append(requirement_entry(req)) + return systems + + @staticmethod + def _add_extra_systems(systems: dict[str, dict]) -> None: # Systems not in System.dat but needed for RetroArch: added via # shared groups in _shared.yml. The includes directive is resolved # at load time by load_platform_config(). - EXTRA_SYSTEMS = { + EXTRA_SYSTEMS: dict[str, _ExtraSystem] = { # ref: Vircon32/libretro.c, virtual console, single BIOS "vircon32": { "files": [ @@ -292,6 +331,9 @@ class Scraper(BaseScraper): "files": [{**f, "curated": True} for f in sys_data["files"]], } + + @staticmethod + def _add_arcade_files(systems: dict[str, dict]) -> None: # Arcade BIOS present in the repo but absent from System.dat. # FBNeo expects them in system/ or system/fbneo/. # ref: fbneo/src/burner/libretro/libretro.cpp @@ -336,6 +378,9 @@ class Scraper(BaseScraper): } ) + + @staticmethod + def _add_system_files(systems: dict[str, dict]) -> None: # Extra files missing from System.dat for specific systems. # Each traced to the core's source code. EXTRA_SYSTEM_FILES = { @@ -455,6 +500,9 @@ class Scraper(BaseScraper): systems[sys_id]["files"].append({**ef, "curated": True}) existing.add(key) + + @staticmethod + def _add_includes_and_data(systems: dict[str, dict]) -> None: # Inject shared group references for systems that have core-specific # subdirectory requirements already defined in _shared.yml. # Note: fuse/ prefix NOT injected for sinclair-zx-spectrum. @@ -510,20 +558,6 @@ class Scraper(BaseScraper): if sys_id in systems: systems[sys_id]["data_directories"] = data_dirs - return { - "platform": "RetroArch", - "version": metadata["retroarch_version"] or "", - "dat_version": metadata["dat_version"] or "", - "homepage": "https://www.retroarch.com", - "source": ( - f"https://github.com/{DATABASE_REPO}/blob/" - f"{self.revision or 'master'}/dat/System.dat" - ), - "base_destination": "system", - "hash_type": "sha1", - "verification_mode": "existence", - "systems": systems, - } def main() -> None: diff --git a/scripts/scraper/mame_devices.py b/scripts/scraper/mame_devices.py index 65fa73d54..ec3c1e92a 100644 --- a/scripts/scraper/mame_devices.py +++ b/scripts/scraper/mame_devices.py @@ -19,14 +19,13 @@ files hash/.xml (attribute_softlists) and the floppy sound samples from __future__ import annotations import html -import io import re import zipfile from collections.abc import Callable, Collection, Iterable, Iterator from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from pathlib import Path -from typing import NamedTuple +from typing import IO, NamedTuple from common import yaml_load @@ -96,7 +95,7 @@ def _device_roms(body: bytes) -> list[dict]: @contextmanager -def open_listxml(path: Path) -> Iterator[io.BufferedIOBase]: +def open_listxml(path: Path) -> Iterator[IO[bytes]]: """Byte stream over a -listxml document, plain or as MAME's release zip.""" if path.suffix.lower() != ".zip": with path.open("rb") as stream: @@ -133,7 +132,7 @@ class Release(NamedTuple): machines: dict[str, MachineLinks] -def scan_release(stream: io.BufferedIOBase) -> Release: +def scan_release(stream: IO[bytes]) -> Release: """Release tag, device sets with dumped ROMs and every element's links. The document is read through a sliding window, never whole: the 0.289 @@ -192,7 +191,7 @@ def scan_release(stream: io.BufferedIOBase) -> Release: return Release(tag, devices, machines) -def scan_device_sets(stream: io.BufferedIOBase) -> tuple[str, dict[str, dict]]: +def scan_device_sets(stream: IO[bytes]) -> tuple[str, dict[str, dict]]: """Release tag of a -listxml document and its device sets with dumped ROMs.""" release = scan_release(stream) return release.tag, release.devices diff --git a/scripts/scraper/mame_hash_scraper.py b/scripts/scraper/mame_hash_scraper.py index 28557323b..c6e71dc91 100644 --- a/scripts/scraper/mame_hash_scraper.py +++ b/scripts/scraper/mame_hash_scraper.py @@ -303,8 +303,7 @@ def _format_diff( elif added: lines.append(f" + {len(added)} new sets available (main profile only)") - for set_name in updated: - lines.append(f" ~ {set_name}.zip (refreshed)") + lines.extend(f" ~ {set_name}.zip (refreshed)" for set_name in updated) oos = diff.get("out_of_scope", 0) lines.append(f" = {unchanged} unchanged") @@ -318,9 +317,9 @@ def _format_diff( def _fetch_hashes(force: bool) -> dict[str, Any]: cache = _load_cache() - if not force and not _is_stale(cache): + if not force and cache is not None and not _is_stale(cache): log.info("using cached data from %s", cache.get("fetched_at", "")) - return cache # type: ignore[return-value] + return cache try: tag = _get_release_tag() @@ -540,8 +539,10 @@ def _platform_archives() -> list[tuple[str, str]]: for name in list_registered_platforms(str(_PLATFORMS_DIR)): config = load_platform_config(name, str(_PLATFORMS_DIR)) for system, data in (config.get("systems") or {}).items(): - for entry in (data or {}).get("files") or []: - stated.append((str(entry.get("name") or ""), str(system))) + stated.extend( + (str(entry.get("name") or ""), str(system)) + for entry in (data or {}).get("files") or [] + ) return stated diff --git a/scripts/scraper/mame_parser.py b/scripts/scraper/mame_parser.py index e87daf195..baef20ee6 100644 --- a/scripts/scraper/mame_parser.py +++ b/scripts/scraper/mame_parser.py @@ -398,8 +398,7 @@ def _parse_rom_entries(block: str, keep_no_dump: bool = False) -> list[dict]: events: list[tuple[int, str, re.Match]] = [] for tag, pat in token_patterns: - for m in pat.finditer(block): - events.append((m.start(), tag, m)) + events.extend((m.start(), tag, m) for m in pat.finditer(block)) # Walked in source order: a ROM_LOAD belongs to the last ROM_REGION above it. events.sort(key=lambda e: e[0]) diff --git a/scripts/scraper/minui_scraper.py b/scripts/scraper/minui_scraper.py index b595f91f2..4dfb299d3 100644 --- a/scripts/scraper/minui_scraper.py +++ b/scripts/scraper/minui_scraper.py @@ -29,22 +29,13 @@ import urllib.parse from collections.abc import Callable, Mapping from dataclasses import dataclass -try: - from .base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_branch_head, - fetch_bytes, - github_headers, - ) -except ImportError: - from base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_branch_head, - fetch_bytes, - github_headers, - ) +from .base_scraper import ( + BaseScraper, + BiosRequirement, + fetch_branch_head, + fetch_bytes, + github_headers, +) PLATFORM_NAME = "minui" @@ -264,6 +255,10 @@ def platform_config( } +def _fetch_with_headers(url: str, headers: dict[str, str] | None = None) -> bytes: + return fetch_bytes(url, headers=headers) + + class Scraper(BaseScraper): """Pak scraper for one frontend of the MinUI family.""" @@ -275,7 +270,7 @@ class Scraper(BaseScraper): url: str | None = None, fetch: Callable[[str, dict[str, str] | None], bytes] | None = None, ) -> None: - self._fetch = fetch or (lambda u, h=None: fetch_bytes(u, headers=h)) + self._fetch = fetch or _fetch_with_headers self.revision = "" if url is None: self.revision = fetch_branch_head(self.variant.repo, self.variant.branch) @@ -336,10 +331,7 @@ class Scraper(BaseScraper): def main() -> None: - try: - from .base_scraper import scraper_cli - except ImportError: - from base_scraper import scraper_cli + from .base_scraper import scraper_cli scraper_cli(Scraper, "Scrape the MinUI pak list") diff --git a/scripts/scraper/misterfpga_scraper.py b/scripts/scraper/misterfpga_scraper.py index a03311256..f3cb28d3d 100644 --- a/scripts/scraper/misterfpga_scraper.py +++ b/scripts/scraper/misterfpga_scraper.py @@ -28,22 +28,13 @@ import urllib.request import zipfile from datetime import datetime, timezone -try: - from .base_scraper import ( - BaseScraper, - BiosRequirement, - _read_limited, - fetch_branch_head, - requirement_entry, - ) -except ImportError: - from base_scraper import ( - BaseScraper, - BiosRequirement, - _read_limited, - fetch_branch_head, - requirement_entry, - ) +from .base_scraper import ( + BaseScraper, + BiosRequirement, + _read_limited, + fetch_branch_head, + requirement_entry, +) PLATFORM_NAME = "misterfpga" @@ -238,10 +229,7 @@ class Scraper(BaseScraper): def main() -> None: """Entry point.""" - try: - from .base_scraper import scraper_cli - except ImportError: - from base_scraper import scraper_cli + from .base_scraper import scraper_cli scraper_cli(Scraper, "Scrape MiSTer FPGA BIOS requirements") diff --git a/scripts/scraper/myminui_scraper.py b/scripts/scraper/myminui_scraper.py index e24087317..0ef030196 100644 --- a/scripts/scraper/myminui_scraper.py +++ b/scripts/scraper/myminui_scraper.py @@ -3,10 +3,7 @@ from __future__ import annotations -try: - from . import minui_scraper -except ImportError: - import minui_scraper +from . import minui_scraper PLATFORM_NAME = "myminui" @@ -18,10 +15,7 @@ class Scraper(minui_scraper.Scraper): def main() -> None: - try: - from .base_scraper import scraper_cli - except ImportError: - from base_scraper import scraper_cli + from .base_scraper import scraper_cli scraper_cli(Scraper, "Scrape the MyMinUI pak list") diff --git a/scripts/scraper/nextui_scraper.py b/scripts/scraper/nextui_scraper.py index 923bc169c..300c3e4eb 100644 --- a/scripts/scraper/nextui_scraper.py +++ b/scripts/scraper/nextui_scraper.py @@ -3,10 +3,7 @@ from __future__ import annotations -try: - from . import minui_scraper -except ImportError: - import minui_scraper +from . import minui_scraper PLATFORM_NAME = "nextui" @@ -18,10 +15,7 @@ class Scraper(minui_scraper.Scraper): def main() -> None: - try: - from .base_scraper import scraper_cli - except ImportError: - from base_scraper import scraper_cli + from .base_scraper import scraper_cli scraper_cli(Scraper, "Scrape the NextUI pak list") diff --git a/scripts/scraper/recalbox_launchers.py b/scripts/scraper/recalbox_launchers.py index d56feabef..347a37b84 100644 --- a/scripts/scraper/recalbox_launchers.py +++ b/scripts/scraper/recalbox_launchers.py @@ -16,7 +16,8 @@ from __future__ import annotations import ast import posixpath import re -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterable, Iterator, Mapping +from dataclasses import dataclass, field from functools import partial from typing import Any @@ -29,6 +30,8 @@ from .configgen_launchers import ( _enclosing_test, _innermost_function, _locate, + assigned_value, + end_line, ) CONFIGGEN = "projects/configgen/configgen" @@ -75,6 +78,34 @@ FILE_OPTIONS = {"o2em_bios": "o2em"} BUILTIN_TOKEN = re.compile(r"<[^<>/]+>") +def _string(node: ast.AST | None) -> str | None: + """The value of a string constant.""" + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return node.value + return None + + +def _text(source: Source, node: ast.AST | None, what: str) -> str | None: + """The value of a string constant, None for any other node. A constant + that is not a string is a shape the reader does not know.""" + if not isinstance(node, ast.Constant): + return None + if not isinstance(node.value, str): + source.fail(f"line {node.lineno}: {what} is not a string: {node.value!r}") + return node.value + + +def _assignments( + nodes: Iterable[ast.AST], +) -> Iterator[tuple[ast.Assign | ast.AnnAssign, str, ast.expr]]: + """Each single-name assignment among `nodes`, its name and its value.""" + for node in nodes: + if isinstance(node, (ast.Assign, ast.AnnAssign)): + assigned = assigned_value(node) + if assigned is not None: + yield node, assigned[0], assigned[1] + + def spell(node: ast.AST | None, env: Mapping[str, str]) -> str | None: """The string an expression always evaluates to, if it can be read.""" if isinstance(node, ast.Constant): @@ -97,8 +128,9 @@ def spell(node: ast.AST | None, env: Mapping[str, str]) -> str | None: parts.append(part) return "".join(parts) if isinstance(node, ast.Call) and not node.keywords: - args = [spell(arg, env) for arg in node.args] - if any(arg is None for arg in args): + spelled = [spell(arg, env) for arg in node.args] + args = [arg for arg in spelled if arg is not None] + if len(args) != len(spelled): return None func = ast.unparse(node.func) if func == "os.path.join" and args: @@ -111,12 +143,10 @@ def spell(node: ast.AST | None, env: Mapping[str, str]) -> str | None: def module_strings(source: Source, prefix: str) -> dict[str, str]: """Module-level string constants, keyed as `prefix.NAME`.""" local: dict[str, str] = {} - for node in source.tree.body: - name = _assigned_name(node) - if name is not None: - value = spell(node.value, local) - if value is not None: - local[name] = value + for _node, name, expr in _assignments(source.tree.body): + value = spell(expr, local) + if value is not None: + local[name] = value return {f"{prefix}.{name}": value for name, value in local.items()} @@ -128,14 +158,11 @@ def _class_strings(source: Source, env: dict[str, str]) -> dict[str, Any]: continue # The class body reads its own attributes by their bare names. bare: dict[str, str] = {} - for node in cls.body: - name = _assigned_name(node) - if name is None: - continue + for _node, name, expr in _assignments(cls.body): scope = {**env, **found, **bare} - value: Any = spell(node.value, scope) - if value is None and isinstance(node.value, ast.Tuple): - items = [spell(e, scope) for e in node.value.elts] + value: Any = spell(expr, scope) + if value is None and isinstance(expr, ast.Tuple): + items = [spell(e, scope) for e in expr.elts] value = items if all(isinstance(i, str) for i in items) else None if value is None: continue @@ -149,17 +176,13 @@ def _class_strings(source: Source, env: dict[str, str]) -> dict[str, Any]: def _bound_once(scope: ast.AST, env: dict[str, str]) -> dict[str, str]: """Names a function binds exactly once to a readable string.""" counts: dict[str, int] = {} - nodes = [] - for node in ast.walk(scope): - name = _assigned_name(node) - if name is not None: - counts[name] = counts.get(name, 0) + 1 - nodes.append(node) + found = list(_assignments(ast.walk(scope))) + for _node, name, _expr in found: + counts[name] = counts.get(name, 0) + 1 local: dict[str, str] = {} - for node in sorted(nodes, key=lambda n: n.lineno): - name = _assigned_name(node) - if name is not None and counts[name] == 1: - value = spell(node.value, {**env, **local}) + for _node, name, expr in sorted(found, key=lambda item: item[0].lineno): + if counts[name] == 1: + value = spell(expr, {**env, **local}) if value is not None: local[name] = value return local @@ -173,12 +196,15 @@ def launcher_names(source: Source) -> dict[str, list[str]]: isinstance(node, ast.If) and isinstance(node.test, ast.Compare) and isinstance(node.test.ops[0], ast.Eq) - and isinstance(node.test.comparators[0], ast.Constant) ): continue + emulator = _text(source, node.test.comparators[0], "emulator name") + if emulator is None: + continue for call in _calls(ast.Module(body=node.body, type_ignores=[]), name="__import__"): - if call.args and isinstance(call.args[0], ast.Constant): - names.setdefault(call.args[0].value, []).append(node.test.comparators[0].value) + module = _text(source, call.args[0], "generator module") if call.args else None + if module is not None: + names.setdefault(module, []).append(emulator) if not names: source.fail("getGenerator imports no generator module") return names @@ -191,8 +217,9 @@ def _handler_map(source: Source, function: str, table: str) -> dict[str, list[st source.fail(f"{table} is not a dict display") handlers: dict[str, list[str]] = {} for key, value in zip(node.keys, node.values): - if isinstance(key, ast.Constant) and isinstance(value, ast.Attribute): - handlers.setdefault(value.attr, []).append(key.value) + name = _text(source, key, f"{table} key") + if name is not None and isinstance(value, ast.Attribute): + handlers.setdefault(value.attr, []).append(name) if not handlers: source.fail(f"{table} sends nothing to a handler") return handlers @@ -271,21 +298,27 @@ def _expr_call(stmt: ast.stmt) -> ast.Call | None: return None -def _systems(test: ast.expr, lists: Mapping[str, list[str]]) -> list[str] | None: +def _systems( + source: Source, test: ast.expr, lists: Mapping[str, list[str]] +) -> list[str] | None: """The systems a `system.Name == x`, `or` or `in list` test accepts.""" if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or): - parts = [_systems(value, lists) for value in test.values] - if any(part is None for part in parts): - return None - return [system for part in parts for system in part] + parts = [_systems(source, value, lists) for value in test.values] + systems: list[str] = [] + for part in parts: + if part is None: + return None + systems += part + return systems if ( isinstance(test, ast.Compare) and len(test.ops) == 1 and ast.unparse(test.left) in SYSTEM_NAMES ): right = test.comparators[0] - if isinstance(test.ops[0], ast.Eq) and isinstance(right, ast.Constant): - return [right.value] + system = _text(source, right, "system name") + if isinstance(test.ops[0], ast.Eq) and system is not None: + return [system] if isinstance(test.ops[0], ast.In) and isinstance(right, ast.Name) and right.id in lists: return list(lists[right.id]) return None @@ -304,7 +337,7 @@ def _condition(source: Source, tests: list[ast.expr], negated: bool, systems: list[str] = [] flags: list[str] = [] for test in tests: - found = _systems(test, lists) + found = _systems(source, test, lists) flag = _flag(test) if found is not None: systems += found @@ -372,12 +405,12 @@ def _branch( def _local_lists(source: Source, scope: ast.AST) -> dict[str, tuple[list[str], ast.stmt]]: - found = {} - for node in ast.walk(scope): - name = _assigned_name(node) - if name is not None and isinstance(node.value, ast.List): - values = [e.value for e in node.value.elts if isinstance(e, ast.Constant)] - if len(values) == len(node.value.elts): + found: dict[str, tuple[list[str], ast.stmt]] = {} + for node, name, value in _assignments(ast.walk(scope)): + if isinstance(value, ast.List): + values = [text for e in value.elts + if (text := _text(source, e, f"{name} item")) is not None] + if len(values) == len(value.elts): found[name] = (values, node) return found @@ -415,8 +448,9 @@ def system_directories(cg: Configgen) -> list[Launcher]: src.fail(f"line {case.pattern.lineno}: a guarded case is not read") pattern = case.pattern options = pattern.patterns if isinstance(pattern, ast.MatchOr) else [pattern] - cores = [p.value.value for p in options - if isinstance(p, ast.MatchValue) and isinstance(p.value, ast.Constant)] + cores = [core for p in options + if isinstance(p, ast.MatchValue) + and (core := _text(src, p.value, "core name")) is not None] wildcard = isinstance(pattern, ast.MatchAs) and pattern.pattern is None if not wildcard and len(cores) != len(options): src.fail(f"line {pattern.lineno}: case pattern is not a list of core names") @@ -429,10 +463,13 @@ def system_directories(cg: Configgen) -> list[Launcher]: condition = ", ".join(words) launchers.append(record( ", ".join(cores) or ALL_CORES, condition, call, - [(pattern.lineno, pattern.lineno), (start, call.end_lineno)], + [(pattern.lineno, pattern.lineno), (start, end_line(call))], )) - body, index = _locate(scope, lambda stmt: stmt is match) + located = _locate(scope, lambda stmt: stmt is match) + if located is None: + src.fail(f"no statement list holds the match on the core writing {SYSTEM_DIRECTORY}") + body, index = located overrides = _setter_branches(src, body[index + 1:], SYSTEM_DIRECTORY, lists) if not overrides: src.fail(f"no per-system {SYSTEM_DIRECTORY} after the match on the core") @@ -442,7 +479,7 @@ def system_directories(cg: Configgen) -> list[Launcher]: src.fail(f"line {call.lineno}: {SYSTEM_DIRECTORY} rewritten for every system") read = {n.id for n in ast.walk(tests[start]) if isinstance(n, ast.Name)} \ if start in tests else set() - spans = [(start, call.end_lineno)] + spans = [(start, end_line(call))] spans += [src.span(node) for name, (_v, node) in local_lists.items() if name in read] launchers.append(record( ALL_CORES, f"{condition}, replacing the directory chosen by core", call, spans, @@ -473,18 +510,20 @@ def core_assets(cg: Configgen) -> list[Launcher]: and isinstance(node.test, ast.Compare) and ast.unparse(node.test.left) == "self.system.Core" and isinstance(node.test.ops[0], ast.Eq) - and isinstance(node.test.comparators[0], ast.Constant) ): continue + core = _text(src, node.test.comparators[0], "core name") + if core is None: + continue calls = [c for stmt in node.body if (c := _expr_call(stmt)) and _setter(c, CORE_ASSETS)] if len(calls) != 1: continue call = calls[0] launchers.append(Launcher( - emulator=node.test.comparators[0].value, build="libretro", kind="passes_path", + emulator=core, build="libretro", kind="passes_path", names=[], search_dir=cg.bios_dir(spell(call.args[1], env), src, CORE_ASSETS), passes_to=f"retroarch {CORE_ASSETS}", - source_ref=src.ref([(node.lineno, call.end_lineno)]), + source_ref=src.ref([(node.lineno, end_line(call))]), )) if not launchers: src.fail(f"no core is given a {CORE_ASSETS}") @@ -516,101 +555,202 @@ def _skip_imports(body: list[ast.stmt], index: int) -> int: return index -def tos_cascade(cg: Configgen, src: Source, scope: ast.FunctionDef, emulator: str, - build: str) -> list[Launcher]: - """A TOS path chosen per machine, then tried down an existence cascade.""" - env = cg.env(src, scope) +def _written_path(call: ast.Call, paths: set[str]) -> str | None: + """X when the last argument of `call` is str(X), X one of `paths`.""" + if not call.args: + return None + last = call.args[-1] + if ( + isinstance(last, ast.Call) + and ast.unparse(last.func) == "str" + and isinstance(last.args[0], ast.Name) + and last.args[0].id in paths + ): + return last.args[0].id + return None + + +def _tos_setter( + src: Source, scope: ast.FunctionDef, env: Mapping[str, str] +) -> tuple[ast.Call, str, str]: + """The setting written from str(), the path variable, and where it goes.""" paths = { - name for node in ast.walk(scope) - if (name := _assigned_name(node)) is not None - and isinstance(node.value, ast.Call) - and ast.unparse(node.value.func) == "os.path.join" + name for _node, name, value in _assignments(ast.walk(scope)) + if isinstance(value, ast.Call) and ast.unparse(value.func) == "os.path.join" } setters = [ - call for call in _calls(scope, attr="setString") - if call.args - and isinstance(call.args[-1], ast.Call) - and ast.unparse(call.args[-1].func) == "str" - and isinstance(call.args[-1].args[0], ast.Name) - and call.args[-1].args[0].id in paths + (call, var) for call in _calls(scope, attr="setString") + if (var := _written_path(call, paths)) is not None ] if len(setters) != 1: src.fail(f"{scope.name}: expected one setting written from str()") - setter = setters[0] - var = setter.args[-1].args[0].id + setter, var = setters[0] keys = [spell(arg, env) for arg in setter.args[:-1]] if None in keys or len(keys) not in (1, 2): src.fail(f"{scope.name}: the TOS is written under a key that is not read") passes_to = f"[{keys[0]}] {keys[1]}" if len(keys) == 2 else f"core option {keys[0]}" + return setter, var, passes_to + + +@dataclass +class _Cascade: + """What the branches between the TOS assignment and its setter decide.""" + + end: ast.stmt + chosen: dict[str, str | None] = field(default_factory=dict) + fallbacks: list[str] = field(default_factory=list) + absolute: bool | None = None + override: tuple[str, str] | None = None + + +def _is_machine_branch(stmt: ast.If) -> bool: + return ( + isinstance(stmt.test, ast.Compare) + and isinstance(stmt.test.comparators[0], ast.Name) + and stmt.test.comparators[0].id.startswith("MACHINE_") + ) + + +def _machine_branches( + src: Source, env: Mapping[str, str], stmt: ast.If, var: str, cascade: _Cascade +) -> None: + """`if machine == MACHINE_X: var = ...` down its elif chain.""" + node: ast.If | None = stmt + while node is not None: + value = _assigns(node.body[0], var) if len(node.body) == 1 else None + machine = node.test.comparators[0] if isinstance(node.test, ast.Compare) else None + if value is None or not isinstance(machine, ast.Name): + src.fail(f"line {node.lineno}: machine branch does not set {var}") + cascade.chosen[machine.id] = spell(value, env) + orelse = node.orelse + node = orelse[0] if len(orelse) == 1 and isinstance(orelse[0], ast.If) else None + + +def _existence_steps( + cg: Configgen, src: Source, env: Mapping[str, str], stmt: ast.If, var: str, + cascade: _Cascade, +) -> None: + """`if not os.path.exists(var): var = ...`, each step nested in the last.""" + node: ast.If | None = stmt + while node is not None: + tested = _exists_arg(node.test) + is_abs = isinstance(tested, ast.Name) and tested.id == var + is_rel = ( + isinstance(tested, ast.Call) + and ast.unparse(tested.func) == "os.path.join" + and spell(tested.args[0], env) == cg.bios + and ast.unparse(tested.args[1]) == var + ) + if not (is_abs or is_rel) or ( + cascade.absolute is not None and cascade.absolute != is_abs + ): + src.fail(f"line {node.lineno}: the cascade tests something else than {var}") + cascade.absolute = is_abs + value = _assigns(node.body[0], var) + if value is None: + src.fail(f"line {node.lineno}: cascade step does not set {var}") + fallback = spell(value, env) + if fallback is None: + src.fail(f"line {node.lineno}: cascade step sets {var} to a path that is not read") + cascade.fallbacks.append(fallback) + inner = node.body[1:] + node = inner[0] if len(inner) == 1 and isinstance(inner[0], ast.If) else None + + +def _rom_override(src: Source, stmt: ast.If, var: str) -> tuple[str, ast.expr] | None: + """(marker, value) for `if "marker" in rom: var = value`.""" + if not ( + isinstance(stmt.test, ast.Compare) + and isinstance(stmt.test.ops[0], ast.In) + and ast.unparse(stmt.test.comparators[0]) in ("rom", "self.rom", "args.rom") + and len(stmt.body) == 1 + ): + return None + marker = _text(src, stmt.test.left, "rom path marker") + value = _assigns(stmt.body[0], var) + return None if marker is None or value is None else (marker, value) + + +def _read_cascade( + cg: Configgen, src: Source, env: Mapping[str, str], body: list[ast.stmt], index: int, + setter_stmt: ast.stmt | None, var: str, +) -> _Cascade: + """The machine choice, the existence cascade and the rom path override.""" + cascade = _Cascade(end=body[index]) + i = _skip_imports(body, index + 1) + while i < len(body) and body[i] is not setter_stmt: + stmt = body[i] + if not isinstance(stmt, ast.If): + src.fail(f"line {stmt.lineno}: unexpected statement in the TOS cascade") + override = _rom_override(src, stmt, var) + if _is_machine_branch(stmt): + _machine_branches(src, env, stmt, var, cascade) + elif _exists_arg(stmt.test) is not None: + _existence_steps(cg, src, env, stmt, var, cascade) + elif override is not None: + value = spell(override[1], env) + if value is None: + src.fail(f"line {stmt.lineno}: rom path override sets {var} to a path that is not read") + cascade.override = (override[0], value) + else: + src.fail(f"line {stmt.lineno}: unexpected branch in the TOS cascade") + cascade.end = stmt + i = _skip_imports(body, i + 1) + return cascade + + +def _machine_table(src: Source, scope: ast.FunctionDef) -> ast.stmt: + """The one dict display mapping rom paths to MACHINE_ constants.""" + dicts = [ + node for node in scope.body + if isinstance(node, (ast.Assign, ast.AnnAssign)) and isinstance(node.value, ast.Dict) + and all(isinstance(v, ast.Name) and v.id.startswith("MACHINE_") for v in node.value.values) + ] + if len(dicts) != 1: + src.fail(f"{scope.name}: no single rom path -> machine table") + return dicts[0] + + +def _machine_depends(src: Source, scope: ast.FunctionDef, table: ast.stmt) -> str: + """The machine comes from the rom path table, else from the config options read.""" + bound = {a.arg for a in scope.args.args} | { + n for node in ast.walk(scope) if (n := _assigned_name(node)) + } + options = [ + option for call in _calls(scope, attr="getInt") + if call.args and (option := _text(src, call.args[0], "machine option")) is not None + and isinstance(call.func, ast.Attribute) + and isinstance(call.func.value, ast.Name) and call.func.value.id in bound + ] + depends = f"machine read from the rom path through {_assigned_name(table)}" + if options: + depends += f", else option {', '.join(options)}" + return depends + + +def tos_cascade(cg: Configgen, src: Source, scope: ast.FunctionDef, emulator: str, + build: str) -> list[Launcher]: + """A TOS path chosen per machine, then tried down an existence cascade.""" + env = cg.env(src, scope) + setter, var, passes_to = _tos_setter(src, scope, env) located = _locate(scope, lambda stmt: _assigns(stmt, var) is not None) if located is None: src.fail(f"{scope.name}: {var} is never assigned") body, index = located - initial = spell(body[index].value, env) - chosen: dict[str, str] = {} - fallbacks: list[str] = [] - absolute = None - override: tuple[str, str] | None = None - end = body[index] - i = _skip_imports(body, index + 1) - while i < len(body) and body[i] is not _outermost_stmt(body, setter): - stmt = body[i] - if not isinstance(stmt, ast.If): - src.fail(f"line {stmt.lineno}: unexpected statement in the TOS cascade") - if ( - isinstance(stmt.test, ast.Compare) - and isinstance(stmt.test.comparators[0], ast.Name) - and stmt.test.comparators[0].id.startswith("MACHINE_") - ): - node: ast.If | None = stmt - while node is not None: - value = _assigns(node.body[0], var) if len(node.body) == 1 else None - machine = node.test.comparators[0] - if value is None or not isinstance(machine, ast.Name): - src.fail(f"line {node.lineno}: machine branch does not set {var}") - chosen[machine.id] = spell(value, env) - orelse = node.orelse - node = orelse[0] if len(orelse) == 1 and isinstance(orelse[0], ast.If) else None - elif _exists_arg(stmt.test) is not None: - node = stmt - while node is not None: - tested = _exists_arg(node.test) - is_abs = isinstance(tested, ast.Name) and tested.id == var - is_rel = ( - isinstance(tested, ast.Call) - and ast.unparse(tested.func) == "os.path.join" - and spell(tested.args[0], env) == cg.bios - and ast.unparse(tested.args[1]) == var - ) - if not (is_abs or is_rel) or (absolute is not None and absolute != is_abs): - src.fail(f"line {node.lineno}: the cascade tests something else than {var}") - absolute = is_abs - value = _assigns(node.body[0], var) - if value is None: - src.fail(f"line {node.lineno}: cascade step does not set {var}") - fallbacks.append(spell(value, env)) - inner = node.body[1:] - node = inner[0] if len(inner) == 1 and isinstance(inner[0], ast.If) else None - elif ( - isinstance(stmt.test, ast.Compare) - and isinstance(stmt.test.left, ast.Constant) - and isinstance(stmt.test.ops[0], ast.In) - and ast.unparse(stmt.test.comparators[0]) in ("rom", "self.rom", "args.rom") - and len(stmt.body) == 1 - and _assigns(stmt.body[0], var) is not None - ): - override = (stmt.test.left.value, spell(_assigns(stmt.body[0], var), env)) - else: - src.fail(f"line {stmt.lineno}: unexpected branch in the TOS cascade") - end = stmt - i = _skip_imports(body, i + 1) + initial = spell(_assigns(body[index], var), env) + setter_stmt = _outermost_stmt(body, setter) + cascade = _read_cascade(cg, src, env, body, index, setter_stmt, var) machines = [ (name, name.removeprefix("MACHINE_").replace("_", "").lower()) for node in scope.body if (name := _assigned_name(node)) and name.startswith("MACHINE_") and name != "MACHINE_UNKNOWN" ] - if not chosen or not fallbacks or absolute is None or not machines or initial is None: + absolute = cascade.absolute + if ( + not cascade.chosen or not cascade.fallbacks or absolute is None or not machines + or initial is None + ): src.fail(f"{scope.name}: no machine choice followed by an existence cascade") def relative(value: str | None) -> str: @@ -619,48 +759,37 @@ def tos_cascade(cg: Configgen, src: Source, scope: ast.FunctionDef, emulator: st src.fail(f"{scope.name}: {value} is not under {cg.bios}") return name - tokens = [v for v in fallbacks if BUILTIN_TOKEN.fullmatch(posixpath.basename(v))] - files = [relative(v) for v in fallbacks if v not in tokens] + tokens = [v for v in cascade.fallbacks if BUILTIN_TOKEN.fullmatch(posixpath.basename(v))] + files = [relative(v) for v in cascade.fallbacks if v not in tokens] if tokens: passes_to += f" ({', '.join(tokens)} when none is found)" - dicts = [ - node for node in scope.body - if isinstance(node, (ast.Assign, ast.AnnAssign)) and isinstance(node.value, ast.Dict) - and all(isinstance(v, ast.Name) and v.id.startswith("MACHINE_") for v in node.value.values) - ] - if len(dicts) != 1: - src.fail(f"{scope.name}: no single rom path -> machine table") - bound = {a.arg for a in scope.args.args} | { - n for node in ast.walk(scope) if (n := _assigned_name(node)) - } - options = [ - call.args[0].value for call in _calls(scope, attr="getInt") - if call.args and isinstance(call.args[0], ast.Constant) - and isinstance(call.func.value, ast.Name) and call.func.value.id in bound - ] - depends = f"machine read from the rom path through {_assigned_name(dicts[0])}" - if options: - depends += f", else option {', '.join(options)}" + table = _machine_table(src, scope) + depends = _machine_depends(src, scope, table) machine_lines = [n.lineno for n in scope.body if _assigned_name(n) in dict(machines)] - cascade = body[index:body.index(_outermost_stmt(body, setter)) + 1] - read = {n.id for stmt in cascade for n in ast.walk(stmt) if isinstance(n, ast.Name)} - helpers = [src.span(n) for n in scope.body - if _assigned_name(n) in read - {var} and spell(n.value, env) is not None] + if setter_stmt is None: + src.fail(f"{scope.name}: the setting is not written in the block assigning {var}") + read = { + n.id for stmt in body[index:body.index(setter_stmt) + 1] + for n in ast.walk(stmt) if isinstance(n, ast.Name) + } + helpers = [src.span(node) for node, name, value in _assignments(scope.body) + if name in read - {var} and spell(value, env) is not None] ref = src.ref([ (min(machine_lines), max(machine_lines)), - src.span(dicts[0]), + src.span(table), *helpers, - (src.span(body[index])[0], max(end.end_lineno, setter.end_lineno)), + (src.span(body[index])[0], max(end_line(cascade.end), end_line(setter))), ]) launchers = [] for constant, slot in machines: - first = relative(chosen.get(constant, initial)) + first = relative(cascade.chosen.get(constant, initial)) launchers.append(Launcher( emulator=emulator, build=build, kind="names_searched", slot=slot, names=list(dict.fromkeys([first, *files])), case_insensitive=False, search_dir=cg.bios, passes_to=passes_to, fails_when_missing=False, depends_on_option=depends, source_ref=ref, )) + override = cascade.override if override is not None and not BUILTIN_TOKEN.search(override[1]): launchers.append(Launcher( emulator=emulator, build=build, kind="fixed_name", slot=override[0], @@ -692,13 +821,11 @@ def hatari_libretro(cg: Configgen) -> list[Launcher]: ] -def gsplus(cg: Configgen) -> list[Launcher]: - """A path tried with os.path.exists down an else chain, and the - placeholders a per-game .gsplus file can name.""" - src = cg.source(GSPLUS) - generate = src.function("generate") - env = cg.env(src, generate) - emulator = cg.emulator(GSPLUS) +def _gsplus_tries( + cg: Configgen, src: Source, env: Mapping[str, str], body: list[ast.stmt], index: int +) -> tuple[list[str], str, ast.stmt]: + """The paths tried down the else chain, the key the found one is written to, + and the last statement of the chain.""" def exists_of(test: ast.expr, var: str) -> bool: return ( @@ -707,34 +834,32 @@ def gsplus(cg: Configgen) -> list[Launcher]: and ast.unparse(test.args[0]) == var ) - located = _locate(generate, lambda stmt: ( - _assigned_name(stmt) is not None - and cg.under_bios(spell(stmt.value, env)) is not None - )) - if located is None: - src.fail("generate assigns no path under BIOS") - body, index = located names: list[str] = [] - key = None + key: str | None = None stmts, i = body, index - last: ast.stmt = body[index] while True: - var = _assigned_name(stmts[i]) - name = cg.under_bios(spell(stmts[i].value, env)) + assigned = assigned_value(stmts[i]) + var = assigned[0] if assigned is not None else None + name = cg.under_bios(spell(assigned[1], env)) if assigned is not None else None test = stmts[i + 1] if i + 1 < len(stmts) else None - tried = isinstance(test, ast.If) and var is not None and exists_of(test.test, var) - if name is None or not tried: + if name is None or not ( + isinstance(test, ast.If) and var is not None and exists_of(test.test, var) + ): src.fail(f"line {stmts[i].lineno}: path is not tried with os.path.exists") + calls = [c for stmt in test.body if (c := _expr_call(stmt))] + for c in calls: + if not isinstance(c.func, ast.Attribute): + src.fail(f"line {c.lineno}: a call of the found branch is not a method call") written = [ - c for stmt in test.body - if (c := _expr_call(stmt)) and c.func.attr == "setString" + c for c in calls + if isinstance(c.func, ast.Attribute) and c.func.attr == "setString" and ast.unparse(c.args[1]) == var ] - if len(written) != 1 or (key is not None and written[0].args[0].value != key): + found = _string(written[0].args[0]) if len(written) == 1 else None + if found is None or (key is not None and found != key): src.fail(f"line {test.lineno}: the found path is not written to one key") - key = written[0].args[0].value + key = found names.append(name) - last = test orelse = test.orelse if len(orelse) == 2 and isinstance(orelse[1], ast.If): stmts, i = orelse, 0 @@ -744,19 +869,37 @@ def gsplus(cg: Configgen) -> list[Launcher]: ] if len(orelse) != 1 or not removed: src.fail(f"line {test.lineno}: the last miss does not remove {key}") - break + return names, key, test + + +def gsplus(cg: Configgen) -> list[Launcher]: + """A path tried with os.path.exists down an else chain, and the + placeholders a per-game .gsplus file can name.""" + src = cg.source(GSPLUS) + generate = src.function("generate") + env = cg.env(src, generate) + emulator = cg.emulator(GSPLUS) + + located = _locate(generate, lambda stmt: ( + (assigned := assigned_value(stmt)) is not None + and cg.under_bios(spell(assigned[1], env)) is not None + )) + if located is None: + src.fail("generate assigns no path under BIOS") + body, index = located + names, key, last = _gsplus_tries(cg, src, env, body, index) guard = next( node for node in ast.walk(generate) if isinstance(node, ast.If) and any(child is body[index] for child in node.orelse) ) - if not (isinstance(guard.test, ast.Compare) and isinstance(guard.test.left, ast.Constant)): + marker = _string(guard.test.left) if isinstance(guard.test, ast.Compare) else None + if marker is None: src.fail("the BIOS search is not the else of a rom path test") - marker = guard.test.left.value launchers = [Launcher( emulator=emulator, build="standalone", kind="names_searched", names=names, case_insensitive=False, search_dir=cg.bios, passes_to=key, fails_when_missing=False, depends_on_option=f'rom path without "{marker}"', - source_ref=src.ref([(src.span(body[index])[0], last.end_lineno)]), + source_ref=src.ref([(src.span(body[index])[0], end_line(last))]), )] for node in ast.walk(ast.Module(body=guard.body, type_ignores=[])): if not ( @@ -764,20 +907,21 @@ def gsplus(cg: Configgen) -> list[Launcher]: and isinstance(node.test, ast.Compare) and isinstance(node.test.left, ast.Call) and _setter(node.test.left, key, "getString") - and isinstance(node.test.comparators[0], ast.Constant) ): continue + placeholder = _text(src, node.test.comparators[0], "placeholder") + if placeholder is None: + continue written = [c for stmt in node.body if (c := _expr_call(stmt)) and _setter(c, key)] name = cg.under_bios(spell(written[0].args[1], env)) if len(written) == 1 else None if name is None: src.fail(f"line {node.lineno}: placeholder branch writes no BIOS path") - placeholder = node.test.comparators[0].value launchers.append(Launcher( emulator=emulator, build="standalone", kind="fixed_name", slot=placeholder, names=[name], case_insensitive=False, search_dir=cg.bios, passes_to=key, fails_when_missing=False, depends_on_option=f'"{marker}" game file whose {key} is {placeholder}', - source_ref=src.ref([(node.lineno, written[0].end_lineno)]), + source_ref=src.ref([(node.lineno, end_line(written[0]))]), )) if len(launchers) == 1: src.fail("no placeholder of a .gsplus game file is replaced") @@ -812,30 +956,31 @@ def amiberry(cg: Configgen) -> list[Launcher]: kick.fail("BIOS_PER_SYSTEM is not a dict display") chooser = kick.function("GetKickstartsFor") messages = [ - node.exc.args[0].value for node in ast.walk(chooser) + message for node in ast.walk(chooser) if isinstance(node, ast.Raise) and isinstance(node.exc, ast.Call) - and node.exc.args and isinstance(node.exc.args[0], ast.Constant) + and node.exc.args + and (message := _text(kick, node.exc.args[0], "failure message")) is not None ] aros = [ - call.args[0].value for call in _calls(chooser, name="AmigaBios") - if call.args and isinstance(call.args[0], ast.Constant) + aros_name for call in _calls(chooser, name="AmigaBios") + if call.args and (aros_name := _text(kick, call.args[0], "AROS name")) is not None ] builtin = [ - node.value.value for node in ast.walk(chooser) + rom for node in ast.walk(chooser) if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "self.rom" - and isinstance(node.value, ast.Constant) + and (rom := _text(kick, node.value, "built-in rom")) is not None ] if len(messages) != 2 or len(aros) != 2 or len(builtin) != 1: kick.fail("GetKickstartsFor no longer has two failures, the AROS pair and a built-in") config = cg.source(AMIBERRY_CONFIG) setter = config.function("SetKickstarts") - keys = [c.args[0].value for c in _calls(setter, attr="setString") - if isinstance(c.args[0], ast.Constant)] + keys = [setting for c in _calls(setter, attr="setString") + if (setting := _text(config, c.args[0], "kickstart key")) is not None] if len(keys) != 2: config.fail("SetKickstarts no longer writes a kickstart and an extended ROM") rom_key, ext_key = keys - tail = [(helper.lineno, helper.end_lineno), (chooser.lineno, chooser.end_lineno)] - config_ref = config.ref([(setter.lineno, setter.end_lineno)]) + tail = [(helper.lineno, end_line(helper)), (chooser.lineno, end_line(chooser))] + config_ref = config.ref([(setter.lineno, end_line(setter))]) emulator = cg.emulator(AMIBERRY_GENERATOR) launchers = [] @@ -889,19 +1034,19 @@ def _amiberry_rom_path(cg: Configgen, emulator: str) -> Launcher: return Launcher( emulator=emulator, build="standalone", kind="passes_path", names=[], search_dir=directory, passes_to="written: rom_path in amiberry.conf", - source_ref=src.ref([(call.lineno, call.end_lineno)]), + source_ref=src.ref([(call.lineno, end_line(call))]), ) -def pcsx2(cg: Configgen) -> list[Launcher]: - """A region token of the rom name picks a BIOS, then a fixed order.""" - src = cg.source(PCSX2) - env = cg.env(src) - chooser = src.function("__CheckPs2Bios") +def _ps2_exists_helper( + cg: Configgen, src: Source, env: Mapping[str, str], chooser: ast.FunctionDef +) -> tuple[str, str]: + """The directory the nested existence helper joins a name to, and its name.""" exists = next((f for f in chooser.body if isinstance(f, ast.FunctionDef)), None) - joined = exists.body[-1].value.args[0] if exists and isinstance(exists.body[-1], ast.Return) \ - and isinstance(exists.body[-1].value, ast.Call) and exists.body[-1].value.args else None - if not ( + returned = exists.body[-1] if exists is not None else None + joined = returned.value.args[0] if isinstance(returned, ast.Return) \ + and isinstance(returned.value, ast.Call) and returned.value.args else None + if exists is None or not ( isinstance(joined, ast.Call) and ast.unparse(joined.func) == "os.path.join" and ast.unparse(joined.args[-1]) == exists.args.args[0].arg ): @@ -909,36 +1054,67 @@ def pcsx2(cg: Configgen) -> list[Launcher]: search_dir = cg.bios_dir( spell(ast.Call(func=joined.func, args=joined.args[:-1], keywords=[]), env), src, "Exists" ) - helper = exists.name + return search_dir, exists.name + +def _region_branch(node: ast.If, helper: str) -> tuple[str, ast.expr, ast.expr | None] | None: + """(token, name tested, name returned) for `if token in rom and Exists(name): return x`.""" + test = node.test + if not ( + isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And) and len(test.values) == 2 + ): + return None + compare, call = test.values + token = _string(compare.left) if isinstance(compare, ast.Compare) else None + if not ( + token is not None + and isinstance(call, ast.Call) + and ast.unparse(call.func) == helper + and len(node.body) == 1 and isinstance(node.body[0], ast.Return) + ): + return None + return token, call.args[0], node.body[0].value + + +def _ps2_region_groups( + src: Source, env: Mapping[str, str], chooser: ast.FunctionDef, helper: str +) -> dict[tuple[str, str], list[str]]: + """(name returned, name tested) -> the rom name tokens that pick it.""" groups: dict[tuple[str, str], list[str]] = {} - chain = next((s for s in chooser.body if isinstance(s, ast.If)), None) - node = chain + node = next((s for s in chooser.body if isinstance(s, ast.If)), None) while node is not None: - test = node.test - ok = ( - isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And) and len(test.values) == 2 - and isinstance(test.values[0], ast.Compare) - and isinstance(test.values[0].left, ast.Constant) - and isinstance(test.values[1], ast.Call) - and ast.unparse(test.values[1].func) == helper - and len(node.body) == 1 and isinstance(node.body[0], ast.Return) - ) - if not ok: + branch = _region_branch(node, helper) + if branch is None: src.fail(f"line {node.lineno}: region branch is not `token in rom and Exists(name)`") - tested = spell(test.values[1].args[0], env) - given = spell(node.body[0].value, env) + token, tested_node, given_node = branch + tested = spell(tested_node, env) + given = spell(given_node, env) if tested is None or given is None: src.fail(f"line {node.lineno}: region branch names no BIOS constant") - groups.setdefault((given, tested), []).append(test.values[0].left.value) + groups.setdefault((given, tested), []).append(token) orelse = node.orelse node = orelse[0] if len(orelse) == 1 and isinstance(orelse[0], ast.If) else None - loops = [s for s in chooser.body if isinstance(s, ast.For) and isinstance(s.iter, ast.Tuple)] + return groups + + +def pcsx2(cg: Configgen) -> list[Launcher]: + """A region token of the rom name picks a BIOS, then a fixed order.""" + src = cg.source(PCSX2) + env = cg.env(src) + chooser = src.function("__CheckPs2Bios") + search_dir, helper = _ps2_exists_helper(cg, src, env, chooser) + + groups = _ps2_region_groups(src, env, chooser, helper) + loops = [ + (s, s.iter) for s in chooser.body + if isinstance(s, ast.For) and isinstance(s.iter, ast.Tuple) + ] if not groups or len(loops) != 1: src.fail("__CheckPs2Bios no longer tries region tokens then a fixed order") - fallback = [spell(e, env) for e in loops[0].iter.elts] - if None in fallback: - src.fail(f"line {loops[0].lineno}: fallback names are not BIOS constants") + loop, names = loops[0] + fallback = [name for e in names.elts if (name := spell(e, env)) is not None] + if len(fallback) != len(names.elts): + src.fail(f"line {loop.lineno}: fallback names are not BIOS constants") writes = [ call for call in _calls(src.tree, attr="setString") @@ -952,10 +1128,10 @@ def pcsx2(cg: Configgen) -> list[Launcher]: src.fail("the chosen BIOS is not written to one config key") constants = {v: k.removeprefix("self.").removeprefix("Pcsx2Generator.") for k, v in env.items() if k.startswith("Pcsx2Generator.BIOS_")} - names_lines = [n.lineno for n in ast.walk(src.tree) - if _assigned_name(n) in {c for c in constants.values()}] - ref = src.ref([(min(names_lines), max(names_lines)), (chooser.lineno, chooser.end_lineno), - (writes[0].lineno, writes[0].end_lineno)]) + names_lines = [node.lineno for node, name, _value in _assignments(ast.walk(src.tree)) + if name in set(constants.values())] + ref = src.ref([(min(names_lines), max(names_lines)), (chooser.lineno, end_line(chooser)), + (writes[0].lineno, end_line(writes[0]))]) make = partial(Launcher, emulator=cg.emulator(PCSX2), build="standalone", case_insensitive=False, search_dir=search_dir, passes_to=f"[{section}] {key}", fails_when_missing=False, source_ref=ref) @@ -989,19 +1165,19 @@ def _presence(cg: Configgen, src: Source, scope: ast.FunctionDef) -> tuple[list[ if not (isinstance(node, ast.If) and isinstance(node.test, ast.BoolOp) and isinstance(node.test.op, ast.Or)): continue - names = [ + found = [ cg.under_bios(spell(value.args[0], env)) for value in node.test.values if isinstance(value, ast.Call) and ast.unparse(value.func) == "os.path.exists" ] - if names and len(names) == len(node.test.values) and None not in names: + names = [name for name in found if name is not None] + if names and len(names) == len(node.test.values) and len(names) == len(found): return names, node - src.fail(f"{scope.name}: no presence test of BIOS paths") + raise LauncherShapeError(f"{src.path}: {scope.name}: no presence test of BIOS paths") def _returned(stmts: list[ast.stmt]) -> str | None: if len(stmts) == 1 and isinstance(stmts[0], ast.Return): - value = stmts[0].value - return value.value if isinstance(value, ast.Constant) else None + return _string(stmts[0].value) return None @@ -1013,46 +1189,46 @@ def dolphin(cg: Configgen) -> list[Launcher]: names, test = _presence(cg, src, checker) found, missing = _returned(test.body), _returned(test.orelse) calls = [ - call for call in _calls(src.tree, attr="setString") - if len(call.args) == 3 and isinstance(call.args[2], ast.Name) + (call, bound.id) for call in _calls(src.tree, attr="setString") + if len(call.args) == 3 and isinstance(bound := call.args[2], ast.Name) and any( - _assigned_name(n) == call.args[2].id and isinstance(n.value, ast.Call) - and isinstance(n.value.func, ast.Attribute) and n.value.func.attr == checker.name - for n in ast.walk(src.tree) + name == bound.id and isinstance(value, ast.Call) + and isinstance(value.func, ast.Attribute) and value.func.attr == checker.name + for _node, name, value in _assignments(ast.walk(src.tree)) ) ] if found is None or missing is None or len(calls) != 1: src.fail("CheckGamecubeIpl's answer is not written to one config key") - call = calls[0] + call, answer = calls[0] section, key = spell(call.args[0], env), spell(call.args[1], env) - binding = next(n for n in ast.walk(src.tree) - if _assigned_name(n) == call.args[2].id) + binding = next(node for node, name, _value in _assignments(ast.walk(src.tree)) + if name == answer) standalone = Launcher( emulator=cg.emulator(DOLPHIN), build="standalone", kind="fixed_name", names=names, case_insensitive=False, search_dir=cg.bios, passes_to=f"[{section}] {key} ({found} when one is present, else {missing})", fails_when_missing=False, - source_ref=src.ref([(checker.lineno, checker.end_lineno), src.span(binding), - (call.lineno, call.end_lineno)]), + source_ref=src.ref([(checker.lineno, end_line(checker)), src.span(binding), + (call.lineno, end_line(call))]), ) cores = cg.source(CORES) configure = cores.function("configureDolphin") names, test = _presence(cg, cores, configure) - options = [(c.args[0].value, c.args[1].value) for branch in (test.body, test.orelse) + options = [(option, value) for branch in (test.body, test.orelse) for stmt in branch if (c := _expr_call(stmt)) and len(c.args) == 2 - and all(isinstance(a, ast.Constant) for a in c.args)] + and (option := _text(cores, c.args[0], "core option")) is not None + and (value := _text(cores, c.args[1], "core option value")) is not None] if len(options) != 2 or options[0][0] != options[1][0]: cores.fail("configureDolphin's presence test does not set one core option both ways") option = options[0][0] on, off = (value.strip('"') for _o, value in options) - first = min(n.lineno for n in ast.walk(configure) - if _assigned_name(n) is not None and cg.under_bios( - spell(n.value, cg.env(cores, configure))) is not None) + first = min(node.lineno for node, _name, value in _assignments(ast.walk(configure)) + if cg.under_bios(spell(value, cg.env(cores, configure))) is not None) libretro = Launcher( emulator=cg.core("configureDolphin"), build="libretro", kind="fixed_name", names=names, case_insensitive=False, search_dir=cg.bios, passes_to=f"core option {option} ({on} when one is present, else {off})", - fails_when_missing=False, source_ref=cores.ref([(first, test.end_lineno)]), + fails_when_missing=False, source_ref=cores.ref([(first, end_line(test))]), ) return [standalone, libretro] @@ -1073,18 +1249,18 @@ def _config_paths(cg: Configgen, path: str, emulator: str) -> Launcher: if not writes: src.fail("writes no BIOS path into its config") conditions: list[str] = [] - spans = [] + spans: list[tuple[int, int]] = [] for function, call, *_rest in writes: - spans.append((call.lineno, call.end_lineno)) + spans.append((call.lineno, end_line(call))) test = next( (n for n in ast.walk(function) if isinstance(n, ast.If) and any(child is call for stmt in n.body for child in ast.walk(stmt))), None, ) if test is not None: spans.append((test.lineno, test.lineno)) - systems = _systems(test.test, {}) + systems = _systems(src, test.test, {}) words = f"system {', '.join(systems)}" if systems else _enclosing_test(function, call) - if words not in conditions: + if words is not None and words not in conditions: conditions.append(words) read = {ast.unparse(n) for arg in call.args for n in ast.walk(arg) if isinstance(n, (ast.Name, ast.Attribute))} @@ -1122,9 +1298,11 @@ def content_files(cg: Configgen) -> list[Launcher]: isinstance(node, ast.If) and isinstance(node.test, ast.Compare) and ast.unparse(node.test.left) == "core" - and isinstance(node.test.comparators[0], ast.Constant) ): continue + core = _text(src, node.test.comparators[0], "core name") + if core is None: + continue refs = [n for n in ast.walk(node) if isinstance(n, ast.Attribute) and ast.unparse(n.value) == "recalboxFiles"] names = list(dict.fromkeys( @@ -1141,11 +1319,11 @@ def content_files(cg: Configgen) -> list[Launcher]: constants = {n.attr for n in refs if cg.under_bios(spell(n, env)) is not None} lines = [n.lineno for n in files.tree.body if _assigned_name(n) in constants] launchers.append(Launcher( - emulator=node.test.comparators[0].value, build="libretro", kind="fixed_name", + emulator=core, build="libretro", kind="fixed_name", names=names, case_insensitive=False, search_dir=cg.bios, passes_to=f"written into {target}, which is loaded as the content", fails_when_missing=False, - source_ref=f"{src.ref([(node.lineno, node.end_lineno)])}, " + source_ref=f"{src.ref([(node.lineno, end_line(node))])}, " f"{files.ref([(line, line) for line in lines])}", )) if not launchers: @@ -1157,7 +1335,11 @@ def core_file_options(cg: Configgen, directories: list[Launcher]) -> list[Launch """System handlers that set a core option naming the file the core opens.""" src = cg.source(CORES) handlers = _handler_map(src, "fillCoresConfiguration", "specificSystemHandlers") - table = src.assignment("specificSystemHandlers", src.function("fillCoresConfiguration")) + table = src.assignment( + "specificSystemHandlers", src.function("fillCoresConfiguration") + ).value + if not isinstance(table, ast.Dict): + src.fail("specificSystemHandlers is not a dict display") defined = {n.name: n for n in ast.walk(src.tree) if isinstance(n, ast.FunctionDef)} launchers = [] for function_name, systems in handlers.items(): @@ -1166,16 +1348,19 @@ def core_file_options(cg: Configgen, directories: list[Launcher]) -> list[Launch continue for call in _calls(function, attr="setString"): if not (len(call.args) == 2 and all(isinstance(a, ast.Constant) for a in call.args) - and call.args[0].value in FILE_OPTIONS): + and _string(call.args[0]) in FILE_OPTIONS): + continue + option = _text(src, call.args[0], "core option") + value = _text(src, call.args[1], "core option value") + if option is None or value is None: continue - option = call.args[0].value core = FILE_OPTIONS[option] directory = core_directory(directories, core) - spans = [(k.lineno, k.lineno) for k, v in zip(table.value.keys, table.value.values) - if isinstance(v, ast.Attribute) and v.attr == function_name] + spans = [(k.lineno, k.lineno) for k, v in zip(table.keys, table.values) + if k is not None and isinstance(v, ast.Attribute) and v.attr == function_name] launchers.append(Launcher( emulator=core, build="libretro", kind="core_option", - names=[call.args[1].value.strip('"')], search_dir=directory.search_dir, + names=[value.strip('"')], search_dir=directory.search_dir, passes_to=f"core option {option}", depends_on_option=f"system {', '.join(systems)}", source_ref=f"{src.ref([(function.lineno, function.end_lineno or function.lineno), *spans])}, " diff --git a/scripts/scraper/retrobat_launchers.py b/scripts/scraper/retrobat_launchers.py index e2541fb50..924e7b577 100644 --- a/scripts/scraper/retrobat_launchers.py +++ b/scripts/scraper/retrobat_launchers.py @@ -14,10 +14,7 @@ import bisect import re from collections.abc import Callable, Iterator -try: - from .shell_launchers import is_feature_ref, split_ref -except ImportError: - from shell_launchers import is_feature_ref, split_ref # type: ignore[no-redef] +from .shell_launchers import is_feature_ref, split_ref GENERATORS = "emulatorLauncher/Generators" FEATURES = ".emulationstation/es_features.cfg" @@ -1534,20 +1531,19 @@ def cxbx(sources: dict[str, Source]) -> list[Record]: f"{CXBX_DATA_FOLDER}, the folder holding {settings.group(1)}," " which the launcher writes beside the binary" ) - records = [] - for match in named: - records.append( - _record( - match.group(1), - "standalone", - "passes_path", - [], - source_ref((src.path, [src.lines(match.start(), match.end()), settings_span])), - search_dir=f'', - passes_to=passes_to, - fails_when_missing=False, - ) + records = [ + _record( + match.group(1), + "standalone", + "passes_path", + [], + source_ref((src.path, [src.lines(match.start(), match.end()), settings_span])), + search_dir=f'', + passes_to=passes_to, + fails_when_missing=False, ) + for match in named + ] first, *rest = fallbacks others = "neither core nor emulator is " + " or ".join(f'"{m.group(1)}"' for m in named) records.append( @@ -1793,8 +1789,8 @@ def _negate(condition: str) -> str: anything else is wrapped in not (...). """ tests = condition.split(" && ") - compared = [re.fullmatch(rf"(\w+) != ({STRING})", t) for t in tests] - if all(compared): + compared = [m for t in tests if (m := re.fullmatch(rf"(\w+) != ({STRING})", t))] + if len(compared) == len(tests): return " || ".join(f"{m.group(1)} == {m.group(2)}" for m in compared) return f"not ({condition})" @@ -2071,7 +2067,7 @@ def _wrapped(expr: str, opener: str) -> str | None: return None inner = expr[len(opener) + 1 : -1] depth = 0 - for offset, char in _code_chars(inner): + for _offset, char in _code_chars(inner): depth += {"(": 1, ")": -1}.get(char, 0) if depth < 0: return None @@ -2165,16 +2161,9 @@ def _braceless_if(src: Source, offset: int) -> str | None: def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: """A path expression as text, with the lines of the declarations it read.""" expr = " ".join(expr.split()) - if re.fullmatch(_BIOS_ROOT, expr): - return "bios", [] - changed = re.fullmatch(r'Path\.ChangeExtension\(exe, "(\.\w+)"\)', expr) - if changed: - return f"{changed.group(1)}", [] - named = re.fullmatch(r'(?:Program\.)?AppConfig\.GetFullPath\("([\w.-]+)"\)', expr) - if named: - return f"<{named.group(1)}>", [] - if expr in _KNOWN: - return _KNOWN[expr], [] + fixed = _render_fixed(expr) + if fixed is not None: + return fixed replaced = re.fullmatch(rf"(.+)\.Replace\({STRING}, {STRING}\)", expr) if replaced: return _render(src, replaced.group(1), scope, before) @@ -2186,28 +2175,10 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: if len(ternary) == 2: branches = _split_top(ternary[1], ":") if len(branches) == 2: - first = _render(src, branches[0], scope, before) - second = _render(src, branches[1], scope, before) - if first is None or second is None: - return None - return f"{first[0]} when {ternary[0]}, else {second[0]}", first[1] + second[1] + return _render_choice(src, ternary[0], branches, scope, before) terms = _split_top(expr, " + ") if len(terms) > 1: - while terms and terms[0] == '"\\""': - terms = terms[1:] - while terms and terms[-1] in ('"\\""', '"\\\\"'): - terms = terms[:-1] - pieces, spans = [], [] - for term in terms: - if term == '";"': - pieces.append(";") - continue - done = _render(src, term, scope, before) - if done is None: - return None - pieces.append(done[0]) - spans += done[1] - return "".join(pieces), spans + return _render_terms(src, terms, scope, before) combine = _wrapped(expr, "Path.Combine") if combine is not None: base, *rest = _split_top(combine, ",") @@ -2219,28 +2190,78 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: if expr in _PATH_PARAMS: return _PATH_PARAMS[expr], [] if re.fullmatch(r"\w+", expr): - code = _code(src) - decls = list(re.compile(rf"(?:string|var)\s+{expr}\s*=\s*").finditer(code, scope, before)) - if not decls: - return (_PATH_PARAMS[expr], []) if expr in _PATH_PARAMS else None - decl = decls[-1] - decl_end = _statement_end(src, decl.end()) - base = _render(src, src.text[decl.end() : decl_end], scope, decl.start()) - if base is None: - return None - text, spans = base[0], [*base[1], src.lines(decl.start(), decl_end)] - for again in re.compile(rf"(? Rendered | None: + """The expressions that name one known folder or file.""" + if re.fullmatch(_BIOS_ROOT, expr): + return "bios", [] + changed = re.fullmatch(r'Path\.ChangeExtension\(exe, "(\.\w+)"\)', expr) + if changed: + return f"{changed.group(1)}", [] + named = re.fullmatch(r'(?:Program\.)?AppConfig\.GetFullPath\("([\w.-]+)"\)', expr) + if named: + return f"<{named.group(1)}>", [] + if expr in _KNOWN: + return _KNOWN[expr], [] + return None + + +def _render_choice( + src: Source, condition: str, branches: list[str], scope: int, before: int +) -> Rendered | None: + """A `condition ? a : b` expression.""" + first = _render(src, branches[0], scope, before) + second = _render(src, branches[1], scope, before) + if first is None or second is None: + return None + return f"{first[0]} when {condition}, else {second[0]}", first[1] + second[1] + + +def _render_terms(src: Source, terms: list[str], scope: int, before: int) -> Rendered | None: + """A concatenation, the quotes wrapped around it dropped.""" + while terms and terms[0] == '"\\""': + terms = terms[1:] + while terms and terms[-1] in ('"\\""', '"\\\\"'): + terms = terms[:-1] + pieces, spans = [], [] + for term in terms: + if term == '";"': + pieces.append(";") + continue + done = _render(src, term, scope, before) + if done is None: + return None + pieces.append(done[0]) + spans += done[1] + return "".join(pieces), spans + + +def _render_variable(src: Source, expr: str, scope: int, before: int) -> Rendered | None: + """A local variable, from its declaration and every later assignment before use.""" + code = _code(src) + decls = list(re.compile(rf"(?:string|var)\s+{expr}\s*=\s*").finditer(code, scope, before)) + if not decls: + return (_PATH_PARAMS[expr], []) if expr in _PATH_PARAMS else None + decl = decls[-1] + decl_end = _statement_end(src, decl.end()) + declared = _render(src, src.text[decl.end() : decl_end], scope, decl.start()) + if declared is None: + return None + text, spans = declared[0], [*declared[1], src.lines(decl.start(), decl_end)] + for again in re.compile(rf"(?= 4: - value = _unquote(words[3]) - if _mentions_bios(value): - section = words[5] if len(words) > 5 else None - where = f"[{section}] {words[2]}" if section else words[2] - target = self.config_name(words[1]) - if _is_file(value): - settings.setdefault(("fixed_name", target, depends or ""), []).append( - (number, value, where) - ) - else: - key = ("passes_path", target, where, depends or "") - settings.setdefault(key, []).append((number, value, where)) + self._setting(number, words, depends, settings) continue if command == "dir_prep" and len(words) == 3: self._dir_prep(path, number, words[1], words[2], depends) @@ -195,18 +181,7 @@ class Component: copies.setdefault((folder, depends), []).append((number, name, target)) continue if command == "tar" and "-C" in words and _mentions_bios(words[words.index("-C") + 1]): - if "-czf" in words: - continue - archive = next((w for w in words if w.endswith((".tar.gz", ".tgz", ".tar"))), None) - if archive is None: - raise LauncherPatternMissing( - f"{path}:{number}", f"tar into bios/ of no archive: {raw}" - ) - self.record( - "copies", [], [(path, number)], search_dir=archive, - passes_to=words[words.index("-C") + 1], fails_when_missing=False, - depends_on_option=depends, - ) + self._tar(path, number, words, raw, depends) continue if command == "sed" and PLACEHOLDER in raw: self._preset(script, number, words) @@ -218,8 +193,8 @@ class Component: raise LauncherPatternMissing( f"{path}:{number}", f"unrecognised use of $bios_path: {raw}" ) - for key, hits in settings.items(): - self._settings(path, key, hits) + for setting, hits in settings.items(): + self._settings(path, setting, hits) for (folder, depends), hits in copies.items(): names = [name for _n, name, _t in hits] targets = [target for _n, _name, target in hits] @@ -229,6 +204,40 @@ class Component: depends_on_option=depends or None, ) + def _setting( + self, number: int, words: list[str], depends: str | None, + settings: dict[tuple[str, ...], list[tuple[int, str, str]]], + ) -> None: + """A set_setting_value that writes a bios/ path into a config.""" + value = _unquote(words[3]) + if not _mentions_bios(value): + return + section = words[5] if len(words) > 5 else None + where = f"[{section}] {words[2]}" if section else words[2] + target = self.config_name(words[1]) + if _is_file(value): + settings.setdefault(("fixed_name", target, depends or ""), []).append( + (number, value, where) + ) + else: + key = ("passes_path", target, where, depends or "") + settings.setdefault(key, []).append((number, value, where)) + + def _tar(self, path: str, number: int, words: list[str], raw: str, depends: str | None) -> None: + """A tar that extracts an archive into bios/.""" + if "-czf" in words: + return + archive = next((w for w in words if w.endswith((".tar.gz", ".tgz", ".tar"))), None) + if archive is None: + raise LauncherPatternMissing( + f"{path}:{number}", f"tar into bios/ of no archive: {raw}" + ) + self.record( + "copies", [], [(path, number)], search_dir=archive, + passes_to=words[words.index("-C") + 1], fails_when_missing=False, + depends_on_option=depends, + ) + def _settings(self, path: str, key: tuple[str, ...], hits: list[tuple[int, str, str]]) -> None: kind, target = key[0], key[1] depends = key[-1] or None diff --git a/scripts/scraper/retrodeck_scraper.py b/scripts/scraper/retrodeck_scraper.py index 7b1bd3b14..00df2dbd3 100644 --- a/scripts/scraper/retrodeck_scraper.py +++ b/scripts/scraper/retrodeck_scraper.py @@ -27,6 +27,7 @@ Verification logic (api_data_processing.sh:289-405): from __future__ import annotations +import importlib import json import re import sys @@ -34,29 +35,22 @@ import urllib.error import urllib.request from pathlib import Path -try: - from .base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_branch_head, - fetch_bytes, - fetch_github_latest_version, - github_headers, - requirement_entry, - ) - from .retrodeck_launchers import extract_launchers -except ImportError: +if not __package__: + # Allow running directly: python scripts/scraper/retrodeck_scraper.py sys.path.insert(0, str(Path(__file__).parent.parent)) - from scraper.base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_branch_head, - fetch_bytes, - fetch_github_latest_version, - github_headers, - requirement_entry, - ) - from scraper.retrodeck_launchers import extract_launchers + importlib.import_module("scraper") + __package__ = "scraper" + +from .base_scraper import ( + BaseScraper, + BiosRequirement, + fetch_branch_head, + fetch_bytes, + fetch_github_latest_version, + github_headers, + requirement_entry, +) +from .retrodeck_launchers import extract_launchers PLATFORM_NAME = "retrodeck" COMPONENTS_REPO = "RetroDECK/components" @@ -253,9 +247,10 @@ def _extract_bios_entries(component_val: dict) -> list[dict]: bios_data = [bios_data] if not isinstance(bios_data, list): return - for entry in bios_data: - if isinstance(entry, dict) and entry.get("filename", "").strip(): - entries.append(entry) + entries.extend( + entry for entry in bios_data + if isinstance(entry, dict) and entry.get("filename", "").strip() + ) if "bios" in component_val: collect(component_val["bios"]) @@ -282,6 +277,112 @@ def _map_system(raw_system: str) -> str | None: return raw_system +def _entry_folder(paths_raw: object) -> str | None: + """The folder a BIOS entry's paths resolve to, None for a saves-only entry.""" + if isinstance(paths_raw, str): + resolved = _resolve_path(paths_raw) + elif isinstance(paths_raw, list): + resolved = "" + for p in paths_raw: + rp = _resolve_path(str(p)) + if not rp.startswith("saves"): + resolved = rp + break + if not resolved: + return None + else: + resolved = "" + + # Skip saves-only entries + if resolved.startswith("saves"): + return None + return resolved + + +def _entry_md5(md5_raw: object) -> str: + """MD5 handling: sanitize upstream errors.""" + if isinstance(md5_raw, list): + parts = [str(m).strip().lower() for m in md5_raw if m] + elif md5_raw: + parts = [str(md5_raw).strip().lower()] + else: + parts = [] + # Keep only valid 32-char hex MD5 hashes + valid = [p for p in parts if re.fullmatch(r"[0-9a-f]{32}", p)] + return ",".join(valid) + + +def _entry_requirement(entry: dict, comp_key: str, default_system: object) -> BiosRequirement | None: + filename = entry["filename"].strip() + raw_system = entry.get("system", default_system) + if isinstance(raw_system, list): + raw_system = raw_system[0] if raw_system else default_system + + system = _map_system(str(raw_system)) + if system is None: + return None + + resolved = _entry_folder(entry.get("paths")) + if resolved is None: + return None + + # Build destination: default to bios/ if no path specified + if resolved: + destination = f"{resolved}/{filename}" + else: + destination = f"bios/{filename}" + + md5 = _entry_md5(entry.get("md5", "")) + + required_raw = entry.get("required", "") + required = bool(required_raw) and str(required_raw).lower() not in ( + "false", + "no", + "optional", + "", + ) + + native: dict[str, object] = {"component": comp_key} + description = str(entry.get("description", "")).strip() + if description: + native["description"] = description + if required_raw not in (None, ""): + native["required_label"] = str(required_raw) + + sha256 = str(entry.get("sha256", "")).strip().lower() + + return BiosRequirement( + name=filename, + system=system, + destination=destination, + md5=md5, + sha256=sha256 or None, + required=required, + native_id=str(raw_system), + native=native, + ) + + +def _warn_md5_conflict( + requirements: list[BiosRequirement], key: tuple[str, str], req: BiosRequirement +) -> None: + existing = next( + ( + r + for r in requirements + if (r.system, r.name.lower()) == key + ), + None, + ) + md5 = req.md5 + if existing and md5 and existing.md5 and md5 != existing.md5: + print( + f" WARNING: {req.name} ({req.system}): MD5 conflict " + f"({existing.md5[:12]}... vs {md5[:12]}...)", + file=sys.stderr, + ) + + class Scraper(BaseScraper): """RetroDECK BIOS scraper from component manifests.""" @@ -416,7 +517,7 @@ class Scraper(BaseScraper): requirements: list[BiosRequirement] = [] seen: set[tuple[str, str]] = set() - for comp_name, manifest in manifests: + for _comp_name, manifest in manifests: for comp_key, comp_val in manifest.items(): if not isinstance(comp_val, dict): continue @@ -426,100 +527,15 @@ class Scraper(BaseScraper): default_system = default_system[0] if default_system else comp_key for entry in _extract_bios_entries(comp_val): - filename = entry["filename"].strip() - raw_system = entry.get("system", default_system) - if isinstance(raw_system, list): - raw_system = raw_system[0] if raw_system else default_system - - system = _map_system(str(raw_system)) - if system is None: + req = _entry_requirement(entry, comp_key, default_system) + if req is None: continue - - paths_raw = entry.get("paths") - if isinstance(paths_raw, str): - resolved = _resolve_path(paths_raw) - elif isinstance(paths_raw, list): - resolved = "" - for p in paths_raw: - rp = _resolve_path(str(p)) - if not rp.startswith("saves"): - resolved = rp - break - if not resolved: - continue - else: - resolved = "" - - # Skip saves-only entries - if resolved.startswith("saves"): - continue - - # Build destination: default to bios/ if no path specified - if resolved: - destination = f"{resolved}/{filename}" - else: - destination = f"bios/{filename}" - - # MD5 handling: sanitize upstream errors - md5_raw = entry.get("md5", "") - if isinstance(md5_raw, list): - parts = [str(m).strip().lower() for m in md5_raw if m] - elif md5_raw: - parts = [str(md5_raw).strip().lower()] - else: - parts = [] - # Keep only valid 32-char hex MD5 hashes - valid = [p for p in parts if re.fullmatch(r"[0-9a-f]{32}", p)] - md5 = ",".join(valid) - - required_raw = entry.get("required", "") - required = bool(required_raw) and str(required_raw).lower() not in ( - "false", - "no", - "optional", - "", - ) - - key = (system, filename.lower()) + key = (req.system, req.name.lower()) if key in seen: - existing = next( - ( - r - for r in requirements - if (r.system, r.name.lower()) == key - ), - None, - ) - if existing and md5 and existing.md5 and md5 != existing.md5: - print( - f" WARNING: {filename} ({system}): MD5 conflict " - f"({existing.md5[:12]}... vs {md5[:12]}...)", - file=sys.stderr, - ) + _warn_md5_conflict(requirements, key, req) continue seen.add(key) - - native: dict[str, object] = {"component": comp_key} - description = str(entry.get("description", "")).strip() - if description: - native["description"] = description - if required_raw not in (None, ""): - native["required_label"] = str(required_raw) - - sha256 = str(entry.get("sha256", "")).strip().lower() - - requirements.append( - BiosRequirement( - name=filename, - system=system, - destination=destination, - md5=md5, - sha256=sha256 or None, - required=required, - native_id=str(raw_system), - native=native, - ) - ) + requirements.append(req) return requirements @@ -578,10 +594,7 @@ class Scraper(BaseScraper): def main() -> None: - try: - from .base_scraper import scraper_cli - except ImportError: - from scraper.base_scraper import scraper_cli + from .base_scraper import scraper_cli scraper_cli(Scraper, "Scrape RetroDECK BIOS requirements") diff --git a/scripts/scraper/retropie_launchers.py b/scripts/scraper/retropie_launchers.py index 544eb1adb..292b3161e 100644 --- a/scripts/scraper/retropie_launchers.py +++ b/scripts/scraper/retropie_launchers.py @@ -23,6 +23,7 @@ import re import shlex from collections.abc import Iterator from dataclasses import dataclass, field +from functools import partial from itertools import product from pathlib import PurePosixPath from typing import Any @@ -224,8 +225,8 @@ class Scripts: lines = text.splitlines() fields: dict[str, tuple[str, int]] = {} for found in _MODULE_FIELD.finditer(text): - line = text.count("\n", 0, found.start()) + 1 - fields.setdefault(found.group(1), (found.group(2), line)) + field_line = text.count("\n", 0, found.start()) + 1 + fields.setdefault(found.group(1), (found.group(2), field_line)) if "id" not in fields: return None repo = fields.get("repo") @@ -299,21 +300,15 @@ class Scripts: for number, text, opener in _logical_lines(module.lines, start + 1, end - 1): stripped = text.strip() if array is not None: - body = re.sub(r"\s+#.*$", "", stripped) - closed = body.endswith(")") - array[1].append(body[:-1] if closed else body) - if closed: - words = _split(" ".join(array[1])) - env[array[0]] = [v for w in words for v in self.expand(w, package, env)] + if self._array_line(array, stripped, package, env): array = None continue if opener is not None: if self._live(branches): - words = [self.expand(w, package, env) for w in stripped.split()] events.setdefault((module.path, number), Event( - module.path, number, words, stripped, - conditions + self._shown(branches, package, env), True, - [self.expand(w, package, env) for w in _split(opener)], + module.path, number, self._expand_all(stripped.split(), package, env), + stripped, conditions + self._shown(branches, package, env), True, + self._expand_all(_split(opener), package, env), )) continue if not stripped or stripped.startswith("#"): @@ -322,35 +317,16 @@ class Scripts: continue if not self._live(branches): continue - loop = _FOR.match(stripped) - if loop is not None: - values = [v for w in _split(loop.group(2)) for v in self.expand(w, package, env)] - loops.append((loop.group(1), env.get(loop.group(1)))) - env[loop.group(1)] = values - continue - if re.match(r"^(while|until)\b|^for\s*\(\(", stripped): - loops.append((None, None)) - continue - if stripped == "done" or stripped.startswith("done ") or stripped.startswith("done;"): - if loops: - var, previous = loops.pop() - if var is not None: - if previous is None: - env.pop(var, None) - else: - env[var] = previous + if self._loop(stripped, package, env, loops): continue if stripped in ("do", "then", "else", "fi", "esac", "{", "}"): continue - guard = re.match(r"^\[\[\s*(.*?)\s*\]\]\s*&&\s*(.*)$", stripped) - shown = conditions + self._shown(branches, package, env) - if guard is not None: - verdict = self._md_id_test(f"[[ {guard.group(1)} ]]", package) - if verdict is False or "$md_mode" in guard.group(1) or "$mode" in guard.group(1): - continue - if verdict is None: - shown = shown + [self._render(guard.group(1), package, env)] - stripped = guard.group(2) + guarded = self._guard( + stripped, package, env, conditions + self._shown(branches, package, env) + ) + if guarded is None: + continue + stripped, shown = guarded opens = re.match(r"^(?:local\s+)?([A-Za-z_]\w*)=\(([^)]*)$", stripped) if opens is not None: array = (opens.group(1), [opens.group(2)]) @@ -362,10 +338,79 @@ class Scripts: events.setdefault( (module.path, number), Event(module.path, number, words, stripped, shown, False) ) - callee = words[0][0] if words and words[0] else None - if callee in self.owner and callee != name: - call_args = {str(i): w for i, w in enumerate(words[1:], 1)} - self._walk(package, callee, call_args, shown, stack | {name}, events) + self._descend(package, name, words, shown, stack, events) + + def _descend( + self, + package: Module, + name: str, + words: list[list[str]], + shown: list[str], + stack: set[str], + events: dict[tuple[str, int], Event], + ) -> None: + """Walk the function a statement calls, with the words it passes.""" + callee = words[0][0] if words and words[0] else None + if callee in self.owner and callee != name: + call_args = {str(i): w for i, w in enumerate(words[1:], 1)} + self._walk(package, callee, call_args, shown, stack | {name}, events) + + def _expand_all( + self, words: list[str], package: Module, env: dict[str, list[str]] + ) -> list[list[str]]: + return [self.expand(w, package, env) for w in words] + + def _array_line( + self, array: tuple[str, list[str]], stripped: str, package: Module, + env: dict[str, list[str]], + ) -> bool: + """Add one line to a multi-line array, and say whether it closed it.""" + body = re.sub(r"\s+#.*$", "", stripped) + closed = body.endswith(")") + array[1].append(body[:-1] if closed else body) + if closed: + words = _split(" ".join(array[1])) + env[array[0]] = [v for w in words for v in self.expand(w, package, env)] + return closed + + def _loop( + self, stripped: str, package: Module, env: dict[str, list[str]], + loops: list[tuple[str | None, list[str] | None]], + ) -> bool: + """Track for/while/until/done, and say whether the line was one of them.""" + loop = _FOR.match(stripped) + if loop is not None: + values = [v for w in _split(loop.group(2)) for v in self.expand(w, package, env)] + loops.append((loop.group(1), env.get(loop.group(1)))) + env[loop.group(1)] = values + return True + if re.match(r"^(while|until)\b|^for\s*\(\(", stripped): + loops.append((None, None)) + return True + if stripped == "done" or stripped.startswith(("done ", "done;")): + if loops: + var, previous = loops.pop() + if var is not None: + if previous is None: + env.pop(var, None) + else: + env[var] = previous + return True + return False + + def _guard( + self, stripped: str, package: Module, env: dict[str, list[str]], shown: list[str] + ) -> tuple[str, list[str]] | None: + """The statement a `[[ test ]] && statement` runs and its conditions, None if never.""" + guard = re.match(r"^\[\[\s*(.*?)\s*\]\]\s*&&\s*(.*)$", stripped) + if guard is None: + return stripped, shown + verdict = self._md_id_test(f"[[ {guard.group(1)} ]]", package) + if verdict is False or "$md_mode" in guard.group(1) or "$mode" in guard.group(1): + return None + if verdict is None: + shown = shown + [self._render(guard.group(1), package, env)] + return guard.group(2), shown def _branch( self, stripped: str, package: Module, env: dict[str, list[str]], @@ -462,14 +507,10 @@ class Scripts: if not bound: results.append(braced) continue - for values in product(*(env[n] for n in bound)): - chosen = dict(zip(bound, values)) - - def replace(found: re.Match[str]) -> str: - key = found.group(1) or found.group(3) - return chosen.get(key, found.group(0)) - - results.append(_VAR.sub(replace, braced)) + results.extend( + _VAR.sub(partial(_bound_value, dict(zip(bound, values))), braced) + for values in product(*(env[n] for n in bound)) + ) return results @@ -483,6 +524,11 @@ LIST_SEPARATORS = {"advmame": ":", "advmame-0.94": ":", "advmame-1.4": ":"} DEFAULT_LIST_SEPARATOR = ";" +def _bound_value(chosen: dict[str, str], found: re.Match[str]) -> str: + key = found.group(1) or found.group(3) + return chosen.get(key, found.group(0)) + + def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR) -> bool: """An iniSet whose value is a list of folders below the roms root. @@ -494,7 +540,7 @@ def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR) return False parts = [p for p in event.words[2][0].split(separator) if p] return len(parts) > 1 and all( - p.startswith(ROMDIR + "/") or p.startswith("${romdir}/") for p in parts + p.startswith((ROMDIR + "/", "${romdir}/")) for p in parts ) @@ -541,9 +587,11 @@ class PackageReader: def read(self) -> list[Launcher]: events = self.scripts.walk(self.package) for event in events: - if not event.heredoc and event.words and event.words[0] == ["copyDefaultConfig"]: - if len(event.words) >= 3 and len(event.words[1]) == 1 and len(event.words[2]) == 1: - self.installed_as.setdefault(event.words[1][0], event.words[2][0]) + if ( + not event.heredoc and event.words and event.words[0] == ["copyDefaultConfig"] + and len(event.words) >= 3 and len(event.words[1]) == 1 and len(event.words[2]) == 1 + ): + self.installed_as.setdefault(event.words[1][0], event.words[2][0]) links: list[Event] = [] for event in events: if not event.words or not event.words[0]: @@ -825,8 +873,8 @@ class PackageReader: if flag.startswith("-") and _mentions_bios(value) ] found += [ - tuple(token.split("=", 1)) for token in tokens - if token.startswith("-") and "=" in token and _mentions_bios(token.split("=", 1)[1]) + (head, tail) for head, sep, tail in (token.partition("=") for token in tokens) + if head.startswith("-") and sep and _mentions_bios(tail) ] if not found: raise LauncherPatternMissing( diff --git a/scripts/scraper/retropie_scraper.py b/scripts/scraper/retropie_scraper.py index 488fe7d11..44ca42a21 100644 --- a/scripts/scraper/retropie_scraper.py +++ b/scripts/scraper/retropie_scraper.py @@ -29,16 +29,10 @@ import tarfile import urllib.error import urllib.request -try: - from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head - from .retropie_launchers import SCRIPTMODULES - from .retropie_launchers import SECTIONS as _SCRIPT_SECTIONS - from .retropie_launchers import extract_launchers -except ImportError: - from base_scraper import BaseScraper, BiosRequirement, fetch_branch_head - from retropie_launchers import SCRIPTMODULES - from retropie_launchers import SECTIONS as _SCRIPT_SECTIONS - from retropie_launchers import extract_launchers +from .base_scraper import BaseScraper, BiosRequirement, fetch_branch_head +from .retropie_launchers import SCRIPTMODULES +from .retropie_launchers import SECTIONS as _SCRIPT_SECTIONS +from .retropie_launchers import extract_launchers PLATFORM_NAME = "retropie" @@ -189,10 +183,7 @@ class Scraper(BaseScraper): def main() -> None: - try: - from .base_scraper import scraper_cli - except ImportError: - from base_scraper import scraper_cli + from .base_scraper import scraper_cli scraper_cli(Scraper, "Scrape the RetroPie package list") diff --git a/scripts/scraper/rocknix_launchers.py b/scripts/scraper/rocknix_launchers.py index eb18cba3e..209aeb5dc 100644 --- a/scripts/scraper/rocknix_launchers.py +++ b/scripts/scraper/rocknix_launchers.py @@ -13,35 +13,22 @@ from __future__ import annotations import posixpath import re -from collections.abc import Callable +from collections.abc import Callable, Hashable from dataclasses import dataclass +from typing import TypeVar -try: - from .configgen_launchers import Launcher - from .shell_launchers import config_placement, evidence_fields - from .shell_launchers import ( - LauncherPatternMissing, - Link, - RepoTree, - Script, - Setting, - describe_keys, - settings, - source_ref, - ) -except ImportError: - from configgen_launchers import Launcher - from shell_launchers import config_placement, evidence_fields # type: ignore[no-redef] - from shell_launchers import ( - LauncherPatternMissing, - Link, - RepoTree, - Script, - Setting, - describe_keys, - settings, - source_ref, - ) +from .configgen_launchers import Launcher +from .shell_launchers import config_placement, evidence_fields +from .shell_launchers import ( + LauncherPatternMissing, + Link, + RepoTree, + Script, + Setting, + describe_keys, + settings, + source_ref, +) ROCKNIX = "projects/ROCKNIX" DEVICES = f"{ROCKNIX}/devices" @@ -53,6 +40,8 @@ CONFIG_ROOT = "/storage/.config" USERCONFIG = f"{ROCKNIX}/packages/sysutils/systemd/scripts/userconfig-setup" Lines = list[tuple[str, set[int]]] +# What per_device groups configs by: equal values make one group. +Found = TypeVar("Found", bound=Hashable) @dataclass @@ -82,13 +71,13 @@ def device_configs( if not re.search(rf"CONFIG=|\$\{{PKG_DIR\}}/{folder}/", body): continue offset = block.start(1) - for arm in re.finditer(r"^\s*([\w*|]+)\)(.*?);;", body, re.M | re.S): + for case_arm in re.finditer(r"^\s*([\w*|]+)\)(.*?);;", body, re.M | re.S): chosen = re.search( - rf'CONFIG="([^"]+)"|\$\{{PKG_DIR\}}/{folder}/([^/\s]+)', arm.group(2) + rf'CONFIG="([^"]+)"|\$\{{PKG_DIR\}}/{folder}/([^/\s]+)', case_arm.group(2) ) if chosen: - arms.append((arm.group(1).split("|"), chosen.group(1) or chosen.group(2))) - mk_lines.add(mk.text.count("\n", 0, offset + arm.start(2)) + 1) + arms.append((case_arm.group(1).split("|"), chosen.group(1) or chosen.group(2))) + mk_lines.add(mk.text.count("\n", 0, offset + case_arm.start(2)) + 1) break if not arms: number, _ = mk.find( @@ -121,15 +110,15 @@ def per_device( tree: RepoTree, configs: list[DeviceConfig], mk_path: str, - read: Callable[[str, str], tuple[object, set[int]]], -) -> list[tuple[str | None, object, Lines]]: + read: Callable[[str, str], tuple[Found, set[int]]], +) -> list[tuple[str | None, Found, Lines]]: """Configs grouped by what read() finds in them. read(path, text) returns a comparable value and the lines it comes from. One group gives one result without a device. Otherwise each group names its devices, in the order of the devices directory. """ - groups: dict[object, tuple[list[str], Lines]] = {} + groups: dict[Found, tuple[list[str], Lines]] = {} for config in configs: value, lines = read(config.path, tree.read(config.path)) devices, refs = groups.setdefault(value, ([], [])) @@ -223,6 +212,14 @@ def _keys(value: FixedPaths) -> list[str]: return [f"[{section}] {key}" if section else key for section, key in value.keys] +@dataclass(frozen=True) +class Installed: + """Where the launch puts a per-device config, and the start script doing it.""" + + target: str = "" + start: Script | None = None + + def config_records( tree: RepoTree, emulator: str, @@ -230,8 +227,7 @@ def config_records( file: str, passes_to_suffix: str = "", depends_on_option: str | None = None, - target: str = "", - start: Script | None = None, + installed: Installed | None = None, unread: Callable[[tuple[str, str]], bool] = lambda key: False, ) -> list[Launcher]: """fixed_name records for the bios paths of a config installed per device. @@ -239,11 +235,12 @@ def config_records( ``unread`` drops the keys the shipped configs leave the emulator reading no file from. """ + installed = installed or Installed() configs = device_configs(tree, package, file) keys = [k for k in bios_keys(tree, [c.path for c in configs]) if not unread(k)] name = posixpath.basename(file) - def read(path: str, text: str) -> tuple[object, set[int]]: + def read(path: str, text: str) -> tuple[FixedPaths, set[int]]: return fixed_paths(settings(text), keys, path) records = [] @@ -265,9 +262,9 @@ def config_records( device=device, depends_on_option=depends_on_option, ), - target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}", + installed.target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}", _keys(value), - start, + installed.start, )) return records @@ -277,7 +274,7 @@ def retroarch(tree: RepoTree) -> list[Launcher]: configs = device_configs(tree, RETROARCH, "retroarch.cfg", folder="sources") wanted = ("system_directory", "systemfiles_in_content_dir") - def read(path: str, text: str) -> tuple[object, set[int]]: + def read(path: str, text: str) -> tuple[tuple[tuple[str, str], ...], set[int]]: found = {s.key: s for s in settings(text) if s.key in wanted} if "system_directory" not in found: raise LauncherPatternMissing(path, "system_directory") @@ -497,7 +494,7 @@ def melonds(tree: RepoTree) -> list[Launcher]: conf_line, conf = script.find(r'^\s*CONF_DIR="([^"]+)"', "CONF_DIR") records = config_records( tree, "melonds", package, "melonDS.ini", depends_on_option=condition, - target=f"{conf.group(1)}/melonDS.ini", start=script, unread=unread, + installed=Installed(f"{conf.group(1)}/melonDS.ini", script), unread=unread, ) for record in records: record.source_ref += ( @@ -514,7 +511,7 @@ def dsperate(tree: RepoTree) -> list[Launcher]: run_line, _ = script.find(r"/usr/bin/dsperate --config ", "dsperate --config") records = config_records( tree, "dsperate", package, "dsperate.ini", " (--config)", - target=script.expand("${DSPERATE_INI}", run_line, set()), start=script, + installed=Installed(script.expand("${DSPERATE_INI}", run_line, set()), script), ) for record in records: record.source_ref += f", {source_ref([(script.path, {run_line})])}" @@ -531,7 +528,7 @@ def xemu(tree: RepoTree) -> list[Launcher]: ) records = config_records( tree, "xemu", package, "xemu.toml", " (copied at each launch)", - target=script.expand("${CONF_DIR}/${XEMU_INI}", copy_line, set()), start=script, + installed=Installed(script.expand("${CONF_DIR}/${XEMU_INI}", copy_line, set()), script), ) for record in records: record.source_ref += f", {source_ref([(script.path, {copy_line})])}" @@ -667,7 +664,7 @@ def directory_records( configs = device_configs(tree, package, file) name = posixpath.basename(file) - def read(path: str, text: str) -> tuple[object, set[int]]: + def read(path: str, text: str) -> tuple[str, set[int]]: found = {(s.section, s.key): s for s in settings(text)} if folder_key not in found: raise LauncherPatternMissing(path, f"[{folder_key[0]}] {folder_key[1]}") @@ -830,7 +827,7 @@ def patched_directories(tree: RepoTree) -> list[Launcher]: ), None, ) - if returned is None: + if start is None or returned is None: raise LauncherPatternMissing(path, f"{function}() patched to return a fixed path") number, directory = returned records.append(Launcher( diff --git a/scripts/scraper/rocknix_scraper.py b/scripts/scraper/rocknix_scraper.py index 7580aeb7d..a21c15273 100644 --- a/scripts/scraper/rocknix_scraper.py +++ b/scripts/scraper/rocknix_scraper.py @@ -17,26 +17,15 @@ from __future__ import annotations import re -try: - from .base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_github_latest_version, - md5_field, - requirement_entry, - ) - from .rocknix_launchers import extract_launchers - from .shell_launchers import RepoTree -except ImportError: - from base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_github_latest_version, - md5_field, - requirement_entry, - ) - from rocknix_launchers import extract_launchers - from shell_launchers import RepoTree +from .base_scraper import ( + BaseScraper, + BiosRequirement, + fetch_github_latest_version, + md5_field, + requirement_entry, +) +from .rocknix_launchers import extract_launchers +from .shell_launchers import RepoTree PLATFORM_NAME = "rocknix" @@ -292,7 +281,10 @@ class Scraper(BaseScraper): { "files": [], "native_id": req.native_id, - "name": names.get(req.native_id, req.system), + "name": ( + names.get(req.native_id, req.system) + if req.native_id is not None else req.system + ), }, ) entry["files"].append(requirement_entry(req)) @@ -321,10 +313,7 @@ class Scraper(BaseScraper): def main() -> None: """Entry point.""" - try: - from .base_scraper import scraper_cli - except ImportError: - from base_scraper import scraper_cli + from .base_scraper import scraper_cli scraper_cli(Scraper, "Scrape ROCKNIX BIOS requirements") diff --git a/scripts/scraper/romfolders/__init__.py b/scripts/scraper/romfolders/__init__.py index 2c549e32b..b5b4923f5 100644 --- a/scripts/scraper/romfolders/__init__.py +++ b/scripts/scraper/romfolders/__init__.py @@ -20,12 +20,11 @@ from collections.abc import Callable from dataclasses import dataclass, field from pathlib import Path -_SCRIPTS_DIR = str(Path(__file__).resolve().parents[2]) -if _SCRIPTS_DIR not in sys.path: +if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[2])) not in sys.path: sys.path.insert(0, _SCRIPTS_DIR) -import upstream # noqa: E402 -from safeparse import yaml_load # noqa: E402 +import upstream +from safeparse import yaml_load CACHE_DIR = upstream.CACHE_DIR diff --git a/scripts/scraper/romfolders/card.py b/scripts/scraper/romfolders/card.py index e910e206e..b1b5ed4fd 100644 --- a/scripts/scraper/romfolders/card.py +++ b/scripts/scraper/romfolders/card.py @@ -208,14 +208,20 @@ def parse_crossmix(spec: dict, fetcher: Fetcher) -> list[dict]: # Koriki +class _CaseConfigParser(ConfigParser): + """Option names kept as written: Koriki's keys are case-sensitive.""" + + def optionxform(self, optionstr: str) -> str: + return optionstr + + @register("koriki") def parse_koriki(spec: dict, fetcher: Fetcher) -> list[dict]: params = spec["params"] key = params["source"] path = params["sections"] text = fetcher.text(key, path) - parser = ConfigParser(interpolation=None, strict=False) - parser.optionxform = str # type: ignore[assignment] + parser = _CaseConfigParser(interpolation=None, strict=False) parser.read_string(text) skip = set(params.get("skip", [])) rows = [] @@ -353,8 +359,8 @@ def parse_minui(spec: dict, fetcher: Fetcher) -> list[dict]: match = re.match(r"^skeleton/[^/]+/Roms/([^/]+)/", path) if match: name = match.group(1) - tag = re.search(r"\(([^()]*)\)\s*$", name) - shipped.setdefault(tag.group(1) if tag else name, name) + paren = re.search(r"\(([^()]*)\)\s*$", name) + shipped.setdefault(paren.group(1) if paren else name, name) paks: dict[str, dict[str, tuple[str, str]]] = {} for path in tree: match = _PAK.match(path) @@ -492,12 +498,12 @@ def parse_gmenu2x(spec: dict, fetcher: Fetcher) -> list[dict]: } key = params["source"] for path in fetcher.tree(key, params["shipped_roms"] + "/"): - folder = path[len(params["shipped_roms"]) + 1:].split("/") - if len(folder) < 2 or folder[0] in rows: + parts = path[len(params["shipped_roms"]) + 1:].split("/") + if len(parts) < 2 or parts[0] in rows: continue - rows[folder[0]] = { - "folder": folder[0], - "source_ref": ref(key, f"{params['shipped_roms']}/{folder[0]}"), + rows[parts[0]] = { + "folder": parts[0], + "source_ref": ref(key, f"{params['shipped_roms']}/{parts[0]}"), "note": "folder the image ships. Its emulator link lives in a release package no repository holds", } return list(rows.values()) diff --git a/scripts/scraper/romfolders/es.py b/scripts/scraper/romfolders/es.py index 2d3a3f6c7..a6f9d84be 100644 --- a/scripts/scraper/romfolders/es.py +++ b/scripts/scraper/romfolders/es.py @@ -160,8 +160,8 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]: continue if not system.get("emulators") and not system.get("force"): continue - path = system.get("path", name) - if not path or str(path).startswith("/"): + folder = system.get("path", name) + if not folder or str(folder).startswith("/"): continue base = defaults.get(name) or {} emulator, core = base.get("emulator"), base.get("core") @@ -175,7 +175,7 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]: if name in def_lines: refs.append(_ref(key, def_path, def_lines[name])) rows.append({ - "folder": str(path), + "folder": str(folder), "name": name, "extensions": _extensions(system.get("extensions")), "core": str(core) if core else None, @@ -393,6 +393,40 @@ def _conf_values(text: str) -> tuple[dict[str, str], dict[str, int]]: return values, lines +def _nesting(line: str, stack: list[list[str]]) -> bool: + """Follow case and if nesting. True when the line is consumed.""" + match = re.match(r'case\s+"?\$\{?(\w+)\}?"?\s+in', line) + if match: + stack.append(["case", match.group(1), ""]) + return True + if line == "esac": + stack.pop() + return True + if line.startswith("if ") or line.startswith("[") and "&&" not in line and line.endswith("then"): + stack.append(["if", line, ""]) + return True + if line in ("fi",): + if stack and stack[-1][0] == "if": + stack.pop() + return True + return line in ("then", "else") or line.startswith("elif ") + + +def _record_call( + words: list[str], number: int, stack: list[list[str]], + cores: list[dict], systems: dict[str, list[int]], +) -> None: + branches = [(s[1], s[2]) for s in stack] + if words[:1] == ["add_emu_core"] and len(words) >= 4: + cores.append({ + "system": words[1], "emulator": words[2], "core": words[3], + "default": len(words) > 4 and words[4] == "true", + "branches": branches, "line": number, + }) + elif words[:1] == ["add_es_system"] and len(words) >= 2: + systems.setdefault(words[1], []).append(number) + + def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]: """add_emu_core and add_es_system calls of makeinstall_target, each with the `case` branches it sits under as (variable, pattern) pairs. @@ -412,21 +446,7 @@ def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]: continue if raw.startswith("}"): break - match = re.match(r'case\s+"?\$\{?(\w+)\}?"?\s+in', line) - if match: - stack.append(["case", match.group(1), ""]) - continue - if line == "esac": - stack.pop() - continue - if line.startswith("if ") or line.startswith("[") and "&&" not in line and line.endswith("then"): - stack.append(["if", line, ""]) - continue - if line in ("fi",): - if stack and stack[-1][0] == "if": - stack.pop() - continue - if line in ("then", "else") or line.startswith("elif "): + if _nesting(line, stack): continue ends = line.endswith(";;") if ends: @@ -436,16 +456,7 @@ def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]: if match and not line.startswith(("add_", "[", "sed", "cp", "mkdir")): stack[-1][2] = match.group(1).strip() line = match.group(2).strip() - words = line.split() - branches = [(s[1], s[2]) for s in stack] - if words[:1] == ["add_emu_core"] and len(words) >= 4: - cores.append({ - "system": words[1], "emulator": words[2], "core": words[3], - "default": len(words) > 4 and words[4] == "true", - "branches": branches, "line": number, - }) - elif words[:1] == ["add_es_system"] and len(words) >= 2: - systems.setdefault(words[1], []).append(number) + _record_call(line.split(), number, stack, cores, systems) if ends and stack and stack[-1][0] == "case": stack[-1][2] = "" return cores, systems @@ -487,7 +498,8 @@ def elec_conf(spec: dict, fetcher: Fetcher) -> list[dict]: flagged = [c for c in mine if c["default"]] plain = [c for c in flagged if not c["branches"]] star = [c for c in flagged if c["branches"] and c["branches"][-1][1] == "*"] - pick = (plain or star or flagged or [None])[0] + candidates = plain or star or flagged + pick: dict | None = candidates[0] if candidates else None if pick is None: pick = next((c for c in mine if not c["branches"]), mine[0] if mine else None) board_defaults = {} @@ -861,10 +873,11 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]: core, core_line = _recalbox_get(sections, lines, section, "core", board) emulator, _ = _recalbox_get(sections, lines, section, "emulator", board) exts, _ = _recalbox_get(sections, lines, section, "extensions", board) - if (exts or "").startswith(_FILES_PREFIX): - names.update(_recalbox_names(exts[len(_FILES_PREFIX):])) + listed = exts or "" + if listed.startswith(_FILES_PREFIX): + names.update(_recalbox_names(listed[len(_FILES_PREFIX):])) else: - extensions.update((exts or "").split()) + extensions.update(listed.split()) cores.append({ "core": core, "emulator": emulator, "priority": int(priority or "255"), "source_ref": "; ".join([ @@ -968,8 +981,8 @@ def retropie(spec: dict, fetcher: Fetcher) -> list[dict]: cfg_path = params["platforms_cfg"] cfg = fetcher.text(key, cfg_path) exts: dict[str, tuple[str, int]] = {} - for number, line in enumerate(cfg.splitlines(), 1): - match = re.match(r'^([\w-]+)_exts="([^"]*)"', line) + for number, cfg_line in enumerate(cfg.splitlines(), 1): + match = re.match(r'^([\w-]+)_exts="([^"]*)"', cfg_line) if match: exts[match.group(1)] = (match.group(2), number) platform = set(params["platform_flags"]) diff --git a/scripts/scraper/romm_scraper.py b/scripts/scraper/romm_scraper.py index 0144a0fe0..4cca66e66 100644 --- a/scripts/scraper/romm_scraper.py +++ b/scripts/scraper/romm_scraper.py @@ -26,22 +26,13 @@ import json import re import sys -try: - from .base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_bytes, - fetch_github_latest_version, - requirement_entry, - ) -except ImportError: - from base_scraper import ( - BaseScraper, - BiosRequirement, - fetch_bytes, - fetch_github_latest_version, - requirement_entry, - ) +from .base_scraper import ( + BaseScraper, + BiosRequirement, + fetch_bytes, + fetch_github_latest_version, + requirement_entry, +) PLATFORM_NAME = "romm" @@ -194,7 +185,7 @@ class Scraper(BaseScraper): raise ValueError("known_bios_files.json format validation failed") data = self._parse_json() - requirements = [] + requirements: list[BiosRequirement] = [] for key, entry in data.items(): if ":" not in key: @@ -216,21 +207,21 @@ class Scraper(BaseScraper): for slug, names in FIRMWARE_MIRRORS.get(igdb_slug, {}).items() if names is None or filename in names ] - for slug in (igdb_slug, *mirrors): - requirements.append( - BiosRequirement( - name=filename, - system=SLUG_MAP[slug], - sha1=sha1, - md5=md5, - crc32=crc32, - size=size, - destination=f"{slug}/{filename}", - required=True, - native_id=slug, - mirror_of=None if slug == igdb_slug else igdb_slug, - ) + requirements.extend( + BiosRequirement( + name=filename, + system=SLUG_MAP[slug], + sha1=sha1, + md5=md5, + crc32=crc32, + size=size, + destination=f"{slug}/{filename}", + required=True, + native_id=slug, + mirror_of=None if slug == igdb_slug else igdb_slug, ) + for slug in (igdb_slug, *mirrors) + ) return requirements diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index a2ea7ceb5..e7a82e3dd 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -31,7 +31,6 @@ from __future__ import annotations import argparse import hashlib -import io import json import os import re @@ -41,8 +40,10 @@ import urllib.parse import urllib.request import zipfile from collections.abc import Callable, Iterator +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path +from typing import IO from ..common import ( list_registered_platforms, @@ -62,9 +63,9 @@ DEFAULT_OUTPUT = "recipes/{source}.json" def relevant_archives(emulators_dir: str, platforms_dir: str) -> set[str]: """Archive names any profile or platform refers to.""" names: set[str] = set() - for _profile_name, profile in load_emulator_profiles( + for profile in load_emulator_profiles( emulators_dir, skip_aliases=False - ).items(): + ).values(): for entry in profile.get("files", []) or []: name = entry.get("name", "") if name.endswith(".zip"): @@ -283,7 +284,7 @@ def _machine_roms(blob: bytes) -> list[dict]: def _scan_listxml( - stream: io.BufferedIOBase, + stream: IO[bytes], selector: Callable[[str], bool], targets: Targets | None = None, ) -> dict[str, tuple[str | None, list[dict]]]: @@ -326,7 +327,7 @@ def _scan_listxml( def listxml_entries( - open_stream: Callable[[], io.BufferedIOBase], + open_stream: Callable[[], IO[bytes]], label: str, keep: set[str] | None, targets: Targets | None = None, @@ -575,6 +576,8 @@ def fetch_pack( if not sha: raise BlobMismatchError(f"libretro/FBNeo has no revision {tag}") listing = _api_json(f"{FBNEO_API}/contents/dats?ref={sha}") + if not isinstance(listing, list): + raise BlobMismatchError(f"libretro/FBNeo lists no dats at {sha}") target = cache_dir / "fbneo-dats" target.mkdir(parents=True, exist_ok=True) blobs: dict[str, str] = {} @@ -616,21 +619,21 @@ def _is_listxml(pack: Path) -> bool: return b" Callable[[], io.BufferedIOBase]: +def _listxml_opener(pack: Path) -> Callable[[], IO[bytes]]: """A callable giving a fresh byte stream over the listxml document.""" if pack.suffix.lower() == ".zip": - def opener() -> zipfile.ZipExtFile: + def opener() -> IO[bytes]: archive = zipfile.ZipFile(pack) name = next(n for n in archive.namelist() if n.lower().endswith(".xml")) - stream = archive.open(name) - stream.close_archive = archive # keep the archive alive - return stream + # The member keeps the archive alive: its shared file closes + # through the archive's own _fpclose. + return archive.open(name) return opener return lambda: pack.open("rb") -def main() -> int: +def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__) parser.add_argument( "--source", choices=SOURCES, required=True, @@ -677,6 +680,76 @@ def main() -> int: "--dry-run", action="store_true", help="print what would change and write nothing", ) + return parser + + +@dataclass(frozen=True) +class _Selection: + """Which sets a snapshot keeps: None everywhere keeps every set.""" + + keep: set[str] | None = None + targets: Targets | None = None + by_members: ByMembers | None = None + + +def _selection(args: argparse.Namespace) -> _Selection: + if args.all: + return _Selection() + held, by_members = collection_archives(args.db) + keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held + targets = catalog_targets(args.provenance_dir, args.db) + return _Selection(keep, targets, by_members) + + +def _import_listxml(pack: Path, args: argparse.Namespace, output: str, chosen: _Selection) -> int: + label = f"MAME {pack.stem.replace('lx', '')}" + entries = listxml_entries( + _listxml_opener(pack), label, chosen.keep, chosen.targets, chosen.by_members + ) + dats = {label: pack.stem} + print(f" {label}: {len(entries)} sets retenus") + members = sum(len(entry["members"]) for entry in entries) + print(f"{len(entries)} recettes, {members} membres, depuis 1 listxml") + if args.dry_run: + return 0 + changed = merge_snapshot(output, args.source, dats, entries) + print(f"{'Wrote' if changed else 'Unchanged'} {output}") + return 0 + + +def _dat_recipes( + pack: Path, revision: str, chosen: _Selection +) -> tuple[dict[str, str], list[dict]]: + """Recipes of every Logiqx DAT a pack holds, and each DAT's version.""" + dats: dict[str, str] = {} + entries: list[dict] = [] + skipped = 0 + for member, content in _iter_dat_contents(pack): + try: + dat = parse_logiqx(content) + except (ValueError, SyntaxError) as exc: + print(f" Skipped {member}: {exc}", file=sys.stderr) + skipped += 1 + continue + if not dat.roms: + skipped += 1 + continue + if revision: + dat.name = f"{dat.name or member} @ {revision}" + found = recipe_entries(dat, chosen.keep, chosen.targets, chosen.by_members) + if not found: + continue + dats[dat.name or member] = dat.version + entries.extend(found) + print(f" {dat.name or member}: {len(found)} sets retenus") + + if skipped: + print(f" {skipped} fichier(s) ignore(s) (non-Logiqx ou vides)") + return dats, entries + + +def main() -> int: + parser = _parser() args = parser.parse_args() blobs: dict[str, str] = {} @@ -708,54 +781,12 @@ def main() -> int: output = args.output or DEFAULT_OUTPUT.format(source=args.source) Path(output).parent.mkdir(parents=True, exist_ok=True) - keep: set[str] | None = None - targets = None - by_members: ByMembers | None = None - if not args.all: - held, by_members = collection_archives(args.db) - keep = relevant_archives(args.emulators_dir, args.platforms_dir) | held - targets = catalog_targets(args.provenance_dir, args.db) - - dats: dict[str, str] = {} - entries: list[dict] = [] - skipped = 0 + chosen = _selection(args) if _is_listxml(pack): - label = f"MAME {pack.stem.replace('lx', '')}" - entries = listxml_entries( - _listxml_opener(pack), label, keep, targets, by_members - ) - dats[label] = pack.stem - print(f" {label}: {len(entries)} sets retenus") - members = sum(len(entry["members"]) for entry in entries) - print(f"{len(entries)} recettes, {members} membres, depuis 1 listxml") - if args.dry_run: - return 0 - changed = merge_snapshot(output, args.source, dats, entries) - print(f"{'Wrote' if changed else 'Unchanged'} {output}") - return 0 + return _import_listxml(pack, args, output, chosen) - for member, content in _iter_dat_contents(pack): - try: - dat = parse_logiqx(content) - except (ValueError, SyntaxError) as exc: - print(f" Skipped {member}: {exc}", file=sys.stderr) - skipped += 1 - continue - if not dat.roms: - skipped += 1 - continue - if revision: - dat.name = f"{dat.name or member} @ {revision}" - found = recipe_entries(dat, keep, targets, by_members) - if not found: - continue - dats[dat.name or member] = dat.version - entries.extend(found) - print(f" {dat.name or member}: {len(found)} sets retenus") - - if skipped: - print(f" {skipped} fichier(s) ignore(s) (non-Logiqx ou vides)") + dats, entries = _dat_recipes(pack, revision, chosen) members = sum(len(entry["members"]) for entry in entries) print(f"{len(entries)} recettes, {members} membres, depuis {len(dats)} DAT") diff --git a/scripts/scraper/shell_launchers.py b/scripts/scraper/shell_launchers.py index e71936986..e882ce77a 100644 --- a/scripts/scraper/shell_launchers.py +++ b/scripts/scraper/shell_launchers.py @@ -15,12 +15,8 @@ import re from collections.abc import Callable, Iterable from dataclasses import dataclass, field -try: - from .base_scraper import fetch_bytes, github_headers - from .configgen_launchers import LauncherShapeError -except ImportError: - from base_scraper import fetch_bytes, github_headers - from configgen_launchers import LauncherShapeError +from .base_scraper import fetch_bytes, github_headers +from .configgen_launchers import LauncherShapeError NAME = r"[A-Za-z_][A-Za-z0-9_]*" # A single-quoted "$" is literal: it is carried as this mark through expansion. @@ -120,62 +116,89 @@ def words(line: str) -> list[Word]: ended a name ("$a""b") still ends it. A "$" inside single quotes is kept as LITERAL_DOLLAR so a later expansion leaves it alone. """ - result: list[Word] = [] - raw, text, quote, started, segment = "", "", "", False, 0 - - def close_segment() -> None: - nonlocal text, segment - text = text[:segment] + re.sub(rf"\$({NAME})", r"${\1}", text[segment:]) - segment = len(text) - + lexer = _Lexer(line) i = 0 while i < len(line): - char = line[i] - if quote == "'": - raw += char - if char == "'": - quote = "" - segment = len(text) - else: - text += LITERAL_DOLLAR if char == "$" else char - elif quote == '"': - raw += char - if char == "\\" and i + 1 < len(line) and line[i + 1] in '"\\$`': - raw += line[i + 1] - text += LITERAL_DOLLAR if line[i + 1] == "$" else line[i + 1] - i += 1 - elif char == '"': - quote = "" - close_segment() - else: - text += char - elif char in "'\"": - close_segment() - quote, started = char, True - raw += char - elif char == "\\" and i + 1 < len(line): - raw += char + line[i + 1] - text += line[i + 1] - started = True - i += 1 - elif char == "#" and not started: - break - elif char.isspace() or char == ";": - if started: - close_segment() - result.append(Word(raw, text)) - raw, text, started, segment = "", "", False, 0 - if char == ";": - result.append(Word(";", ";")) + if lexer.quote == "'": + lexer.single(line[i]) + elif lexer.quote == '"': + i = lexer.double(i) else: - raw += char - text += char - started = True + step = lexer.plain(i) + if step is None: + break + i = step i += 1 - if started: - close_segment() - result.append(Word(raw, text)) - return result + if lexer.started: + lexer.close_segment() + lexer.result.append(Word(lexer.raw, lexer.text)) + return lexer.result + + +class _Lexer: + """The state words() keeps while it reads a line character by character.""" + + def __init__(self, line: str) -> None: + self.line = line + self.result: list[Word] = [] + self.raw, self.text, self.quote, self.started, self.segment = "", "", "", False, 0 + + def close_segment(self) -> None: + self.text = self.text[:self.segment] + re.sub( + rf"\$({NAME})", r"${\1}", self.text[self.segment:] + ) + self.segment = len(self.text) + + def single(self, char: str) -> None: + """One character inside single quotes.""" + self.raw += char + if char == "'": + self.quote = "" + self.segment = len(self.text) + else: + self.text += LITERAL_DOLLAR if char == "$" else char + + def double(self, i: int) -> int: + """The character at i inside double quotes, and the index of the last one read.""" + line, char = self.line, self.line[i] + self.raw += char + if char == "\\" and i + 1 < len(line) and line[i + 1] in '"\\$`': + self.raw += line[i + 1] + self.text += LITERAL_DOLLAR if line[i + 1] == "$" else line[i + 1] + return i + 1 + if char == '"': + self.quote = "" + self.close_segment() + else: + self.text += char + return i + + def plain(self, i: int) -> int | None: + """The character at i outside quotes, and the index of the last one read (None at a comment).""" + line, char = self.line, self.line[i] + if char in "'\"": + self.close_segment() + self.quote, self.started = char, True + self.raw += char + elif char == "\\" and i + 1 < len(line): + self.raw += char + line[i + 1] + self.text += line[i + 1] + self.started = True + return i + 1 + elif char == "#" and not self.started: + return None + elif char.isspace() or char == ";": + if self.started: + self.close_segment() + self.result.append(Word(self.raw, self.text)) + self.raw, self.text, self.started, self.segment = "", "", False, 0 + if char == ";": + self.result.append(Word(";", ";")) + else: + self.raw += char + self.text += char + self.started = True + return i @dataclass @@ -492,6 +515,58 @@ def _quoted_glob(command: str) -> bool: return "*" in raw and "*" not in re.sub(r'"[^"]*"|\'[^\']*\'', "", raw) +def _copy_skips( + script: Script, + number: int, + line: str, + copy: re.Match[str], + target: str, + source_name: str, + sources: tuple[str, ...], +) -> bool | None: + """For a copy that installs ``target``, whether it leaves a file already there. + + None when the copy installs something else. + """ + args = [] + for word in words(line[copy.start(1):])[1:]: + # The command ends at a separator or a redirection. + if word.raw in {";", "&&", "||", "|"} or re.match(r"\d*>|&>", word.raw): + break + args.append(word.text) + operands = [a for a in args if not a.startswith("-")] + if not operands: + return None + # A quoted "*" is a file named *, which no package installs: + # the copy does nothing (EmuELEC's duckstation.sh). + if _quoted_glob(line[copy.start(1):]): + return None + destination = script.expand(operands[-1], number, set()).rstrip("/") + source = script.expand(operands[0], number, set()).rstrip("/") + hits = target == destination or target.startswith( + (destination + "/", f"{destination}/{source.rsplit('/', 1)[-1]}") + ) + # A copy of another file into the same place is another + # record's: amiberry copies the A500 or the A1200 setup. + named = source.rsplit("/", 1)[-1] + if not hits or (source_name and "." in named and named != source_name): + return None + # A named file copied into a folder above the target is + # another file of that folder (ARMSX2's secrets.ini). + if ( + not source_name and "." in named and "*" not in named + and destination != target and named != target.rsplit("/", 1)[-1] + ): + return None + if sources and not source.startswith(sources): + return None + # cp -i fed by false answers no to every overwrite. + prompted = any( + a.startswith("-") and not a.startswith("--") and "i" in a[1:] for a in args + ) and re.search(r"\bfalse\s*\|\s*$", line[:copy.start(1)]) + return "-n" in args or "--ignore-existing" in args or bool(prompted) + + def config_placement( script: Script, target: str, @@ -517,43 +592,10 @@ def config_placement( for number, line in script.code(): if (copy := _COPY.search(line)) or (writer and writer.search(line)): if copy: - args = [] - for word in words(line[copy.start(1):])[1:]: - # The command ends at a separator or a redirection. - if word.raw in {";", "&&", "||", "|"} or re.match(r"\d*>|&>", word.raw): - break - args.append(word.text) - operands = [a for a in args if not a.startswith("-")] - if not operands: + copied = _copy_skips(script, number, line, copy, target, source_name, sources) + if copied is None: continue - # A quoted "*" is a file named *, which no package installs: - # the copy does nothing (EmuELEC's duckstation.sh). - if _quoted_glob(line[copy.start(1):]): - continue - destination = script.expand(operands[-1], number, set()).rstrip("/") - source = script.expand(operands[0], number, set()).rstrip("/") - hits = target == destination or target.startswith(destination + "/") or ( - target.startswith(f"{destination}/{source.rsplit('/', 1)[-1]}") - ) - # A copy of another file into the same place is another - # record's: amiberry copies the A500 or the A1200 setup. - named = source.rsplit("/", 1)[-1] - if not hits or (source_name and "." in named and named != source_name): - continue - # A named file copied into a folder above the target is - # another file of that folder (ARMSX2's secrets.ini). - if ( - not source_name and "." in named and "*" not in named - and destination != target and named != target.rsplit("/", 1)[-1] - ): - continue - if sources and not source.startswith(sources): - continue - # cp -i fed by false answers no to every overwrite. - prompted = any( - a.startswith("-") and not a.startswith("--") and "i" in a[1:] for a in args - ) and re.search(r"\bfalse\s*\|\s*$", line[:copy.start(1)]) - skip = "-n" in args or "--ignore-existing" in args or bool(prompted) + skip = copied else: skip = False install.add(number) @@ -561,9 +603,10 @@ def config_placement( kept = False elif re.search(r"\bsed\b.*\s-i\b|\bsed -i", line) and bare: expanded = script.expand(line, number, set()) - if target in expanded or target.rsplit("/", 1)[-1] in expanded: - if any(re.search(rf"\b{re.escape(k)}\b", expanded) for k in bare): - overrides.add(number) + if (target in expanded or target.rsplit("/", 1)[-1] in expanded) and any( + re.search(rf"\b{re.escape(k)}\b", expanded) for k in bare + ): + overrides.add(number) if not install and required: raise script.missing(f"install of {target}") return ConfigPlacement(script.path, target, install, kept, overrides) diff --git a/scripts/scraper/targets/__init__.py b/scripts/scraper/targets/__init__.py index f72d7ecb3..ebdf4d76a 100644 --- a/scripts/scraper/targets/__init__.py +++ b/scripts/scraper/targets/__init__.py @@ -74,7 +74,7 @@ def discover_target_scrapers() -> dict[str, type]: if _scrapers: return _scrapers package_dir = Path(__file__).parent - for finder, name, ispkg in pkgutil.iter_modules([str(package_dir)]): + for _finder, name, _ispkg in pkgutil.iter_modules([str(package_dir)]): if not name.endswith("_targets_scraper"): continue module = importlib.import_module(f".{name}", package=__package__) diff --git a/scripts/scraper/targets/amberelec_targets_scraper.py b/scripts/scraper/targets/amberelec_targets_scraper.py index 72b3b557f..38eeb0e7c 100644 --- a/scripts/scraper/targets/amberelec_targets_scraper.py +++ b/scripts/scraper/targets/amberelec_targets_scraper.py @@ -24,23 +24,16 @@ from datetime import datetime, timezone import yaml from . import BaseTargetScraper +from ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS +from ..base_scraper import fetch_bytes +from ..batocera_scraper import _not_cores +from ..es_emulators import es_cores, xml_systems PLATFORM_NAME = "amberelec" RAW_BASE = "https://raw.githubusercontent.com/AmberELEC/AmberELEC/{ref}" META_MK = "packages/amberelec/package.mk" -try: - from ..amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS - from ..base_scraper import fetch_bytes - from ..batocera_scraper import _not_cores - from ..es_emulators import es_cores, xml_systems -except ImportError: - from scraper.amberelec_scraper import BUILDS_OF, ES_SYSTEMS_TEMPLATE, RUNNERS - from scraper.base_scraper import fetch_bytes - from scraper.batocera_scraper import _not_cores - from scraper.es_emulators import es_cores, xml_systems - _DEVICE_RE = re.compile( r"^(\w+):\n\tDEVICE=(\w+) ARCH=(\w+) \./scripts/build_distro$", re.MULTILINE ) diff --git a/scripts/scraper/targets/batocera_targets_scraper.py b/scripts/scraper/targets/batocera_targets_scraper.py index a6aec9414..1baa42311 100644 --- a/scripts/scraper/targets/batocera_targets_scraper.py +++ b/scripts/scraper/targets/batocera_targets_scraper.py @@ -30,14 +30,10 @@ import yaml from safeparse import yaml_load_upstream from . import BaseTargetScraper +from ..base_scraper import github_headers PLATFORM_NAME = "batocera" -try: - from ..base_scraper import github_headers -except ImportError: - from scraper.base_scraper import github_headers - _TARGET_FLAG_RE = re.compile(r"^(BR2_PACKAGE_BATOCERA_TARGET_\w+)=y", re.MULTILINE) # The images a target flag builds, each a board directory whose last segment @@ -306,7 +302,7 @@ def _parse_es_systems(text: str) -> dict[str, list[str]]: package_to_emulators: dict[str, list[str]] = {} - for _system_name, system_data in data.items(): + for system_data in data.values(): if not isinstance(system_data, dict): continue emulators = system_data.get("emulators") diff --git a/scripts/scraper/targets/emuelec_targets_scraper.py b/scripts/scraper/targets/emuelec_targets_scraper.py index 21b196b90..5153aadcd 100644 --- a/scripts/scraper/targets/emuelec_targets_scraper.py +++ b/scripts/scraper/targets/emuelec_targets_scraper.py @@ -35,6 +35,12 @@ from typing import NamedTuple import yaml from . import BaseTargetScraper +from ..base_scraper import fetch_bytes, github_headers +from ..batocera_scraper import _not_cores +from ..emuelec_scraper import ( + BUILDS_OF, ES_SYSTEMS_TEMPLATE, PORTS_TEMPLATE, RUNNERS, port_engines, with_ports, +) +from ..es_emulators import SystemEmulators, es_cores PLATFORM_NAME = "emuelec" @@ -45,21 +51,6 @@ META_MK = "packages/sx05re/emuelec/package.mk" OPTIONS = "distributions/EmuELEC/options" ES_MK = "packages/sx05re/emuelec-emulationstation/package.mk" -try: - from ..base_scraper import fetch_bytes, github_headers - from ..batocera_scraper import _not_cores - from ..emuelec_scraper import ( - BUILDS_OF, ES_SYSTEMS_TEMPLATE, PORTS_TEMPLATE, RUNNERS, port_engines, with_ports, - ) - from ..es_emulators import SystemEmulators, es_cores -except ImportError: - from scraper.base_scraper import fetch_bytes, github_headers - from scraper.batocera_scraper import _not_cores - from scraper.emuelec_scraper import ( - BUILDS_OF, ES_SYSTEMS_TEMPLATE, PORTS_TEMPLATE, RUNNERS, port_engines, with_ports, - ) - from scraper.es_emulators import SystemEmulators, es_cores - _ASSET_RE = re.compile(r"^EmuELEC-(?P[A-Za-z0-9-]+)\.(?P[a-z0-9_]+)-") # The metapackage, line for line. Each rule below transcribes these lines; diff --git a/scripts/scraper/targets/lakka_targets_scraper.py b/scripts/scraper/targets/lakka_targets_scraper.py index 073506137..eae64d338 100644 --- a/scripts/scraper/targets/lakka_targets_scraper.py +++ b/scripts/scraper/targets/lakka_targets_scraper.py @@ -21,6 +21,7 @@ from datetime import datetime, timezone import yaml from . import BaseTargetScraper +from ..base_scraper import fetch_bytes, github_headers PLATFORM_NAME = "lakka" @@ -29,11 +30,6 @@ RAW_BASE = "https://raw.githubusercontent.com/" + REPO + "/{tag}" API_BASE = "https://api.github.com/repos/" + REPO CORES_MK = "packages/lakka/libretro_cores/package.mk" -try: - from ..base_scraper import fetch_bytes, github_headers -except ImportError: - from scraper.base_scraper import fetch_bytes, github_headers - _IF_RE = re.compile(r"^(if|elif)\s+\[\s+(.*?)\s+\];?\s*(?:then)?\s*$") _TEST_RE = re.compile(r'^(!\s+)?"\$\{?(\w+)\}?"\s*(=|!=)\s*"?([^"\s]*)"?$') _SET_RE = re.compile(r"^\s*-([nz])\s+\"\$\{?(\w+)\}?\"\s*$") @@ -85,6 +81,91 @@ def _expand(value: str, env: dict[str, str]) -> str: ) +class _Evaluation: + """The state of one evaluate() run over an options file.""" + + def __init__(self, env: dict[str, str]) -> None: + self.env = dict(env) + # One frame per open if: [parent state, branch taken, this branch's state], + # each True, False, or None where a condition read an unknown variable. + self.stack: list[list[bool | None]] = [] + self.case_depth = self.loop_depth = 0 + + def state(self) -> bool | None: + states = [frame[2] for frame in self.stack] + if False in states: + return False + return None if None in states else True + + def nesting(self, line: str) -> bool: + """Follow case and loop nesting. True when the line is consumed.""" + if re.match(r"^case\b", line): + self.case_depth += 1 + return True + if line == "esac": + self.case_depth -= 1 + return True + if re.match(r"^(for|while)\b", line): + self.loop_depth += 1 + return True + if line == "done": + self.loop_depth -= 1 + return True + return bool(self.loop_depth) + + def branch(self, line: str) -> bool: + """Follow if/elif/else/fi. True when the line is one of them.""" + go: bool | None + branch = _IF_RE.match(line) + if branch and branch.group(1) == "if": + parent = self.state() + go = False if parent is False else ( + None if parent is None else _condition(branch.group(2), self.env) + ) + self.stack.append([parent, go, go]) + return True + if branch and branch.group(1) == "elif": + frame = self.stack[-1] + if frame[0] is False or frame[1] is True: + go = False + elif frame[0] is None or frame[1] is None: + go = None + else: + go = _condition(branch.group(2), self.env) + frame[1] = True if go is True else (None if go is None else frame[1]) + frame[2] = go + return True + if line == "else": + frame = self.stack[-1] + if frame[0] is False or frame[1] is True: + go = False + elif frame[0] is None or frame[1] is None: + go = None + else: + go = True + frame[1], frame[2] = True, go + return True + if line == "fi": + self.stack.pop() + return True + return False + + def assign(self, line: str) -> None: + assign = _ASSIGN_RE.match(line) + current = self.state() + if not assign or current is False: + return + name, op, value = assign.groups() + if self.case_depth or current is None: + if name in WATCHED: + where = "a case statement" if self.case_depth else "an undecidable branch" + raise ShellSubsetError(f"{name} assigned inside {where}") + return + value = " ".join(_expand(value, self.env).split()) + env = self.env + env[name] = f"{env.get(name, '')} {value}".strip() if op == "+=" else value + + def evaluate(text: str, env: dict[str, str]) -> dict[str, str]: """Run the assignments and if/elif/else blocks of a LibreELEC options file. @@ -93,82 +174,13 @@ def evaluate(text: str, env: dict[str, str]) -> dict[str, str]: as a set difference. A watched variable set inside a case statement is ambiguous and stops the scrape rather than guess. """ - env = dict(env) - lines = re.sub(r"\\\n", " ", text).splitlines() - # One frame per open if: [parent state, branch taken, this branch's state], - # each True, False, or None where a condition read an unknown variable. - stack: list[list[bool | None]] = [] - case_depth = loop_depth = 0 - - def state() -> bool | None: - states = [frame[2] for frame in stack] - if False in states: - return False - return None if None in states else True - - for raw in lines: + run = _Evaluation(env) + for raw in re.sub(r"\\\n", " ", text).splitlines(): line = raw.split("#", 1)[0].strip() - if not line: + if not line or run.nesting(line) or run.branch(line): continue - if re.match(r"^case\b", line): - case_depth += 1 - continue - if line == "esac": - case_depth -= 1 - continue - if re.match(r"^(for|while)\b", line): - loop_depth += 1 - continue - if line == "done": - loop_depth -= 1 - continue - if loop_depth: - continue - branch = _IF_RE.match(line) - if branch and branch.group(1) == "if": - parent = state() - go = False if parent is False else ( - None if parent is None else _condition(branch.group(2), env) - ) - stack.append([parent, go, go]) - continue - if branch and branch.group(1) == "elif": - frame = stack[-1] - if frame[0] is False or frame[1] is True: - go = False - elif frame[0] is None or frame[1] is None: - go = None - else: - go = _condition(branch.group(2), env) - frame[1] = True if go is True else (None if go is None else frame[1]) - frame[2] = go - continue - if line == "else": - frame = stack[-1] - if frame[0] is False or frame[1] is True: - go = False - elif frame[0] is None or frame[1] is None: - go = None - else: - go = True - frame[1], frame[2] = True, go - continue - if line == "fi": - stack.pop() - continue - assign = _ASSIGN_RE.match(line) - current = state() - if not assign or current is False: - continue - name, op, value = assign.groups() - if case_depth or current is None: - if name in WATCHED: - where = "a case statement" if case_depth else "an undecidable branch" - raise ShellSubsetError(f"{name} assigned inside {where}") - continue - value = " ".join(_expand(value, env).split()) - env[name] = f"{env.get(name, '')} {value}".strip() if op == "+=" else value - return env + run.assign(line) + return run.env def device_cores(cores_mk: str, env: dict[str, str]) -> list[str]: diff --git a/scripts/scraper/targets/recalbox_targets_scraper.py b/scripts/scraper/targets/recalbox_targets_scraper.py index e1e1b7fd9..e0e940c5c 100644 --- a/scripts/scraper/targets/recalbox_targets_scraper.py +++ b/scripts/scraper/targets/recalbox_targets_scraper.py @@ -22,6 +22,8 @@ from datetime import datetime, timezone import yaml from . import BaseTargetScraper +from ..base_scraper import fetch_bytes +from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores PLATFORM_NAME = "recalbox" @@ -33,13 +35,6 @@ DEFCONFIG_URL = "https://gitlab.com/recalbox/recalbox/-/raw/{tag}/configs/{name} _DEFCONFIG_RE = re.compile(r"^recalbox-(\w+)_defconfig$") _ENABLED_RE = re.compile(r"^(BR2_PACKAGE_\w+)=y\s*$", re.MULTILINE) -try: - from ..base_scraper import fetch_bytes - from ..recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores -except ImportError: - from scraper.base_scraper import fetch_bytes - from scraper.recalbox_scraper import SYSTEMS_TREE_URL, Scraper as PlatformScraper, board_cores - def enabled_packages(defconfig: str) -> set[str]: """The Buildroot packages a defconfig turns on.""" diff --git a/scripts/scraper/targets/rocknix_targets_scraper.py b/scripts/scraper/targets/rocknix_targets_scraper.py index 86cd8cf81..b106c66aa 100644 --- a/scripts/scraper/targets/rocknix_targets_scraper.py +++ b/scripts/scraper/targets/rocknix_targets_scraper.py @@ -23,6 +23,8 @@ from datetime import datetime, timezone import yaml from . import BaseTargetScraper +from ..base_scraper import fetch_bytes, github_headers +from ..rocknix_scraper import standalone_emulators PLATFORM_NAME = "rocknix" @@ -31,13 +33,6 @@ GITHUB_API = "https://api.github.com/repos/ROCKNIX/distribution/contents" EMULATORS_MK = "projects/ROCKNIX/packages/virtual/emulators/package.mk" DEVICES_DIR = "projects/ROCKNIX/devices" -try: - from ..base_scraper import fetch_bytes, github_headers - from ..rocknix_scraper import standalone_emulators -except ImportError: - from scraper.base_scraper import fetch_bytes, github_headers - from scraper.rocknix_scraper import standalone_emulators - # `NAME="a b \ # c"` or `NAME+=" a b"`, continuation lines joined first. _ASSIGN_RE = re.compile(r'^\s*(?:\[[^\]]*\]\s*&&\s*)?(\w+)(\+?=)"([^"]*)"', re.MULTILINE) @@ -98,6 +93,33 @@ _CORE_FILE_RE = re.compile(r"([\w+.-]+)_libretro\.(?:so\b|\{[^}]*\bso\b[^}]*\})" _TEST_RE = re.compile(r'\[\s*"\$\{(\w+)\}"\s*=\s*"([^"]*)"\s*\]') +def _holds(condition: str, values: dict[str, str]) -> bool: + tests = _TEST_RE.findall(condition) + if not tests or re.sub(_TEST_RE, "", condition).strip(" ;&") not in ("", "then"): + raise RuntimeError(f"makeinstall_target tests {condition.strip()!r}") + for variable, value in tests: + if variable not in values: + raise RuntimeError(f"makeinstall_target tests ${{{variable}}}") + if values[variable] != value: + return False + return True + + +def _copied_cores(line: str) -> list[str]: + """The core files one line of makeinstall_target copies, by installed name.""" + found: list[str] = [] + for sources, target in _COPY_RE.findall(line): + if named := _CORE_FILE_RE.search(target): + found.append(named.group(1)) + continue + found.extend( + named.group(1) for source in sources.split() + if not source.startswith("-") + and (named := _CORE_FILE_RE.search(source.rsplit("/", 1)[-1])) + ) + return found + + def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]: """The cores a libretro package installs on a device. @@ -115,17 +137,6 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]: # config/options:36 sets TARGET_ARCH="${ARCH}". values = {"ARCH": arch, "TARGET_ARCH": arch, "ENABLE_32BIT": "true" if with_32bit else "false"} - def holds(condition: str) -> bool: - tests = _TEST_RE.findall(condition) - if not tests or re.sub(_TEST_RE, "", condition).strip(" ;&") not in ("", "then"): - raise RuntimeError(f"makeinstall_target tests {condition.strip()!r}") - for variable, value in tests: - if variable not in values: - raise RuntimeError(f"makeinstall_target tests ${{{variable}}}") - if values[variable] != value: - return False - return True - found: list[str] = [] stack: list[bool] = [] in_case = False @@ -143,7 +154,7 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]: stack[-1] = arch in arm.group(1).split("|") or arm.group(1) == "*" line = arm.group(2) if line.startswith("if "): - stack.append(holds(line[3:])) + stack.append(_holds(line[3:], values)) continue if line == "else": stack[-1] = not stack[-1] @@ -153,13 +164,7 @@ def installed_cores(package_mk: str, arch: str, with_32bit: bool) -> list[str]: continue if not all(stack): continue - for sources, target in _COPY_RE.findall(line): - if named := _CORE_FILE_RE.search(target): - found.append(named.group(1)) - continue - for source in sources.split(): - if not source.startswith("-") and (named := _CORE_FILE_RE.search(source.rsplit("/", 1)[-1])): - found.append(named.group(1)) + found.extend(_copied_cores(line)) if not found: raise RuntimeError("makeinstall_target installs no libretro core") return sorted(set(found)) diff --git a/scripts/sect233r1.py b/scripts/sect233r1.py index 258077641..4e6f7127e 100644 --- a/scripts/sect233r1.py +++ b/scripts/sect233r1.py @@ -162,7 +162,7 @@ def _ec_mul(k: int, p: tuple[int, int] | None) -> tuple[int, int] | None: return _INF result = _INF - addend = p + addend: tuple[int, int] | None = p while k: if k & 1: result = _ec_add(result, addend) diff --git a/scripts/sourceref.py b/scripts/sourceref.py index a7436f977..f2e202a3c 100644 --- a/scripts/sourceref.py +++ b/scripts/sourceref.py @@ -356,6 +356,95 @@ def resolve_project_word(path: str, trees: Iterable[list[str] | None]) -> str | return None +def _joined_line(lines: list[str], number: int) -> tuple[str, int, int]: + """(line, boundary, joined_at) of one scalar line, its wrapped run joined. + + boundary is where the line's own text ends, joined_at where the next + line's text starts in the joined line, 0 when nothing was joined. + """ + # A literal block keeps its line breaks, so a citation wrapped after + # `file:` or after a range's comma lost the ranges on the next line + # (gearcoleco `libretro.cpp:` then four ranges). The next line is + # read as the run's continuation, and a run reaching into it is wrapped. + line = lines[number].rstrip() + boundary = len(line) + joined_at = 0 + following = lines[number + 1].lstrip() if number + 1 < len(lines) else "" + if PROSE_WRAPPED_RANGE_RE.match(following) and line[-1:].isalnum(): + # The break can fall before the colon too: jgenesis wraps + # `.../src/config.rs` then `:76-78,95-99` on the next line. + joined_at = len(line) + line += following + following = "" + # A numbered list after a colon (abuse: `setup.cpp:` then `1. -datadir`) + # is not a range. + if not following[:1].isdigit() or PROSE_LIST_ITEM_RE.match(following): + following = "" + if following and line.endswith(":"): + joined_at = len(line) + line += following + elif following and line.endswith(","): + joined_at = len(line) + 1 + line += " " + following + return line, boundary, joined_at + + +def _prose_events(line: str) -> list[tuple[int, int, re.Match]]: + """Citations, file names and abbreviated locations of a line, in order.""" + return sorted( + [(m.start(), 0, m) for m in PROSE_CITE_RE.finditer(line)] + + [(m.start(), 1, m) for m in _PROSE_FILE_NAMED_RE.finditer(line)] + + [(m.start(), 2, m) for m in _PROSE_ABBREVIATED_RE.finditer(line)], + key=lambda event: (event[0], event[1]), + ) + + +def _locate_run( + kind: int, match: re.Match, line: str, lines: list[str], number: int, + known: frozenset[str] | set[str], named: tuple[str, str] | None, +) -> tuple[tuple[str, str, int, tuple[int, int]] | None, tuple[str, str] | None]: + """(path, role, start, span) of the run an event opens, None when it + opens none, and the file named for the locations after it.""" + if kind == 1: + if "://" not in line[max(0, match.start() - 3):match.end()]: + named = (match.group("path"), "") + return None, named + if kind == 2: + if named is None: + return None, named + path, role = named + path_start = match.start() + return (path, role, path_start, (path_start, path_start)), named + found, role, path_start, path_span = _prose_path(line, lines, number, match, known) + if found is None: + return None, named + return (found, role, path_start, path_span), (found, role) + + +def _run_spans(line: str, match: re.Match) -> tuple[list[tuple[int, int]], int]: + """Range spans of the run a match opens, and where the run ends.""" + spans = [(match.start("range"), match.end("range"))] + end = match.end() + while True: + cont = PROSE_CONT_RE.match(line, end) + if cont is None and (listed := PROSE_CONT_LIST_RE.match(line, end)): + spans.extend( + (item.start(), item.end()) + for item in _PROSE_LIST_RANGE_RE.finditer( + line, end, listed.end() + ) + ) + end = listed.end() + break + if cont is None: + cont = PROSE_CONT_SPACED_RE.match(line, end) + if cont is None: + break + spans.append((cont.start("range"), cont.end("range"))) + end = cont.end() + return spans, end + + def _prose_runs( text: str, known: frozenset[str] | set[str] = frozenset() ) -> Iterator[tuple[ @@ -380,79 +469,19 @@ def _prose_runs( # Where the run wrapped from the line before ends in this one: its # ranges are that run's, not abbreviated locations of their own. carried = 0 - for number, own in enumerate(lines): - # A literal block keeps its line breaks, so a citation wrapped after - # `file:` or after a range's comma lost the ranges on the next line - # (gearcoleco `libretro.cpp:` then four ranges). The next line is - # read as the run's continuation, and a run reaching into it is wrapped. - line = own.rstrip() - boundary = len(line) - joined_at = 0 - following = lines[number + 1].lstrip() if number + 1 < len(lines) else "" - if PROSE_WRAPPED_RANGE_RE.match(following) and line[-1:].isalnum(): - # The break can fall before the colon too: jgenesis wraps - # `.../src/config.rs` then `:76-78,95-99` on the next line. - joined_at = len(line) - line += following - following = "" - # A numbered list after a colon (abuse: `setup.cpp:` then `1. -datadir`) - # is not a range. - if not following[:1].isdigit() or PROSE_LIST_ITEM_RE.match(following): - following = "" - if following and line.endswith(":"): - joined_at = len(line) - line += following - elif following and line.endswith(","): - joined_at = len(line) + 1 - line += " " + following + for number in range(len(lines)): + line, boundary, joined_at = _joined_line(lines, number) consumed, carried = carried, 0 - events = sorted( - [(m.start(), 0, m) for m in PROSE_CITE_RE.finditer(line)] - + [(m.start(), 1, m) for m in _PROSE_FILE_NAMED_RE.finditer(line)] - + [(m.start(), 2, m) for m in _PROSE_ABBREVIATED_RE.finditer(line)], - key=lambda event: (event[0], event[1]), - ) - for _start, kind, match in events: + for _start, kind, match in _prose_events(line): if match.start() >= boundary: break if match.start() < consumed: continue - if kind == 1: - if "://" not in line[max(0, match.start() - 3):match.end()]: - named = (match.group("path"), "") + located, named = _locate_run(kind, match, line, lines, number, known, named) + if located is None: continue - if kind == 2: - if named is None: - continue - path, role = named - path_start = match.start() - path_span = (path_start, path_start) - else: - path, role, path_start, path_span = _prose_path( - line, lines, number, match, known - ) - if path is None: - continue - named = (path, role) - spans = [(match.start("range"), match.end("range"))] - end = match.end() - while True: - cont = PROSE_CONT_RE.match(line, end) - if cont is None and (listed := PROSE_CONT_LIST_RE.match(line, end)): - spans.extend( - (item.start(), item.end()) - for item in _PROSE_LIST_RANGE_RE.finditer( - line, end, listed.end() - ) - ) - end = listed.end() - break - if cont is None: - cont = PROSE_CONT_SPACED_RE.match(line, end) - if cont is None: - break - spans.append((cont.start("range"), cont.end("range"))) - end = cont.end() + path, role, path_start, path_span = located + spans, end = _run_spans(line, match) consumed = end if end > boundary: indent = len(lines[number + 1]) - len(lines[number + 1].lstrip()) diff --git a/scripts/standalone_probe.py b/scripts/standalone_probe.py index cbf6a35a9..64b42bb3f 100644 --- a/scripts/standalone_probe.py +++ b/scripts/standalone_probe.py @@ -27,7 +27,6 @@ from __future__ import annotations import argparse import contextlib -import datetime as dt import hashlib import json import os @@ -49,6 +48,7 @@ from typing import IO sys.path.insert(0, str(Path(__file__).resolve().parent)) import core_probe as cp +from autorun import now_iso ROOT = Path(__file__).resolve().parent.parent CACHE = ROOT / ".cache" / "standalone" @@ -293,10 +293,6 @@ def installed(emu: Emulator, sha256: str | None, cache: Path = CACHE) -> tuple[d # One repetition # -------------------------------------------------------------------------- -def now_iso() -> str: - return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat() - - # The X server runs inside the sandbox, on the sandbox's own /tmp: the # display is private to the run, and the host's /tmp/.X11-unix (read-only # under WSLg) is never touched. Its fbdir option keeps the screen as an XWD @@ -338,6 +334,35 @@ def read_lines(stream: IO[bytes], out: list[dict], samples: list) -> None: out.append({"frame": len(samples), "level": "info", "text": text}) +def wait_for_screen(proc: subprocess.Popen, screen_file: Path, logs: list[dict]) -> None: + deadline = time.monotonic() + 30 + while not screen_file.exists(): + if proc.poll() is not None or time.monotonic() > deadline: + raise cp.ProbeError(f"Xvfb did not start in the sandbox (exit {proc.poll()}): " + f"{' / '.join(line['text'] for line in logs[-5:])}") + time.sleep(0.05) + + +def sample_screen(proc: subprocess.Popen, screen_file: Path, args: argparse.Namespace, + samples: list[tuple[float, str, bool]], png_dir: Path | None, started: float) -> dict | None: + """Hash the screen every interval. Returns how the emulator ended, None + while it still runs.""" + for index in range(args.samples): + target = started + (index + 1) * args.interval + while time.monotonic() < target and proc.poll() is None: + time.sleep(min(0.05, max(0.0, target - time.monotonic()))) + if proc.poll() is not None: + code = proc.returncode + return {"status": code if code >= 0 else None, + "signal": signal.Signals(-code).name if code < 0 else None} + width, height, rgb = parse_xwd(screen_file.read_bytes()) + sha1 = hashlib.sha1(rgb).hexdigest() + samples.append((round(time.monotonic() - started, 3), sha1, cp.uniform_frame(rgb, 3))) + if png_dir and not any(p.name.endswith(f"{sha1[:12]}.png") for p in png_dir.iterdir()): + (png_dir / f"{index:04d}-{sha1[:12]}.png").write_bytes(cp.png_bytes(width, height, rgb)) + return None + + def run_once(args: argparse.Namespace, emu: Emulator, tree: Path, system_dir: Path, scratch: Path, png_dir: Path | None) -> dict: home = scratch / "home" @@ -375,28 +400,9 @@ def run_once(args: argparse.Namespace, emu: Emulator, tree: Path, system_dir: Pa reader = threading.Thread(target=read_lines, args=(proc.stdout, logs, samples), daemon=True) reader.start() try: - deadline = time.monotonic() + 30 - while not screen_file.exists(): - if proc.poll() is not None or time.monotonic() > deadline: - raise cp.ProbeError(f"Xvfb did not start in the sandbox (exit {proc.poll()}): " - f"{' / '.join(line['text'] for line in logs[-5:])}") - time.sleep(0.05) + wait_for_screen(proc, screen_file, logs) started = time.monotonic() - ended = None - for index in range(args.samples): - target = started + (index + 1) * args.interval - while time.monotonic() < target and proc.poll() is None: - time.sleep(min(0.05, max(0.0, target - time.monotonic()))) - if proc.poll() is not None: - code = proc.returncode - ended = {"status": code if code >= 0 else None, - "signal": signal.Signals(-code).name if code < 0 else None} - break - width, height, rgb = parse_xwd(screen_file.read_bytes()) - sha1 = hashlib.sha1(rgb).hexdigest() - samples.append((round(time.monotonic() - started, 3), sha1, cp.uniform_frame(rgb, 3))) - if png_dir and not any(p.name.endswith(f"{sha1[:12]}.png") for p in png_dir.iterdir()): - (png_dir / f"{index:04d}-{sha1[:12]}.png").write_bytes(cp.png_bytes(width, height, rgb)) + ended = sample_screen(proc, screen_file, args, samples, png_dir, started) wall = time.monotonic() - started finally: stop(proc) @@ -608,13 +614,23 @@ def _probe(args: argparse.Namespace, emu: Emulator) -> int: return 0 +def _check_mode_problems(args: argparse.Namespace) -> list[str]: + problems = [] + if len({dest for dest, _ in args.vary}) != 1: + problems.append("--vary must name the same DEST in every occurrence") + problems.extend(f"--vary {dest}={src}: not a file" + for dest, src in args.vary if src and not Path(src).is_file()) + if args.observable not in OBSERVABLES: + problems.append(f"--observable {args.observable}: not one of {', '.join(OBSERVABLES)}") + return problems + + def validate(args: argparse.Namespace) -> list[str]: problems = [] if not Path(args.content).is_file(): problems.append(f"--content {args.content}: not a file") - for dest, src in args.bios_file: - if not Path(src).is_file(): - problems.append(f"--bios-file {dest}={src}: not a file") + problems.extend(f"--bios-file {dest}={src}: not a file" + for dest, src in args.bios_file if not Path(src).is_file()) if args.oracle and not Path(args.oracle).is_file(): problems.append(f"--oracle {args.oracle}: not a file") if args.samples < 2 or args.interval <= 0: @@ -630,13 +646,7 @@ def validate(args: argparse.Namespace) -> list[str]: if args.subject and not re.fullmatch(r"[a-z0-9]+(?:[-_][a-z0-9]+)*", args.subject): problems.append(f"--subject {args.subject!r}: lowercase letters, digits, - and _ only") if args.mode == "check": - if len({dest for dest, _ in args.vary}) != 1: - problems.append("--vary must name the same DEST in every occurrence") - for dest, src in args.vary: - if src and not Path(src).is_file(): - problems.append(f"--vary {dest}={src}: not a file") - if args.observable not in OBSERVABLES: - problems.append(f"--observable {args.observable}: not one of {', '.join(OBSERVABLES)}") + problems += _check_mode_problems(args) return problems diff --git a/scripts/upstream.py b/scripts/upstream.py index a37604cad..6c9b9133f 100644 --- a/scripts/upstream.py +++ b/scripts/upstream.py @@ -419,9 +419,9 @@ def fetch_file( return None if text == ABSENT else text.splitlines() if offline: raise NotCachedError(f"{repo.slug}@{sha[:8]}:{path} is not in the offline cache") - text = _http_text(content_url(repo, sha, path)) - write_cache(target, ABSENT if text is None else text) - return None if text is None else text.splitlines() + fetched = _http_text(content_url(repo, sha, path)) + write_cache(target, ABSENT if fetched is None else fetched) + return None if fetched is None else fetched.splitlines() # How long an answer about a moving reference stays trusted. A branch tip, a @@ -696,6 +696,15 @@ def _github_graphql( return payload +def _dig(value: object, *keys: str) -> object: + """The value under nested keys of a JSON answer, None where one is missing.""" + for key in keys: + if not isinstance(value, dict) or key not in value: + return None + value = value[key] + return value + + def newest_tag(repo: Repo, cache_dir: str, offline: bool = False) -> str | None: """The tag on the newest commit. @@ -708,10 +717,7 @@ def newest_tag(repo: Repo, cache_dir: str, offline: bool = False) -> str | None: _NEWEST_TAG_QUERY, {"owner": repo.owner, "name": repo.name}, cache_dir, offline, ) - try: - nodes = payload["data"]["repository"]["refs"]["nodes"] - except (TypeError, KeyError): - nodes = None + nodes = _dig(payload, "data", "repository", "refs", "nodes") if isinstance(nodes, list): return nodes[0].get("name") if nodes else None tags = list_tags(repo, cache_dir, offline) @@ -911,7 +917,7 @@ def ancestry( if ahead is None: return None if repo.family == "github": - behind = forward.get("behind_by") + behind = forward.get("behind_by") if isinstance(forward, dict) else None else: behind = _commits_ahead( _api(_compare_url(repo, head, base), cache_dir, offline), repo.family @@ -1132,8 +1138,8 @@ def list_gitlinks( if len(payload) < TREE_PAGE_SIZE: break return links - url = _tree_url(repo, sha) - payload = _api(url, cache_dir, offline) if url else None + tree_url = _tree_url(repo, sha) + payload = _api(tree_url, cache_dir, offline) if tree_url else None if not isinstance(payload, dict): return {} return { diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index e29bf0271..ab88b819e 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -30,7 +30,10 @@ import zipfile from collections.abc import Callable, Iterable from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any, TypedDict + +if TYPE_CHECKING: + from typing_extensions import Unpack sys.path.insert(0, os.path.dirname(__file__)) from common import ( @@ -99,7 +102,7 @@ class ValidationResult: def __init__(self, filepath: str) -> None: self.filepath = filepath self.filename = os.path.basename(filepath) - self.checks = [] # (status, message) tuples + self.checks: list[tuple[str, str]] = [] # (status, message) tuples self.sha1 = "" self.md5 = "" self.crc32 = "" @@ -410,46 +413,53 @@ def _archive_members( return described -def validate_file( - filepath: str, - db: dict | None, - platform_hashes: dict, - profile_hashes: dict | None = None, -) -> ValidationResult: - """Run all validation checks on a file.""" - result = ValidationResult(filepath) +@dataclass(frozen=True) +class _Review: + """One file under review and the tables it is read against.""" + filepath: str + db: dict | None + platform_hashes: dict + profile_hashes: dict + + +@dataclass(frozen=True) +class _Known: + """What declares the file: a platform's hash, its own check, a profile, its name.""" + + sha1: bool + md5: bool + other: bool + accepted_by: set[str] + by_profile: set[str] | None + name: bool + + @property + def by_platform(self) -> bool: + return bool(self.sha1 or self.md5 or self.other or self.accepted_by) + + +def _path_problem(filepath: str) -> str: + """Why the path cannot be reviewed, empty when it can.""" # Whoever opened the pull request chose this path, so its shape is # settled before anything is read. A symlink to an endless device would # otherwise be hashed until the job timed out, and a symlink out of the # checkout would be reported as though its target had been contributed. if os.path.islink(filepath): - result.add_check(False, "Symlinks are not allowed") - return result - + return "Symlinks are not allowed" if not os.path.exists(filepath): - result.add_check(False, f"File not found: {filepath}. A path is read from the folder " - "the command runs in, or pass --changed to check the files " - "changed under bios/") - return result - + return (f"File not found: {filepath}. A path is read from the folder " + "the command runs in, or pass --changed to check the files " + "changed under bios/") if os.path.isdir(filepath): - result.add_check(False, "Folder with no file in it") - return result - + return "Folder with no file in it" if not os.path.isfile(filepath): - result.add_check(False, "Not a regular file: a device, a pipe or a socket") - return result + return "Not a regular file: a device, a pipe or a socket" + return "" - result.size = os.path.getsize(filepath) - hashes = compute_hashes(filepath) - result.sha1 = hashes["sha1"] - result.md5 = hashes["md5"] - result.crc32 = hashes["crc32"] - - ext = os.path.splitext(filepath)[1].lower() - blocked = ext in BLOCKED_EXTENSIONS +def _check_size(result: ValidationResult) -> bool: + """The size checks, True when the file is too large for git.""" too_large = result.size > MAX_FILE_SIZE if too_large: # GitHub refuses a pushed file over 100 MiB, so a pull request cannot @@ -465,167 +475,179 @@ def validate_file( result.add_check(False, "File is empty (0 bytes)") else: result.add_check(True, f"File size within limits ({result.size:,} bytes)") + return too_large + +def _relative_path(filepath: str) -> str: # Paths are compared as the database writes them, relative to the # checkout: an absolute path to the file itself read as its duplicate. - relative = filepath if os.path.isabs(filepath): candidate = os.path.relpath(filepath, os.getcwd()) if not candidate.startswith(".."): - relative = candidate + return candidate + return filepath - if db: - if result.sha1 in db.get("files", {}): - existing = db["files"][result.sha1] - held_at = { - os.path.normpath(p) - for p in [existing.get("path"), *(existing.get("paths") or [])] if p - } - if os.path.normpath(relative) in held_at: - # The file the database was built from, not a copy of it: a - # PR that regenerated database.json was told each new file - # duplicated itself. - result.add_check(True, "Already in the database at this path") - elif _in_nodedup_dir(relative): - result.add_info( - f"Identical to `{existing['path']}`, kept: this tree is read by path" - ) - else: - result.outcome = "held" - result.add_warning( - f"Already held at `{existing['path']}`: nothing to add, " - "leave this copy out of the pull request" - ) - else: - result.add_check(True, "Not a duplicate in database") +def _check_duplicate(result: ValidationResult, db: dict, relative: str) -> None: + if result.sha1 not in db.get("files", {}): + result.add_check(True, "Not a duplicate in database") + return + existing = db["files"][result.sha1] + held_at = { + os.path.normpath(p) + for p in [existing.get("path"), *(existing.get("paths") or [])] if p + } + if os.path.normpath(relative) in held_at: + # The file the database was built from, not a copy of it: a + # PR that regenerated database.json was told each new file + # duplicated itself. + result.add_check(True, "Already in the database at this path") + elif _in_nodedup_dir(relative): + result.add_info( + f"Identical to `{existing['path']}`, kept: this tree is read by path" + ) + else: + result.outcome = "held" + result.add_warning( + f"Already held at `{existing['path']}`: nothing to add, " + "leave this copy out of the pull request" + ) + + +def _identify(review: _Review, result: ValidationResult, sha256: str) -> _Known: + platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes sha1_known = result.sha1 in platform_hashes.get("sha1", set()) md5_known = result.md5 in platform_hashes.get("md5", set()) other_known = ( - hashes.get("sha256", "") in platform_hashes.get("sha256", set()) + sha256 in platform_hashes.get("sha256", set()) or (result.crc32, result.size) in platform_hashes.get("crc32", set()) ) accepted_by = ( set() if sha1_known or md5_known or other_known - else _platforms_accepting(filepath, result.filename, platform_hashes) + else _platforms_accepting(review.filepath, result.filename, platform_hashes) ) - name_known = result.filename in platform_hashes.get("names", set()) - - profile_hashes = profile_hashes or {} by_profile = ( profile_hashes.get("sha1", {}).get(result.sha1) - or profile_hashes.get("sha256", {}).get(hashes.get("sha256", "")) + or profile_hashes.get("sha256", {}).get(sha256) or profile_hashes.get("md5", {}).get(result.md5) or profile_hashes.get("crc32", {}).get((result.crc32, result.size)) or profile_hashes.get("crc32", {}).get((result.crc32, None)) ) + return _Known(sha1_known, md5_known, other_known, accepted_by, by_profile, + result.filename in platform_hashes.get("names", set())) - if blocked: - # An executable is refused unless an emulator profile pins its exact - # bytes: PICO-8's pico8.exe and SDL2.dll are declared by sha1 from the - # official archive. A weak hash (md5, crc32) never vouches for code. - pinned = ( - profile_hashes.get("sha1", {}).get(result.sha1) - or profile_hashes.get("sha256", {}).get(hashes.get("sha256", "")) - ) - if pinned: - result.add_check( - True, - f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}", - ) - else: - result.add_check(False, f"Blocked file extension: {ext}") - # The files of a ZIP no list declares whole, when the upload is one. - members: list[str] | None = None - if sha1_known: - result.add_check(True, "SHA1 matches known platform requirement") - elif md5_known: - result.add_check(True, "MD5 matches known platform requirement") - elif other_known: - result.add_check(True, "Hash matches known platform requirement") - elif accepted_by: +def _check_executable(result: ValidationResult, sha256: str, profile_hashes: dict, ext: str) -> None: + # An executable is refused unless an emulator profile pins its exact + # bytes: PICO-8's pico8.exe and SDL2.dll are declared by sha1 from the + # official archive. A weak hash (md5, crc32) never vouches for code. + pinned = ( + profile_hashes.get("sha1", {}).get(result.sha1) + or profile_hashes.get("sha256", {}).get(sha256) + ) + if pinned: result.add_check( - True, "Accepted by the platform's own check: " + ", ".join(sorted(accepted_by)) + True, + f"Executable whose bytes an emulator profile pins by sha1: {', '.join(sorted(pinned))}", ) - elif by_profile: - names = sorted(by_profile) + else: + result.add_check(False, f"Blocked file extension: {ext}") + + +def _check_known(review: _Review, result: ValidationResult, known: _Known, too_large: bool) -> list[str] | None: + """What declares the file, and the files of a ZIP no list declares + whole, when the upload is one.""" + if known.sha1: + result.add_check(True, "SHA1 matches known platform requirement") + elif known.md5: + result.add_check(True, "MD5 matches known platform requirement") + elif known.other: + result.add_check(True, "Hash matches known platform requirement") + elif known.accepted_by: + result.add_check( + True, "Accepted by the platform's own check: " + ", ".join(sorted(known.accepted_by)) + ) + elif known.by_profile: + names = sorted(known.by_profile) shown = ", ".join(names[:5]) + (f" and {len(names) - 5} more" if len(names) > 5 else "") result.add_check(True, f"Hash matches a file the emulator profile declares: {shown}") - elif name_known: + elif known.name: result.add_warning( "Filename matches a known requirement but hash differs - may be a variant" ) else: result.outcome = "unknown" members = None if too_large else _archive_members( - filepath, db, platform_hashes, profile_hashes + review.filepath, review.db, review.platform_hashes, review.profile_hashes ) - if members is not None: - # A folder zipped to upload many files at once was hashed as one - # file and its contributor asked where that dump came from. - shown = "; ".join(members[:10]) + ( - f"; and {len(members) - 10} more" if len(members) > 10 else "" - ) - result.add_warning( - "A ZIP no platform list or emulator profile declares as a whole: " - "add the files it holds, unzipped, not the archive. Inside: " - + (shown or "nothing") - ) - else: - result.add_warning( - "Not recognised: no platform list or emulator profile declares this " - f"file. Say in the {'issue' if too_large else 'pull request'} which " - "emulator reads it, for which system, and where the dump comes from" - ) + _report_unknown(result, members, too_large) + return members + return None - normalized = os.path.normpath(relative) - values = (result.sha1, result.md5, hashes.get("sha256", "")) - expected = expected_folders(values, platform_hashes, profile_hashes) - if too_large: - # The file stays out of the pull request, so no folder of bios/ is - # the contributor's to choose: the release asset is placed by hand. - pass - elif normalized.startswith("bios" + os.sep): - parts = normalized.split(os.sep) - here = f"bios/{parts[1]}/{parts[2]}/" if len(parts) >= 4 else "" - makers = {folder.split("/")[1] for folder in expected} - if expected and (len(parts) < 4 or parts[1] not in makers): - # Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/. - result.add_warning( - "Placed under " + (here or "the bios/ root") + ", while the other files of " - "its system are in " + " or ".join(f"`{f}`" for f in expected) - ) - elif len(parts) >= 4: - result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/") - else: - result.add_warning("File should be in bios/Manufacturer/Console/ structure") - elif result.outcome == "held" or members is not None: - # Nothing to place: a copy, or an archive whose files go in unzipped. - pass + +def _report_unknown(result: ValidationResult, members: list[str] | None, too_large: bool) -> None: + if members is not None: + # A folder zipped to upload many files at once was hashed as one + # file and its contributor asked where that dump came from. + shown = "; ".join(members[:10]) + ( + f"; and {len(members) - 10} more" if len(members) > 10 else "" + ) + result.add_warning( + "A ZIP no platform list or emulator profile declares as a whole: " + "add the files it holds, unzipped, not the archive. Inside: " + + (shown or "nothing") + ) else: - # The contributor asks before forking: say where it goes. - spot = placement( - values, result.filename, db, platform_hashes, profile_hashes, - declared=bool(sha1_known or md5_known or other_known or accepted_by or by_profile), + result.add_warning( + "Not recognised: no platform list or emulator profile declares this " + f"file. Say in the {'issue' if too_large else 'pull request'} which " + "emulator reads it, for which system, and where the dump comes from" ) - result.destination = spot.destination(result.sha1) - copies = f". --place copies it to `{result.destination}`" if result.destination else "" - if spot.folders: - result.add_warning( - "File is not under bios/ yet. Its system's files are in " - + " or ".join(f"`{f}`" for f in spot.folders) + copies - ) - elif spot.home: - result.add_warning( - f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`" - + copies - ) - else: - result.add_warning( - "File is not under bios/ yet. Place it in bios/Manufacturer/Console/" - ) + +def _check_bios_placement(result: ValidationResult, normalized: str, expected: list[str]) -> None: + parts = normalized.split(os.sep) + here = f"bios/{parts[1]}/{parts[2]}/" if len(parts) >= 4 else "" + makers = {folder.split("/")[1] for folder in expected} + if expected and (len(parts) < 4 or parts[1] not in makers): + # Depth alone passed a PS1 BIOS filed under bios/Nintendo/Game Boy/. + result.add_warning( + "Placed under " + (here or "the bios/ root") + ", while the other files of " + "its system are in " + " or ".join(f"`{f}`" for f in expected) + ) + elif len(parts) >= 4: + result.add_check(True, f"Correct placement: bios/{parts[1]}/{parts[2]}/") + else: + result.add_warning("File should be in bios/Manufacturer/Console/ structure") + + +def _suggest_destination(review: _Review, result: ValidationResult, values: tuple[str, ...], + known: _Known) -> None: + # The contributor asks before forking: say where it goes. + spot = placement( + values, result.filename, review.db, review.platform_hashes, review.profile_hashes, + declared=bool(known.by_platform or known.by_profile), + ) + result.destination = spot.destination(result.sha1) + copies = f". --place copies it to `{result.destination}`" if result.destination else "" + if spot.folders: + result.add_warning( + "File is not under bios/ yet. Its system's files are in " + + " or ".join(f"`{f}`" for f in spot.folders) + copies + ) + elif spot.home: + result.add_warning( + f"File is not under bios/ yet. The collection keeps this name in `{spot.home}`" + + copies + ) + else: + result.add_warning( + "File is not under bios/ yet. Place it in bios/Manufacturer/Console/" + ) + + +def _check_declared_size(result: ValidationResult, platform_hashes: dict, profile_hashes: dict) -> bool: + """True when the size fits every declaration of the name.""" declared = [ *platform_hashes.get("sizes", {}).get(result.filename, []), *profile_hashes.get("sizes", {}).get(result.filename, []), @@ -639,27 +661,80 @@ def validate_file( f"Every declaration of {result.filename} expects {shown} bytes, " f"this file has {result.size:,}: truncated or another file" ) + return size_fits - if (name_known and not (sha1_known or md5_known or other_known or accepted_by) - and not by_profile and size_fits): - owners = name_systems(result.filename, platform_hashes, profile_hashes) - home = _variant_home(db, result.filename, "", set() if len(owners) > 1 else { - d for table in (platform_hashes, profile_hashes or {}) for s in owners - for d in table.get("system_dirs", {}).get(s, ()) - } if owners else None) - if not home and normalized.startswith("bios" + os.sep): - # Beside the file, in the folder the contributor chose. - home = os.path.dirname(normalized).replace(os.sep, "/") + "/" - slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}" - if home and not normalized.startswith("bios" + os.sep): - result.destination = slot - if home: - result.add_info( - f"This may be a valid variant. If accepted, it will be placed in `{slot}`" - ) - else: - result.add_info("This may be a valid variant of a file the collection lacks") +def _note_variant(review: _Review, result: ValidationResult, normalized: str) -> None: + platform_hashes, profile_hashes = review.platform_hashes, review.profile_hashes + owners = name_systems(result.filename, platform_hashes, profile_hashes) + home = _variant_home(review.db, result.filename, "", set() if len(owners) > 1 else { + d for table in (platform_hashes, profile_hashes) for s in owners + for d in table.get("system_dirs", {}).get(s, ()) + } if owners else None) + if not home and normalized.startswith("bios" + os.sep): + # Beside the file, in the folder the contributor chose. + home = os.path.dirname(normalized).replace(os.sep, "/") + "/" + slot = f"{home}.variants/{result.filename}.{result.sha1[:8]}" + if home and not normalized.startswith("bios" + os.sep): + result.destination = slot + if home: + result.add_info( + f"This may be a valid variant. If accepted, it will be placed in `{slot}`" + ) + else: + result.add_info("This may be a valid variant of a file the collection lacks") + + +def validate_file( + filepath: str, + db: dict | None, + platform_hashes: dict, + profile_hashes: dict | None = None, +) -> ValidationResult: + """Run all validation checks on a file.""" + result = ValidationResult(filepath) + problem = _path_problem(filepath) + if problem: + result.add_check(False, problem) + return result + + result.size = os.path.getsize(filepath) + hashes = compute_hashes(filepath) + result.sha1 = hashes["sha1"] + result.md5 = hashes["md5"] + result.crc32 = hashes["crc32"] + sha256 = hashes.get("sha256", "") + + ext = os.path.splitext(filepath)[1].lower() + too_large = _check_size(result) + relative = _relative_path(filepath) + if db: + _check_duplicate(result, db, relative) + + review = _Review(filepath, db, platform_hashes, profile_hashes or {}) + known = _identify(review, result, sha256) + if ext in BLOCKED_EXTENSIONS: + _check_executable(result, sha256, review.profile_hashes, ext) + members = _check_known(review, result, known, too_large) + + normalized = os.path.normpath(relative) + values = (result.sha1, result.md5, sha256) + if too_large: + # The file stays out of the pull request, so no folder of bios/ is + # the contributor's to choose: the release asset is placed by hand. + pass + elif normalized.startswith("bios" + os.sep): + _check_bios_placement(result, normalized, + expected_folders(values, platform_hashes, review.profile_hashes)) + elif result.outcome == "held" or members is not None: + # Nothing to place: a copy, or an archive whose files go in unzipped. + pass + else: + _suggest_destination(review, result, values, known) + + size_fits = _check_declared_size(result, platform_hashes, review.profile_hashes) + if known.name and not known.by_platform and not known.by_profile and size_fits: + _note_variant(review, result, normalized) return result @@ -734,16 +809,24 @@ class Placement: return self.folder + self.name +class PlacementOptions(TypedDict, total=False): + """How placement() tests a path, and the systems and directory a + declaration names.""" + + exists: Callable[[str], bool] + systems: Iterable[str] + directory: str + + def placement( values: Iterable[str], filename: str, db: dict | None, platform_hashes: dict, profile_hashes: dict | None, + *, declared: bool, - exists: Callable[[str], bool] = os.path.exists, - systems: Iterable[str] = (), - directory: str = "", + **options: Unpack[PlacementOptions], ) -> Placement: """Where a file goes, by its hashes and its name. @@ -761,6 +844,9 @@ def placement( copy by name counts only in a directory of that tail, and a held directory of that tail is the folder. """ + exists = options.get("exists", os.path.exists) + systems = options.get("systems", ()) + directory = options.get("directory", "") values = [value for value in values if value] folders = expected_folders(values, platform_hashes, profile_hashes) if folders: @@ -954,11 +1040,7 @@ def get_changed_files() -> list[str]: "staged, modified and untracked files only", file=sys.stderr, ) - seen: set[str] = set() - return [ - f for f in changed - if f.startswith("bios/") and not (f in seen or seen.add(f)) and os.path.isfile(f) - ] + return [f for f in dict.fromkeys(changed) if f.startswith("bios/") and os.path.isfile(f)] def expand_folders(paths: list[str]) -> list[str]: @@ -1054,11 +1136,11 @@ def main() -> None: ) # One output format: --json beside --markdown printed JSON and dropped # the markdown without a word. - output = parser.add_mutually_exclusive_group() - output.add_argument( + formats = parser.add_mutually_exclusive_group() + formats.add_argument( "--markdown", action="store_true", help="Output as markdown (for PR comments)" ) - output.add_argument("--json", action="store_true", help="Output as JSON") + formats.add_argument("--json", action="store_true", help="Output as JSON") parser.add_argument( "--place", action="store_true", help="copy each recognised file from outside bios/ to the folder and name " @@ -1095,21 +1177,20 @@ def main() -> None: all_passed = all(r.passed for r in results) if args.json: - output = [] - for r in results: - output.append( - { - "file": r.filepath, - "passed": r.passed, - # A file that failed, unread or refused, is not a new one. - "outcome": r.outcome or ("new" if r.passed else "failed"), - "destination": r.destination, - "sha1": r.sha1, - "md5": r.md5, - "size": r.size, - "checks": [{"status": s, "message": m} for s, m in r.checks], - } - ) + output = [ + { + "file": r.filepath, + "passed": r.passed, + # A file that failed, unread or refused, is not a new one. + "outcome": r.outcome or ("new" if r.passed else "failed"), + "destination": r.destination, + "sha1": r.sha1, + "md5": r.md5, + "size": r.size, + "checks": [{"status": s, "message": m} for s, m in r.checks], + } + for r in results + ] print(json.dumps(output, indent=2)) elif args.markdown: lines = ["## BIOS Validation Report", ""] diff --git a/scripts/validate_schemas.py b/scripts/validate_schemas.py index 60fff9a8f..b50923a0e 100644 --- a/scripts/validate_schemas.py +++ b/scripts/validate_schemas.py @@ -33,6 +33,13 @@ def _load_json(path: Path) -> object: return json.load(handle) +def _json_object(path: Path) -> dict: + data = _load_json(path) + if not isinstance(data, dict): + raise ValueError(f"{path}: not a JSON object") + return data + + def _validator(name: str) -> Draft202012Validator: schema = _load_json(SCHEMAS / name) Draft202012Validator.check_schema(schema) @@ -63,6 +70,16 @@ def _load_source(path: Path) -> object: return _SOURCES[key] +def _source_mapping(path: Path) -> dict: + """A source YAML that holds a mapping, empty when the file is.""" + document = _load_source(path) + if not document: + return {} + if not isinstance(document, dict): + raise ValueError(f"{path}: not a mapping") + return document + + def _validate_yaml_directory( directory: Path, schema_name: str, @@ -149,12 +166,11 @@ def _config_reads_without_build(path: Path, document: object) -> list[str]: continue if read.get("revision") or read.get("binary_sha256"): continue - for platform in read.get("platforms") or []: - if str(platform) not in builds: - out.append( - f"{path.relative_to(ROOT)}: config_reads[{index}] ({read.get('file')}) " - f"names {platform}, which has no pin_build" - ) + out.extend( + f"{path.relative_to(ROOT)}: config_reads[{index}] ({read.get('file')}) " + f"names {platform}, which has no pin_build" + for platform in read.get("platforms") or [] if str(platform) not in builds + ) return out @@ -272,12 +288,12 @@ def _data_only_source_refs(path: Path, document: object) -> list[str]: if not isinstance(entry, dict) or not entry.get("source_ref"): continue refs = entry["source_ref"] - for ref in refs.values() if isinstance(refs, dict) else [refs]: - if ref and not _ref_cites_code(str(ref)): - out.append( - f"{path.relative_to(ROOT)}: files[{index}] ({entry.get('name')}) " - f"source_ref cites no code that reads the file: {ref}" - ) + out.extend( + f"{path.relative_to(ROOT)}: files[{index}] ({entry.get('name')}) " + f"source_ref cites no code that reads the file: {ref}" + for ref in (refs.values() if isinstance(refs, dict) else [refs]) + if ref and not _ref_cites_code(str(ref)) + ) return out @@ -310,7 +326,7 @@ def _checks_without_values(path: Path, document: object) -> list[str]: def _validate_json_files( paths: list[Path], schema_name: str, - semantic_check: Callable[[Path, object], list[str]] | None = None, + semantic_check: Callable[[Path, dict], list[str]] | None = None, ) -> list[str]: validator = _validator(schema_name) out: list[str] = [] @@ -322,7 +338,8 @@ def _validate_json_files( continue validation_errors = _errors(validator, data, str(path.relative_to(ROOT))) out.extend(validation_errors) - if not validation_errors and semantic_check is not None: + # Every schema a semantic check follows describes an object. + if not validation_errors and semantic_check is not None and isinstance(data, dict): out.extend(semantic_check(path, data)) return out @@ -420,11 +437,11 @@ def _unreachable_citations(path: Path, document: object) -> list[str]: elif isinstance(node, list): stack.extend(node) elif isinstance(node, str): - for match in _UNREACHABLE_REF.finditer(node): - out.append( - f"{path.relative_to(ROOT)}: citation names a path outside " - f"any repository: {match.group().strip(' ,;(')}" - ) + out.extend( + f"{path.relative_to(ROOT)}: citation names a path outside " + f"any repository: {match.group().strip(' ,;(')}" + for match in _UNREACHABLE_REF.finditer(node) + ) return out @@ -464,7 +481,7 @@ def _unknown_data_dir_refs() -> list[str]: for path in source_yaml_paths(directory): if path.name.startswith("_"): continue - document = _load_source(path) or {} + document = _source_mapping(path) systems = document.get("systems") holders = [document, *(systems.values() if isinstance(systems, dict) else [])] for holder in holders: @@ -489,7 +506,7 @@ def _repository_layout_in_profiles() -> list[str]: """ out: list[str] = [] for path in source_yaml_paths(ROOT / "emulators"): - document = _load_source(path) or {} + document = _source_mapping(path) for entry in document.get("files") or []: if not isinstance(entry, dict): continue @@ -855,7 +872,7 @@ def _measurement_errors(root: Path | None = None) -> list[str]: def _defs_validator(name: str, definition: str) -> Draft202012Validator: """A validator for one $defs entry of a schema file.""" - schema = _load_json(SCHEMAS / name) + schema = _json_object(SCHEMAS / name) Draft202012Validator.check_schema(schema) return Draft202012Validator( {**schema, "$ref": f"#/$defs/{definition}"}, format_checker=FormatChecker() @@ -924,13 +941,13 @@ def _arcade_pin_errors() -> list[str]: code in place, and the installer kept serving it.""" out: list[str] = [] for path in sorted((ROOT / "games" / "arcade").glob("*.json")): - doc = _load_json(path) + doc = _json_object(path) profile_path = ROOT / "emulators" / f"{doc.get('profile')}.yml" label = str(path.relative_to(ROOT)) if not profile_path.is_file(): out.append(f"{label}: no profile emulators/{profile_path.name}") continue - profile = _load_source(profile_path) or {} + profile = _source_mapping(profile_path) pinned = profile.get("source_commit") pins = set(pinned.values()) if isinstance(pinned, dict) else {pinned} commit = (doc.get("source") or {}).get("commit") @@ -956,7 +973,7 @@ def _games_index_errors() -> list[str]: if not index_path.exists(): return [] out: list[str] = [] - index = _load_json(index_path) + index = _json_object(index_path) out.extend(_errors(_defs_validator("games-index.schema.json", "index"), index, str(index_path.relative_to(ROOT)))) kinds = { @@ -978,9 +995,8 @@ def _games_index_errors() -> list[str]: if len(data) != entry["size"] or hashlib.sha256(data).hexdigest() != entry["sha256"]: out.append(f"{label}: size or sha256 differs from index.json") out.extend(_errors(validator, json.loads(data), label)) - for path in sorted(base.rglob("*.json")): - if path != index_path and path not in listed: - out.append(f"{path.relative_to(ROOT)}: not listed in index.json") + out.extend(f"{path.relative_to(ROOT)}: not listed in index.json" + for path in sorted(base.rglob("*.json")) if path != index_path and path not in listed) return out diff --git a/scripts/version_basis.py b/scripts/version_basis.py index c4e169d2a..2bae72159 100644 --- a/scripts/version_basis.py +++ b/scripts/version_basis.py @@ -29,6 +29,7 @@ build mode, the way it keys core_version. from __future__ import annotations import re +from collections.abc import Callable from dataclasses import dataclass import upstream @@ -175,6 +176,123 @@ def _ancestry( return relation +@dataclass(frozen=True) +class _Request: + """One basis read for one build mode, and what its readings carry.""" + + profile: dict + mode: str + basis: dict + kind: str + stated: str | None + cache_dir: str + offline: bool + profiles: dict | None + recompute: bool + + def reading(self, value: str | None, where: str, updates: tuple = ()) -> Reading: + status = MATCH if value == self.stated else DRIFT + return Reading(self.mode, self.kind, self.stated, value, where, status, updates) + + def unreadable(self, reason: str) -> Reading: + return Reading(self.mode, self.kind, self.stated, None, reason, UNREADABLE) + + def repo_and_pin(self) -> tuple[upstream.Repo, str]: + return _repo_and_pin(self.profile, self.basis, self.mode, self.cache_dir, self.offline) + + +def _read_none(req: _Request) -> Reading: + if req.recompute: + # A release tagged since the basis was written gives the + # code a version: the advance has to name it. + repo, pin = req.repo_and_pin() + described = upstream.describe(repo, pin, req.cache_dir, req.offline) + if described is not None: + tag, distance = described + return Reading(req.mode, req.kind, req.stated, describe_form(tag, distance, pin), + f"{repo.slug}: tag {tag} is now in " + f"{pin[:7]}'s history", DRIFT) + return req.reading(None, "the code states no version") + + +def _read_unverified(req: _Request) -> Reading: + return Reading(req.mode, req.kind, req.stated, None, f"not verified: {req.basis.get('why')}", + UNCHECKED) + + +def _read_package(req: _Request) -> Reading: + artifact = str(req.basis.get("artifact") or "") + if req.basis.get("pattern"): + # An artefact named after its version says it in its name: + # advancemame-0.94.0.tar.gz. + found = read_text_version(artifact, str(req.basis["pattern"]), req.basis.get("format")) + if found is None: + return req.unreadable(f"{artifact}: pattern not found") + return req.reading(found[0], f"named by {artifact}") + return Reading(req.mode, req.kind, req.stated, None, f"read from {artifact}", UNCHECKED) + + +def _read_alias(req: _Request) -> Reading: + other = (req.profiles or {}).get(str(req.basis.get("of") or "")) + if other is None: + return req.unreadable(f"alias of {req.basis.get('of')}: no such profile") + return req.reading(declared(other, req.mode) if isinstance(other.get("core_version"), dict) + else declared(other, ""), f"alias of {req.basis['of']}") + + +def _read_file(req: _Request, repo: upstream.Repo, pin: str) -> Reading: + path = str(req.basis.get("path") or "") + lines = upstream.fetch_file(repo, pin, path, req.cache_dir, req.offline) + if lines is None: + return req.unreadable(f"{repo.slug}@{pin[:7]}:{path}: absent") + found = read_text_version("\n".join(lines), str(req.basis.get("pattern") or ""), + req.basis.get("format")) + if found is None: + return req.unreadable(f"{repo.slug}@{pin[:7]}:{path}: pattern not found") + value, line = found + return req.reading(value, f"{repo.slug}@{pin[:7]}:{path}:{line}") + + +def _read_tag(req: _Request, repo: upstream.Repo, pin: str) -> Reading: + basis = req.basis + if req.recompute: + described = upstream.describe(repo, pin, req.cache_dir, req.offline, basis.get("match")) + if described is None: + return req.unreadable(f"{repo.slug}@{pin[:7]}: no tag in its history") + tag, distance = described + else: + tag, distance = str(basis.get("tag") or ""), basis.get("distance") + commit = upstream.tag_commit(repo, tag, req.cache_dir, req.offline) + if commit is None: + return req.unreadable(f"{repo.slug}: no tag {tag}") + relation = (0, 0) if commit == pin else _ancestry( + repo, commit, pin, req.cache_dir, req.offline) + if relation is None: + return req.unreadable(f"{repo.slug}: {tag}...{pin[:7]} not comparable") + if relation[1]: + return req.unreadable(f"{repo.slug}: tag {tag} is not in {pin[:7]}'s history") + if relation[0] != distance: + return Reading(req.mode, req.kind, req.stated, describe_form(tag, relation[0], pin), + f"{repo.slug}: {pin[:7]} is {relation[0]} commits after " + f"{tag}, the basis says {distance}", DRIFT, + (("distance", relation[0]),)) + return req.reading(describe_form(tag, distance, pin), + f"{repo.slug}: tag {tag} + {distance}", + (("tag", tag), ("distance", distance))) + + +_OFF_FORGE: dict[str, Callable[[_Request], Reading]] = { + "none": _read_none, + "unverified": _read_unverified, + "package": _read_package, + "alias": _read_alias, +} +_ON_FORGE: dict[str, Callable[[_Request, upstream.Repo, str], Reading]] = { + "file": _read_file, + "tag": _read_tag, +} + + def read( profile: dict, mode: str, basis: dict, cache_dir: str, offline: bool, profiles: dict | None = None, recompute: bool = False, @@ -185,87 +303,20 @@ def read( has to: a recorded tag only proves its own distance, and a tag released between the two pins would go unseen. """ - stated = declared(profile, mode) kind = str(basis.get("kind") or "") - - def reading(value: str | None, where: str, updates: tuple = ()) -> Reading: - status = MATCH if value == stated else DRIFT - return Reading(mode, kind, stated, value, where, status, updates) - - def unreadable(reason: str) -> Reading: - return Reading(mode, kind, stated, None, reason, UNREADABLE) - + req = _Request(profile, mode, basis, kind, declared(profile, mode), + cache_dir, offline, profiles, recompute) try: - if kind == "none": - if recompute: - # A release tagged since the basis was written gives the - # code a version: the advance has to name it. - repo, pin = _repo_and_pin(profile, basis, mode, cache_dir, offline) - described = upstream.describe(repo, pin, cache_dir, offline) - if described is not None: - return Reading(mode, kind, stated, describe_form(*described, pin), - f"{repo.slug}: tag {described[0]} is now in " - f"{pin[:7]}'s history", DRIFT) - return reading(None, "the code states no version") - if kind == "unverified": - return Reading(mode, kind, stated, None, f"not verified: {basis.get('why')}", - UNCHECKED) - if kind == "package": - artifact = str(basis.get("artifact") or "") - if basis.get("pattern"): - # An artefact named after its version says it in its name: - # advancemame-0.94.0.tar.gz. - found = read_text_version(artifact, str(basis["pattern"]), basis.get("format")) - if found is None: - return unreadable(f"{artifact}: pattern not found") - return reading(found[0], f"named by {artifact}") - return Reading(mode, kind, stated, None, f"read from {artifact}", UNCHECKED) - if kind == "alias": - other = (profiles or {}).get(str(basis.get("of") or "")) - if other is None: - return unreadable(f"alias of {basis.get('of')}: no such profile") - return reading(declared(other, mode) if isinstance(other.get("core_version"), dict) - else declared(other, ""), f"alias of {basis['of']}") - repo, pin = _repo_and_pin(profile, basis, mode, cache_dir, offline) - if kind == "file": - path = str(basis.get("path") or "") - lines = upstream.fetch_file(repo, pin, path, cache_dir, offline) - if lines is None: - return unreadable(f"{repo.slug}@{pin[:7]}:{path}: absent") - found = read_text_version("\n".join(lines), str(basis.get("pattern") or ""), - basis.get("format")) - if found is None: - return unreadable(f"{repo.slug}@{pin[:7]}:{path}: pattern not found") - value, line = found - return reading(value, f"{repo.slug}@{pin[:7]}:{path}:{line}") - if kind == "tag": - if recompute: - described = upstream.describe(repo, pin, cache_dir, offline, basis.get("match")) - if described is None: - return unreadable(f"{repo.slug}@{pin[:7]}: no tag in its history") - tag, distance = described - else: - tag, distance = str(basis.get("tag") or ""), basis.get("distance") - commit = upstream.tag_commit(repo, tag, cache_dir, offline) - if commit is None: - return unreadable(f"{repo.slug}: no tag {tag}") - relation = (0, 0) if commit == pin else _ancestry( - repo, commit, pin, cache_dir, offline) - if relation is None: - return unreadable(f"{repo.slug}: {tag}...{pin[:7]} not comparable") - if relation[1]: - return unreadable(f"{repo.slug}: tag {tag} is not in {pin[:7]}'s history") - if relation[0] != distance: - return Reading(mode, kind, stated, describe_form(tag, relation[0], pin), - f"{repo.slug}: {pin[:7]} is {relation[0]} commits after " - f"{tag}, the basis says {distance}", DRIFT, - (("distance", relation[0]),)) - return reading(describe_form(tag, distance, pin), - f"{repo.slug}: tag {tag} + {distance}", - (("tag", tag), ("distance", distance))) + off_forge = _OFF_FORGE.get(kind) + if off_forge is not None: + return off_forge(req) + repo, pin = req.repo_and_pin() + on_forge = _ON_FORGE.get(kind) + if on_forge is not None: + return on_forge(req, repo, pin) except (upstream.UpstreamError, VersionUnreadable) as exc: - return unreadable(str(exc)) - return unreadable(f"unknown kind {kind!r}") + return req.unreadable(str(exc)) + return req.unreadable(f"unknown kind {kind!r}") def check( diff --git a/tests/test_archive_build.py b/tests/test_archive_build.py index 935b94a66..9d79a2a45 100644 --- a/tests/test_archive_build.py +++ b/tests/test_archive_build.py @@ -198,9 +198,9 @@ class Capture(Fixture): self.assertEqual(records["bios/set.zip"]["members"][0]["sha1"], "kept") def test_zlib_ng_refuses_to_capture(self): - with mock.patch.object(archive_build, "zlib_ng_version", lambda: "2.2.4"): - with self.assertRaises(archive_build.ZlibNgError): - self.capture() + with mock.patch.object(archive_build, "zlib_ng_version", lambda: "2.2.4"), \ + self.assertRaises(archive_build.ZlibNgError): + self.capture() def test_composite_and_zipped_pins_name_no_container(self): platforms = self.root / "platforms" diff --git a/tests/test_archive_recipes.py b/tests/test_archive_recipes.py index 6d88d00ea..083fe9437 100644 --- a/tests/test_archive_recipes.py +++ b/tests/test_archive_recipes.py @@ -85,56 +85,86 @@ def _hashes(values: object) -> set[str]: return {str(value).strip().lower() for value in raw if str(value).strip()} +def _allowed_members() -> dict[str, set[str]]: + from common import load_emulator_profiles + from romset_recipes import load_dat_recipes + + allowed: dict[str, set[str]] = defaultdict(set) + for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items(): + for recipe in per_label.values(): + allowed[archive.lower()] |= {crc for _name, crc in recipe} + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) + for profile in profiles.values(): + for entry in profile.get("files", []) or []: + crcs = { + str(member.get("crc32") or "").lower() + for member in entry.get("contents") or [] + } + crcs.discard("") + if not crcs: + continue + for name in [entry.get("name", "")] + list(entry.get("aliases") or []): + if name: + allowed[str(name).lower()] |= crcs + for name, devices in DEVICE_ROMS.items(): + for device in devices: + allowed[name] |= allowed.get(device, set()) + return allowed + + +def _platform_pins() -> tuple[set[str], dict[str, set[tuple[str, str]]]]: + from common import list_registered_platforms, load_platform_config + + pinned: set[str] = set() + zipped: dict[str, set[tuple[str, str]]] = defaultdict(set) + platforms_dir = str(REPO_ROOT / "platforms") + for platform in list_registered_platforms(platforms_dir): + config = load_platform_config(platform, platforms_dir) + for system in config.get("systems", {}).values(): + for entry in system.get("files", []) or []: + if entry.get("zipped_file"): + for md5 in _hashes(entry.get("md5")): + zipped[str(entry.get("name", "")).lower()].add( + (str(entry["zipped_file"]).casefold(), md5) + ) + continue + for key in ("md5", "sha1", "alt_md5"): + pinned |= _hashes(entry.get(key)) + return pinned, zipped + + +def _extra_members( + path: Path, name: str, allowed: set[str], zipped: set[tuple[str, str]] +) -> list[zipfile.ZipInfo] | None: + stem = name[:-4] + try: + with zipfile.ZipFile(path) as archive: + extra = [ + info for info in archive.infolist() + if not info.is_dir() + and f"{info.CRC:08x}" not in allowed + # a merged set keeps each clone in a folder of its name + and not ("/" in info.filename and info.filename.split("/")[0] != stem) + ] + return [ + info for info in extra + if (info.filename.casefold(), + hashlib.md5(archive.read(info)).hexdigest()) not in zipped + ] + except zipfile.BadZipFile: + return None + + class HeldArchivesMatchTheirRecipes(unittest.TestCase): def test_no_member_outside_every_recipe_of_the_name(self): bios = REPO_ROOT / "bios" if not bios.is_dir() or not (REPO_ROOT / "recipes").is_dir(): self.skipTest("bios/ or recipes/ is not present") - from common import ( - list_registered_platforms, - load_emulator_profiles, - load_platform_config, - variant_base_name, - ) + from common import variant_base_name from hashing import md5_composite_of - from romset_recipes import load_dat_recipes - allowed: dict[str, set[str]] = defaultdict(set) - for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items(): - for recipe in per_label.values(): - allowed[archive.lower()] |= {crc for _name, crc in recipe} - profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) - for profile in profiles.values(): - for entry in profile.get("files", []) or []: - crcs = { - str(member.get("crc32") or "").lower() - for member in entry.get("contents") or [] - } - crcs.discard("") - if not crcs: - continue - for name in [entry.get("name", "")] + list(entry.get("aliases") or []): - if name: - allowed[str(name).lower()] |= crcs - for name, devices in DEVICE_ROMS.items(): - for device in devices: - allowed[name] |= allowed.get(device, set()) - - pinned: set[str] = set() - zipped: dict[str, set[tuple[str, str]]] = defaultdict(set) - platforms_dir = str(REPO_ROOT / "platforms") - for platform in list_registered_platforms(platforms_dir): - config = load_platform_config(platform, platforms_dir) - for system in config.get("systems", {}).values(): - for entry in system.get("files", []) or []: - if entry.get("zipped_file"): - for md5 in _hashes(entry.get("md5")): - zipped[str(entry.get("name", "")).lower()].add( - (str(entry["zipped_file"]).casefold(), md5) - ) - continue - for key in ("md5", "sha1", "alt_md5"): - pinned |= _hashes(entry.get(key)) + allowed = _allowed_members() + pinned, zipped = _platform_pins() offenders = [] for path in sorted(bios.rglob("*")): @@ -143,22 +173,8 @@ class HeldArchivesMatchTheirRecipes(unittest.TestCase): continue if path.parent.name in NOT_ROMSETS: continue - stem = name[:-4] - try: - with zipfile.ZipFile(path) as archive: - extra = [ - info for info in archive.infolist() - if not info.is_dir() - and f"{info.CRC:08x}" not in allowed[name] - # a merged set keeps each clone in a folder of its name - and not ("/" in info.filename and info.filename.split("/")[0] != stem) - ] - extra = [ - info for info in extra - if (info.filename.casefold(), - hashlib.md5(archive.read(info)).hexdigest()) not in zipped[name] - ] - except zipfile.BadZipFile: + extra = _extra_members(path, name, allowed[name], zipped[name]) + if extra is None: continue if len(extra) < MIN_EXTRA or str(path.relative_to(REPO_ROOT)) in KEPT: continue diff --git a/tests/test_artifact_lock.py b/tests/test_artifact_lock.py index ba3e2d2a6..aec1ec691 100644 --- a/tests/test_artifact_lock.py +++ b/tests/test_artifact_lock.py @@ -54,9 +54,10 @@ class ArtifactLockTest(unittest.TestCase): pass def test_writer_excludes_reader(self): - with artifact_lock(self.dir), self.assertRaises(ArtifactLockBusy): - with artifact_lock(self.dir, exclusive=False): - pass + with artifact_lock(self.dir), \ + self.assertRaises(ArtifactLockBusy), \ + artifact_lock(self.dir, exclusive=False): + pass def test_readers_share(self): with artifact_lock(self.dir, exclusive=False), artifact_lock(self.dir, exclusive=False): @@ -121,6 +122,7 @@ class PackLockCliTest(unittest.TestCase): text=True, cwd=str(scratch_checkout()), timeout=300, + check=False, ) def test_generate_pack_refuses_locked_output(self): @@ -162,6 +164,7 @@ class PackLockCliTest(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "misterfpga", "--platforms-dir", str(platforms), "--output-dir", str(output)], capture_output=True, text=True, cwd=str(REPO_ROOT), timeout=120, + check=False, ) except subprocess.TimeoutExpired: self.fail("generate_pack waited on the data tree instead of refusing") @@ -240,6 +243,7 @@ class PipelineHoldsItsFixedOutputs(unittest.TestCase): [sys.executable, "scripts/pipeline.py", "--offline", "--skip-docs", "--output-dir", scratch], capture_output=True, text=True, cwd=str(checkout), timeout=120, + check=False, ) self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) self.assertIn("another run is writing database.json", proc.stderr) @@ -260,21 +264,21 @@ class TheSuiteTakesTheRepositoryHoldInItsScratch(unittest.TestCase): scratch = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, scratch, True) moved = scratch / "repository-lock" - with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(moved)}): - with artifacts.hold_repository_outputs(str(REPO_ROOT)): - key = str(REPO_ROOT.resolve()).strip(os.sep).replace(os.sep, "__") - self.assertTrue((moved / key / ".lock").is_file()) - # Held there: a second hold in the same tree is refused. - with self.assertRaises(artifacts.ArtifactLockBusy): - with artifacts.hold_repository_outputs(str(REPO_ROOT)): - pass + with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(moved)}), \ + artifacts.hold_repository_outputs(str(REPO_ROOT)): + key = str(REPO_ROOT.resolve()).strip(os.sep).replace(os.sep, "__") + self.assertTrue((moved / key / ".lock").is_file()) + # Held there: a second hold in the same tree is refused. + with self.assertRaises(artifacts.ArtifactLockBusy), \ + artifacts.hold_repository_outputs(str(REPO_ROOT)): + pass def test_another_directory_keeps_its_own_lock(self): out = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, out, True) - with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(out / "x")}): - with artifacts.artifact_lock(str(out)): - self.assertTrue((out / ".lock").is_file()) + with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(out / "x")}), \ + artifacts.artifact_lock(str(out)): + self.assertTrue((out / ".lock").is_file()) self.assertFalse((out / "x").exists()) def test_the_suite_sets_it(self): @@ -401,6 +405,7 @@ class SiteGenerationHoldsDocs(unittest.TestCase): result = subprocess.run( [sys.executable, "scripts/generate_site.py", "--docs-dir", docs], cwd=scratch_checkout(), capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1, result.stdout + result.stderr) self.assertIn("in use by another run", result.stderr) diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index fa771b4a4..3d0904290 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -100,10 +100,14 @@ class EveryWriterGoesThroughIt(unittest.TestCase): for top in tree.body: if path.name == "generate_installer_doc.py" and getattr(top, "name", "") in sandbox: continue - for node in ast.walk(top): - if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) - and node.func.attr in ("write_text", "write_bytes")): - offenders.append(f"{path.name}:{node.lineno}") + offenders.extend( + f"{path.name}:{node.lineno}" + for node in ast.walk(top) + if ( + isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr in ("write_text", "write_bytes") + ) + ) self.assertEqual(offenders, []) def test_the_text_is_utf8_whatever_the_locale(self): diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 249175027..9eec9145e 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -30,11 +30,8 @@ except ImportError: else: HAS_JSONSCHEMA = True -ROOT = Path(__file__).resolve().parent.parent -TMP_ROOT = ROOT / "tmp" / "tests" -TMP_ROOT.mkdir(parents=True, exist_ok=True) -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import install from scripts import pipeline, region, region_audit @@ -45,6 +42,10 @@ from scripts.generate_pack import ( verify_pack_against_platform, ) +ROOT = Path(__file__).resolve().parent.parent +TMP_ROOT = ROOT / "tmp" / "tests" +TMP_ROOT.mkdir(parents=True, exist_ok=True) + class ReadmeRegressions(unittest.TestCase): """The README advertises commands, and these must stay executable. @@ -1283,7 +1284,7 @@ class PipelineRegressions(unittest.TestCase): "2a2 refresh FBNeo hashes", ): with self.subTest(failed_label=failed_label): - def fake_run(_command, label): + def fake_run(_command, label, failed_label=failed_label): return label != failed_label, "RetroArch: 1/1 OK\n" argv = ["pipeline.py", "--skip-packs", "--skip-docs"] @@ -2227,7 +2228,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): for position, step in enumerate(steps): if needle in step.get("name", "") or needle in str(step.get("run", "")): return position - self.fail(f"no step matching {needle!r}") + raise self.failureException(f"no step matching {needle!r}") def test_site_deploy_completes_the_checkout_before_generating(self): steps = self._steps("deploy-site.yml", "build") @@ -2281,6 +2282,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): [sys.executable, str(ROOT / "scripts" / "restore_large_files.py"), "--gitignore", missing, "--cache", directory], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) self.assertIn("lists the release assets", proc.stderr) @@ -2868,6 +2870,7 @@ class PreservedBytesAreNeverNormalised(unittest.TestCase): out = subprocess.run( ["git", "check-attr", "text", "--", path], capture_output=True, text=True, cwd=ROOT, + check=False, ).stdout return out.rsplit(":", 1)[-1].strip() @@ -2984,14 +2987,16 @@ class AMissingDependencyStopsTheBuild(unittest.TestCase): offenders = [] for path in sorted((ROOT / "scripts").rglob("*.py")): tree = ast.parse(path.read_text(encoding="utf-8")) - for node in ast.walk(tree): + offenders.extend( + f"{path.relative_to(ROOT)}:{node.lineno}" + for node in ast.walk(tree) if ( isinstance(node, ast.ExceptHandler) and isinstance(node.type, ast.Name) and node.type.id in ("ImportError", "ModuleNotFoundError") and all(isinstance(stmt, ast.Pass) for stmt in node.body) - ): - offenders.append(f"{path.relative_to(ROOT)}:{node.lineno}") + ) + ) self.assertEqual(offenders, []) @@ -3168,6 +3173,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", "--verify-packs", "--output-dir", directory], capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, ) self.assertNotEqual( named.returncode, 0, @@ -3180,6 +3186,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", "--output-dir", directory], capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, ) self.assertIn("SKIP (no pack in", swept.stdout) self.assertNotEqual(swept.returncode, 0, swept.stdout + swept.stderr) @@ -3285,6 +3292,7 @@ class ScriptsImportThreeWays(unittest.TestCase): return subprocess.run( [sys.executable, *args], capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, ) def test_imported_as_a_package(self): @@ -3761,9 +3769,9 @@ class TheDatabaseCacheIsWrittenWhole(unittest.TestCase): with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: path = os.path.join(directory, "cache", "db_cache.json") generate_db.save_cache(path, {"a": 1}) - with mock.patch.object(json, "dumps", side_effect=TypeError("miscomputed")): - with self.assertRaises(TypeError): - generate_db.save_cache(path, {"a": 2}) + with mock.patch.object(json, "dumps", side_effect=TypeError("miscomputed")), \ + self.assertRaises(TypeError): + generate_db.save_cache(path, {"a": 2}) self.assertEqual(generate_db.load_cache(path), {"a": 1}) self.assertEqual(os.listdir(os.path.dirname(path)), ["db_cache.json"]) @@ -4240,7 +4248,7 @@ class TriageSurvivesAForgeRefusal(unittest.TestCase): # A header row and a closing count frame the ranking. lines = out.getvalue().splitlines()[1:-1] self.assertEqual(len(lines), 2) - self.assertTrue(any("eden" in l and "unreachable" in l for l in lines)) + self.assertTrue(any("eden" in line and "unreachable" in line for line in lines)) class VerifyStrictAppliesInEveryMode(unittest.TestCase): @@ -4266,6 +4274,7 @@ class VerifyStrictAppliesInEveryMode(unittest.TestCase): return subprocess.run( [sys.executable, "scripts/verify.py", *flags], cwd=ROOT, capture_output=True, text=True, + check=False, ).returncode def test_emulator_and_system_modes_fail_on_a_missing_required_file(self): @@ -4608,6 +4617,7 @@ class EveryToolRefusesAFlagItWouldDrop(unittest.TestCase): proc = subprocess.run( [sys.executable, script, *argv], cwd=ROOT, capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) @@ -4746,8 +4756,8 @@ class TheToolsPageSaysWhatDedupDoes(unittest.TestCase): from scripts import dedup line = next( - l for l in (ROOT / "wiki" / "tools.md").read_text().splitlines() - if l.startswith("| `dedup.py`") + row for row in (ROOT / "wiki" / "tools.md").read_text().splitlines() + if row.startswith("| `dedup.py`") ) self.assertNotIn(".variants", line) for name in dedup.NODEDUP_DIRS: @@ -4868,6 +4878,7 @@ class GeneratedArtifactsMeetTheirSchemas(unittest.TestCase): proc = subprocess.run( [sys.executable, "scripts/validate_schemas.py"], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -6139,6 +6150,7 @@ class ATargetIsNamedWhenItRemovesTheCore(unittest.TestCase): [sys.executable, "scripts/cross_reference.py", "--platform", "batocera", "--target", "bcm2711", "--emulator", "dolphin"], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1) self.assertIn("bcm2711 target", result.stderr) @@ -6156,6 +6168,7 @@ class ANamedPackThatIsAbsentFails(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", "--verify-packs", "--output-dir", directory], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1) self.assertIn("retroarch: FAIL (no pack in", result.stdout) @@ -6169,6 +6182,7 @@ class ANamedPackThatIsAbsentFails(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", "--output-dir", directory], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1) self.assertIn("no pack to verify", result.stderr) @@ -6343,6 +6357,7 @@ class VerifyPacksRefusesWhatItCannotDo(unittest.TestCase): result = subprocess.run( [sys.executable, "scripts/generate_pack.py", *extra, "--output-dir", out], cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, ) self.assertEqual(result.returncode, 2, result.stderr[-300:]) self.assertIn("--verify-packs", result.stderr) @@ -6857,7 +6872,7 @@ class DocsDescribeTheRegistriesTheyName(unittest.TestCase): def test_the_dedup_list_is_named_whole_or_by_its_constant(self): from dedup import NODEDUP_DIRS tools = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") - line = next(l for l in tools.splitlines() if "NODEDUP_DIRS" in l) + line = next(entry for entry in tools.splitlines() if "NODEDUP_DIRS" in entry) # Compared as list items: `mame` was missing while the substring # test found it in `_mame_clones.json` on the same line. listed = line.split("`NODEDUP_DIRS`", 1)[1].split(":", 1)[1].rstrip(" |") @@ -7193,6 +7208,7 @@ class InstallerJsonKindsNeverOverwriteEachOther(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", *flags, "--offline", "--output-dir", tmp], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) return proc, before, target.read_text(encoding="utf-8") @@ -7334,6 +7350,7 @@ class ToolsRunFromAnyDirectory(unittest.TestCase): return subprocess.run( [sys.executable, *argv], cwd=cwd, capture_output=True, text=True, timeout=600, + check=False, ) def test_listing_works_from_scripts(self): @@ -7528,6 +7545,7 @@ class ATargetTypoIsAnErrorInEveryTool(unittest.TestCase): [sys.executable, f"scripts/{script}", "--platform", "retroarch", "--target", "swich"], cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, ) output = proc.stdout + proc.stderr self.assertNotEqual(proc.returncode, 0) @@ -7548,6 +7566,7 @@ class AnUnknownSystemIsRefusedBeforeAnyWork(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "batocera", "--system", "playstaton-nothing", "--output-dir", str(out)], cwd=ROOT, capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) self.assertIn( @@ -7651,9 +7670,11 @@ class ProfileNotesDescribeTheCoreAlone(unittest.TestCase): for number, line in enumerate(text.splitlines(), 1): if self.SHOUT.search(line): found.append(f"{path.stem}:{number}") - for match in re.finditer(r"\bunlike (?:the )?([\w+-]+)", line, re.I): - if match.group(1).casefold() in names: - found.append(f"{path.stem}:{number}") + found.extend( + f"{path.stem}:{number}" + for match in re.finditer(r"\bunlike (?:the )?([\w+-]+)", line, re.I) + if match.group(1).casefold() in names + ) self.assertEqual(found, []) @@ -7677,13 +7698,15 @@ class Ps2BiosImagesAreFoundByContent(unittest.TestCase): # Whatever the profile's own flags: TeknoParrot documents its # pcsx2x6 component, whose scan is the same (BiosTools.cpp:268-291 # at 583f0e90), and carries no agnostic flag. - for entry in profile.get("files") or []: + named.extend( + f"{path.stem}: {entry['name']}" + for entry in profile.get("files") or [] if ( entry.get("min_size") in (2097152, 4194304) and entry.get("max_size") == 8388608 and opens_by_name(entry, profile) - ): - named.append(f"{path.stem}: {entry['name']}") + ) + ) self.assertEqual(named, []) @@ -7723,11 +7746,15 @@ class Dev9FilesAreReadFromTheWorkingDirectory(unittest.TestCase): unset = [] for path in sorted((ROOT / "emulators").glob("*.yml")): profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - for entry in profile.get("files") or []: - if entry.get("name") in ("eeprom.dat", "flash.dat") and "DEV9" in str( - entry.get("source_ref") - ) and entry.get("load_from") != "working_directory": - unset.append(f"{path.stem}: {entry['name']}") + unset.extend( + f"{path.stem}: {entry['name']}" + for entry in profile.get("files") or [] + if ( + entry.get("name") in ("eeprom.dat", "flash.dat") + and "DEV9" in str(entry.get("source_ref")) + and entry.get("load_from") != "working_directory" + ) + ) self.assertEqual(unset, []) diff --git a/tests/test_autorun.py b/tests/test_autorun.py index 2cdbd4d5a..7d0515ead 100644 --- a/tests/test_autorun.py +++ b/tests/test_autorun.py @@ -512,7 +512,7 @@ class Commits(Origin): with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(ar.run_job(ctx, "n"), (ar.OK, "dry run")) lines = ar.describe(ctx.jobs["n"], ctx) - would = sorted(l.split("would commit ")[1] for l in lines if "would commit" in l) + would = sorted(line.split("would commit ")[1] for line in lines if "would commit" in line) self.assertEqual(would, ["database.json", "install/b.json"]) self.assertEqual(run_git(wt, "diff", "--cached", "--name-only"), "") self.assertFalse(ctx.state_path.exists()) @@ -620,7 +620,7 @@ class Push(Origin): class RunnerPush(Origin): def _ctx(self, value: int, push: bool) -> ar.Context: - write = "open('database.json', 'w').write('{\"n\": %d}')" % value + write = f"open('database.json', 'w').write('{{\"n\": {value:d}}}')" jobs = {"n": {"min_free_gb": 0, "steps": [[PY, "-c", write]], "commits": [ {"subject": "chore: regenerate collection records", "paths": ["database.json"]}]}} return ar.Context(repo=self.repo, jobs=ar.parse_jobs({"jobs": jobs}), diff --git a/tests/test_campaign.py b/tests/test_campaign.py index f1f41b7cb..512d44365 100644 --- a/tests/test_campaign.py +++ b/tests/test_campaign.py @@ -29,14 +29,15 @@ from types import MappingProxyType import yaml -REPO_ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(REPO_ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import campaign import campaign_profiles import campaign_rules as rules import measurement_records as mr +REPO_ROOT = Path(__file__).resolve().parent.parent + TMP = REPO_ROOT / "tmp" / "tests" PROFILE = """\ diff --git a/tests/test_core_data_trees.py b/tests/test_core_data_trees.py index 6d352552b..18e658ca5 100644 --- a/tests/test_core_data_trees.py +++ b/tests/test_core_data_trees.py @@ -173,7 +173,7 @@ class AmberelecCarriesTheMachines(unittest.TestCase): (full, src) for src, full in builder._data_directory_members( config.get("systems", {}), registry, "amberelec", config.get("base_destination", ""), False, set(), set(), set(), - refs, core_trees=trees, + refs_out=refs, core_trees=trees, ) ) finally: @@ -204,7 +204,7 @@ class TheCountLineKeepsTreesOutOfTheBaseline(unittest.TestCase): "myminui", "platforms", db, "bios", "tmp", offline=True, record=record, data_registry=common.load_data_dir_registry("platforms"), ) - line = next(l for l in out.getvalue().splitlines() if "files packed" in l) + line = next(entry for entry in out.getvalue().splitlines() if "files packed" in entry) self.assertIn("(0 baseline + ", line) if record.trees: self.assertIn(f"+ {len(record.trees)} in core data trees + ", line) diff --git a/tests/test_core_file_fills_declaration.py b/tests/test_core_file_fills_declaration.py index 499f67dd2..52f281334 100644 --- a/tests/test_core_file_fills_declaration.py +++ b/tests/test_core_file_fills_declaration.py @@ -370,13 +370,15 @@ class TheManifestResolvesLikeThePack(unittest.TestCase): for fn in ast.walk(ast.parse(source)): if not isinstance(fn, ast.FunctionDef) or fn.name == "generate_md5_pack": continue - for node in ast.walk(fn): + missing.extend( + f"{fn.name}:{node.lineno}" + for node in ast.walk(fn) if ( isinstance(node, ast.Call) and getattr(node.func, "id", None) == "resolve_file" and "data_dir_registry" not in {k.arg for k in node.keywords} - ): - missing.append(f"{fn.name}:{node.lineno}") + ) + ) self.assertEqual(missing, []) diff --git a/tests/test_core_probe.py b/tests/test_core_probe.py index de09f6af1..19a05d7d7 100644 --- a/tests/test_core_probe.py +++ b/tests/test_core_probe.py @@ -25,12 +25,13 @@ import unittest.mock from pathlib import Path from typing import ClassVar -REPO_ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(REPO_ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import core_probe import measurement_records +REPO_ROOT = Path(__file__).resolve().parent.parent + STRACE_SAMPLE = """\ 4242 openat(AT_FDCWD, "/sys/bios/card.bin", O_RDONLY) = 5 4242 openat(AT_FDCWD, "/sys/bios/missing.bin", O_RDONLY) = -1 ENOENT (No such file or directory) diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index 93b737253..7c86113ff 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -353,9 +353,11 @@ class ProfileContract(unittest.TestCase): offenders = [] for path in sorted((REPO_ROOT / "emulators").glob("*.yml")): document = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - for entry in document.get("files") or []: - if self._errors_for_directory_rules(entry): - offenders.append(f"{path.name}: {entry.get('name')}") + offenders.extend( + f"{path.name}: {entry.get('name')}" + for entry in document.get("files") or [] + if self._errors_for_directory_rules(entry) + ) self.assertEqual(offenders, []) @staticmethod @@ -402,6 +404,7 @@ class CollectionScanAndIgnoreRules(unittest.TestCase): listed = subprocess.run( ["git", "ls-files", "--others", "--ignored", "--exclude-standard", "bios"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) if listed.returncode != 0: self.skipTest("not a git checkout") diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index dea19f7cb..72caa8d1c 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -47,9 +47,11 @@ def _section(text: str, heading: str) -> str: def _table_rows(text: str) -> list[list[str]]: rows = [] - for line in text.splitlines(): - if line.startswith("|") and not re.match(r"\|\s*-", line): - rows.append([cell.strip() for cell in line.strip().strip("|").split(" | ")]) + rows.extend( + [cell.strip() for cell in line.strip().strip("|").split(" | ")] + for line in text.splitlines() + if line.startswith("|") and not re.match(r"\|\s*-", line) + ) return rows[1:] @@ -321,9 +323,11 @@ class PublishedHeadings(unittest.TestCase): offenders = [] for page in (ROOT / "README.md", ROOT / "CONTRIBUTING.md"): text = FENCED.sub("", page.read_text(encoding="utf-8")) - for title in re.findall(r"(?m)^#{1,4} (.+)$", text): - if _sentence_case(title) != title: - offenders.append(f"{page.name}: {title}") + offenders.extend( + f"{page.name}: {title}" + for title in re.findall(r"(?m)^#{1,4} (.+)$", text) + if _sentence_case(title) != title + ) self.assertEqual(offenders, [], "\n".join(offenders)) @@ -388,9 +392,11 @@ class DocstringsWithoutInsistence(unittest.TestCase): offenders = [] paths = sorted((ROOT / "scripts").rglob("*.py")) + [ROOT / "install.py"] for path in paths: - for line in _python_prose(path.read_text(encoding="utf-8")).splitlines(): - if self.TICS.search(line): - offenders.append(f"{path.relative_to(ROOT)}: {line.strip()[:80]}") + offenders.extend( + f"{path.relative_to(ROOT)}: {line.strip()[:80]}" + for line in _python_prose(path.read_text(encoding="utf-8")).splitlines() + if self.TICS.search(line) + ) self.assertEqual(offenders, [], "\n".join(offenders)) @@ -1026,9 +1032,11 @@ def unknown_commands(text: str) -> list[str]: if not source: wrong.append(name) continue - for option in re.findall(r"(? list[str]: if not part or part.lstrip().startswith(FOREIGN_COMMANDS): continue program = _owner(part) or default - for option in OPTION.findall(part): - if program is None or not has(program, option): - stale.append(f"{option} ({program}): {part.strip()}") + stale.extend( + f"{option} ({program}): {part.strip()}" + for option in OPTION.findall(part) + if program is None or not has(program, option) + ) for paragraph in re.split(r"\n\s*\n", _prose(text)): named = {m.group(1) for m in SCRIPT.finditer(paragraph)} - {"install.sh", "install.ps1"} owners = named | page_scripts | ({default} if default else set()) @@ -1531,9 +1542,11 @@ def stale_options(text: str, default: str | None) -> list[str]: continue own = _owner(span) candidates = {own} if own else owners - for option in OPTION.findall(span): - if not any(has(program, option) for program in candidates): - stale.append(f"{option} ({', '.join(sorted(candidates))}): {span}") + stale.extend( + f"{option} ({', '.join(sorted(candidates))}): {span}" + for option in OPTION.findall(span) + if not any(has(program, option) for program in candidates) + ) return stale @@ -1891,8 +1904,9 @@ class SkipFlagsNameTheSteps(unittest.TestCase): for node in ast.walk(ast.parse(source)): if (isinstance(node, ast.Call) and getattr(node.func, "attr", "") == "add_argument" and node.args and isinstance(node.args[0], ast.Constant)): - helps.update({node.args[0].value: ast.literal_eval(kw.value) - for kw in node.keywords if kw.arg == "help"}) + for kw in node.keywords: + if kw.arg == "help": + helps[node.args[0].value] = ast.literal_eval(kw.value) for flag in ("--skip-packs", "--skip-docs"): steps = set() for row in table.splitlines(): @@ -2094,10 +2108,10 @@ class LandingAChangeNamesTheCommitRules(unittest.TestCase): message = clone / "MSG" message.write_text("fix: address review 3 notes\n", encoding="utf-8") refused = subprocess.run([str(clone / ".git" / "hooks" / "commit-msg"), "MSG"], - cwd=clone, capture_output=True, text=True) + cwd=clone, capture_output=True, text=True, check=False) message.write_text("fix: say what the change does\n", encoding="utf-8") accepted = subprocess.run([str(clone / ".git" / "hooks" / "commit-msg"), "MSG"], - cwd=clone, capture_output=True, text=True) + cwd=clone, capture_output=True, text=True, check=False) self.assertEqual(refused.returncode, 1, refused.stderr) self.assertIn("which review asked for it", refused.stderr) self.assertEqual(accepted.returncode, 0, accepted.stderr) diff --git a/tests/test_download.py b/tests/test_download.py index 98b06a1e2..c63643278 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -478,6 +478,7 @@ class TestDownloadPython(DownloaderCase): capture_output=True, text=True, timeout=120, + check=False, ) if expect_success: self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -513,6 +514,7 @@ class TestDownloadPython(DownloaderCase): capture_output=True, text=True, timeout=60, + check=False, ) self.assertNotEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -525,6 +527,7 @@ class TestDownloadPython(DownloaderCase): capture_output=True, text=True, timeout=60, + check=False, ) self.assertNotEqual(proc.returncode, 0) self.assertIn("RETROBIOS_API", proc.stderr) @@ -541,6 +544,7 @@ class TestDownloadShell(DownloaderCase): capture_output=True, text=True, timeout=120, + check=False, ) if expect_success: self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -597,6 +601,7 @@ class TestDownloadShell(DownloaderCase): proc = subprocess.run( ["bash", str(SHELL), self.platform, str(self.dest)], env=env, capture_output=True, text=True, timeout=120, + check=False, ) self.assertNotEqual(proc.returncode, 0) self.assertEqual(installed.read_bytes(), b"valid") @@ -625,7 +630,8 @@ class TestDownloadShell(DownloaderCase): ) time.sleep(0.5) second = subprocess.run( - command, env=env, capture_output=True, text=True, timeout=120 + command, env=env, capture_output=True, text=True, timeout=120, + check=False, ) out, err = first.communicate(timeout=120) self.assertEqual(first.returncode, 0, out + err) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 065642dcb..781c592cf 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -2884,6 +2884,7 @@ class TestE2E(unittest.TestCase): ["python", "scripts/generate_pack.py", "--emulator", "test", "--split"], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) self.assertIn("error", result.stderr.lower()) @@ -2902,6 +2903,7 @@ class TestE2E(unittest.TestCase): ], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) @@ -2920,6 +2922,7 @@ class TestE2E(unittest.TestCase): ], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) @@ -2938,6 +2941,7 @@ class TestE2E(unittest.TestCase): ], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) @@ -6293,10 +6297,12 @@ struct BurnDriver BurnDrvneogeo = { ] for mode, flag, expected in matrix: with self.subTest(mode=mode, flag=flag): + self.assertEqual(expected, "refuse") result = subprocess.run( [sys.executable, "scripts/generate_pack.py", *mode, *flag, "--output-dir", os.path.join(self.root, "modecheck")], capture_output=True, text=True, cwd=repo, timeout=120, + check=False, ) combined = result.stdout + result.stderr self.assertNotEqual( @@ -6405,6 +6411,7 @@ struct BurnDriver BurnDrvneogeo = { [sys.executable, "scripts/generate_pack.py", "--system", "atari-lynx", "--offline", *extra, "--output-dir", out], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) names[label] = sorted( @@ -6427,6 +6434,7 @@ struct BurnDriver BurnDrvneogeo = { [sys.executable, "scripts/generate_pack.py", "--platform", "misterfpga", "--offline", "--source", "truth", "--output-dir", out], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertNotEqual(proc.returncode, 0) self.assertIn("a truth pack would hold nothing", proc.stderr) @@ -6445,6 +6453,7 @@ struct BurnDriver BurnDrvneogeo = { [sys.executable, "scripts/generate_pack.py", "--emulator", "handy", "--required-only", "--offline", "--output-dir", out], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertIn("no file needed, no pack written", proc.stdout) @@ -6452,6 +6461,7 @@ struct BurnDriver BurnDrvneogeo = { verify = subprocess.run( [sys.executable, "scripts/verify.py", "--emulator", "handy", "--required-only"], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(verify.returncode, proc.returncode) @@ -6477,6 +6487,7 @@ struct BurnDriver BurnDrvneogeo = { proc = subprocess.run( [sys.executable, *argv, *extra], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) self.assertIn("runs no core a profile describes", proc.stderr) diff --git a/tests/test_exporters.py b/tests/test_exporters.py index ae1c6589b..4bb1cc614 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -2603,6 +2603,7 @@ class UpstreamFidelity(unittest.TestCase): capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(result.stdout.strip()) @@ -2625,6 +2626,7 @@ class UpstreamFidelity(unittest.TestCase): capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) @@ -2639,7 +2641,8 @@ class UpstreamFidelity(unittest.TestCase): script = Path(tmp) / "checkBIOS.sh" script.write_text(produced["checkBIOS.sh"], encoding="utf-8") result = subprocess.run( - ["bash", "-n", str(script)], capture_output=True, text=True, timeout=60 + ["bash", "-n", str(script)], capture_output=True, text=True, timeout=60, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) @@ -2759,6 +2762,7 @@ class UpstreamFidelity(unittest.TestCase): capture_output=True, text=True, timeout=60, + check=False, ) with self.subTest(module=relative): self.assertEqual(result.returncode, 0, result.stderr) diff --git a/tests/test_fileless_audit.py b/tests/test_fileless_audit.py index 0c6cc7c04..62ba75023 100644 --- a/tests/test_fileless_audit.py +++ b/tests/test_fileless_audit.py @@ -16,11 +16,12 @@ import unittest from pathlib import Path from unittest import mock -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import fileless_audit +ROOT = Path(__file__).resolve().parent.parent + ASKS = [ "static void init(void)", diff --git a/tests/test_games_index.py b/tests/test_games_index.py index a6b93b938..374f8e221 100644 --- a/tests/test_games_index.py +++ b/tests/test_games_index.py @@ -230,6 +230,7 @@ class CommittedData(unittest.TestCase): result = subprocess.run( [sys.executable, "scripts/generate_games_index.py", "--check", "--quiet"], cwd=ROOT, capture_output=True, text=True, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr[-2000:]) diff --git a/tests/test_handheld_launchers.py b/tests/test_handheld_launchers.py index 4ea88c20b..b8201acf3 100644 --- a/tests/test_handheld_launchers.py +++ b/tests/test_handheld_launchers.py @@ -12,6 +12,7 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import contextlib import hashlib import importlib.util import json @@ -87,7 +88,7 @@ def read_gptk(path: Path) -> dict[str, list[str]]: mapping: dict[str, list[str]] = {} for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() - if not line or line.startswith("#") or line.startswith("["): + if not line or line.startswith(("#", "[")): continue key, sep, value = line.partition(" = ") assert sep, line @@ -359,9 +360,9 @@ class TheArchives(unittest.TestCase): self.assertEqual(labels["retroarch"], "RetroArch") expected = "".join(f"{p}\t{label}\n" for p, label in sorted(labels.items())) for name, (_script, folder) in self.LAYOUT.items(): - with self.subTest(archive=name): - with zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: - self.assertEqual(zf.read(f"{folder}/packs.txt").decode(), expected) + with self.subTest(archive=name), \ + zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: + self.assertEqual(zf.read(f"{folder}/packs.txt").decode(), expected) def test_an_unpinned_installer_is_refused(self): root = _tempdir(self) @@ -818,10 +819,8 @@ class Device: for name in ("mapper.pid", "ui.pid", "engine.pid"): path = self.state / name if path.exists(): - try: + with contextlib.suppress(ProcessLookupError, ValueError): os.kill(int(path.read_text()), signal.SIGKILL) - except (ProcessLookupError, ValueError): - pass def _left(self) -> list[int]: """The processes a run on this device started that still run: each @@ -881,10 +880,8 @@ class Device: pid = int((self.state / "mapper.pid").read_text()) stopped = (self.state / "mapper.stopped").exists() if not stopped: - try: + with contextlib.suppress(ProcessLookupError): os.kill(pid, signal.SIGKILL) - except ProcessLookupError: - pass self.test.assertTrue(stopped, "gptokeyb was left running") def assert_mapper_gone(self) -> None: diff --git a/tests/test_hidden_extras.py b/tests/test_hidden_extras.py index 452c3205c..bd4f8ff59 100644 --- a/tests/test_hidden_extras.py +++ b/tests/test_hidden_extras.py @@ -109,7 +109,7 @@ class TheReportSaysSo(unittest.TestCase): for u in self.results[platform]["undeclared_files"]: if u.get("emulator") == emulator and (u.get("path") or u.get("name")) == path: return u - self.skipTest(f"{emulator} {path} is not in the cross-reference") + raise unittest.SkipTest(f"{emulator} {path} is not in the cross-reference") def _listed(self, emulator: str, path: str, platform: str) -> bool: return any( diff --git a/tests/test_install.py b/tests/test_install.py index 305c26895..2f80a40b1 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -61,6 +61,52 @@ def _tempdir(test: unittest.TestCase) -> str: return path +def _parenthesized_withs(tokens: list) -> list[str]: + import tokenize + + found = [] + for i, tok in enumerate(tokens): + if tok.type == tokenize.NAME and tok.string == "with" and i + 1 < len(tokens): + if tokens[i + 1].string != "(": + continue + depth = 0 + for inner in tokens[i + 1:]: + if inner.string in "([{" and inner.type == tokenize.OP: + depth += 1 + elif inner.string in ")]}" and inner.type == tokenize.OP: + depth -= 1 + if depth == 0: + break + elif depth == 1 and inner.type == tokenize.NAME and inner.string == "as": + found.append(f"line {tok.start[0]}: parenthesized with") + break + return found + + +def _nested_fstrings(tokens: list) -> list[str]: + import tokenize + + found: list[str] = [] + fstring_start = getattr(tokenize, "FSTRING_START", None) + if fstring_start is None: + return found + stack = [] + for tok in tokens: + if tok.type == fstring_start: + if stack: + found.append(f"line {tok.start[0]}: f-string inside an f-string") + stack.append(tok.string[-1]) + elif tok.type == tokenize.FSTRING_END: + stack.pop() + elif stack and tok.type == tokenize.STRING and stack[-1] in tok.string: + found.append(f"line {tok.start[0]}: f-string reuses its quote") + elif stack and tok.type == tokenize.FSTRING_MIDDLE: + continue + elif stack and tok.type == tokenize.ERRORTOKEN and tok.string == "\\": + found.append(f"line {tok.start[0]}: backslash in an f-string field") + return found + + class TestShellUnquote(unittest.TestCase): def test_plain_value(self): self.assertEqual(install._shell_unquote("/userdata/bios"), "/userdata/bios") @@ -1670,39 +1716,8 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): import io import tokenize - found = [] tokens = list(tokenize.generate_tokens(io.StringIO(self.SOURCE).readline)) - for i, tok in enumerate(tokens): - if tok.type == tokenize.NAME and tok.string == "with" and i + 1 < len(tokens): - if tokens[i + 1].string != "(": - continue - depth = 0 - for inner in tokens[i + 1:]: - if inner.string in "([{" and inner.type == tokenize.OP: - depth += 1 - elif inner.string in ")]}" and inner.type == tokenize.OP: - depth -= 1 - if depth == 0: - break - elif depth == 1 and inner.type == tokenize.NAME and inner.string == "as": - found.append(f"line {tok.start[0]}: parenthesized with") - break - fstring_start = getattr(tokenize, "FSTRING_START", None) - if fstring_start is not None: - stack = [] - for tok in tokens: - if tok.type == fstring_start: - if stack: - found.append(f"line {tok.start[0]}: f-string inside an f-string") - stack.append(tok.string[-1]) - elif tok.type == tokenize.FSTRING_END: - stack.pop() - elif stack and tok.type == tokenize.STRING and stack[-1] in tok.string: - found.append(f"line {tok.start[0]}: f-string reuses its quote") - elif stack and tok.type == tokenize.FSTRING_MIDDLE: - continue - elif stack and tok.type == tokenize.ERRORTOKEN and tok.string == "\\": - found.append(f"line {tok.start[0]}: backslash in an f-string field") + found = _parenthesized_withs(tokens) + _nested_fstrings(tokens) self.assertEqual(found, []) def test_no_runtime_generic_builtin(self): @@ -2194,9 +2209,9 @@ class TestManualPlatformPrompt(unittest.TestCase): def test_quit_stops_like_ctrl_c(self): """`install.sh && retroarch` went on to start RetroArch with no BIOS after a q, which left with 0 where Ctrl+C leaves with 130.""" - with unittest.mock.patch("builtins.input", lambda _prompt="": "q"): - with self.assertRaises(SystemExit) as raised: - install._prompt_manual_platform("linux") + with unittest.mock.patch("builtins.input", lambda _prompt="": "q"), \ + self.assertRaises(SystemExit) as raised: + install._prompt_manual_platform("linux") self.assertEqual(raised.exception.code, install.QUIT_CODE) def test_quotes_around_a_typed_folder_are_dropped(self): @@ -2207,7 +2222,8 @@ class TestManualPlatformPrompt(unittest.TestCase): f' "{root}/My Card/bios" '): answers = iter(["1", typed]) with self.subTest(typed=typed), \ - unittest.mock.patch("builtins.input", lambda _prompt="": next(answers)), \ + unittest.mock.patch("builtins.input", + lambda _prompt="", answers=answers: next(answers)), \ contextlib.redirect_stdout(io.StringIO()): chosen = install._prompt_manual_platform("linux") self.assertEqual(chosen, [("retroarch", root / "My Card" / "bios")]) @@ -2217,7 +2233,8 @@ class TestManualPlatformPrompt(unittest.TestCase): answers = iter(["1", '"~/$RB_TEST_DIR/bios"']) with self.subTest(os_type=os_type), \ unittest.mock.patch.dict(os.environ, {"RB_TEST_DIR": "cards"}), \ - unittest.mock.patch("builtins.input", lambda _prompt="": next(answers)), \ + unittest.mock.patch("builtins.input", + lambda _prompt="", answers=answers: next(answers)), \ contextlib.redirect_stdout(io.StringIO()): chosen = install._prompt_manual_platform(os_type) self.assertEqual(chosen[0][1], Path.home() / "cards" / "bios") @@ -2313,6 +2330,7 @@ class TestLaunchboxDetectionPowershell(unittest.TestCase): capture_output=True, text=True, timeout=60, + check=False, ) finally: httpd.shutdown() @@ -2576,6 +2594,7 @@ class TestAvailablePlatforms(unittest.TestCase): capture_output=True, text=True, timeout=30, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertTrue(marker.is_file(), "piped bootstrap did not download install.py") @@ -2693,7 +2712,7 @@ class TestAvailablePlatforms(unittest.TestCase): proc = subprocess.run( [shutil.which("sh"), str(root / "install.sh")], env={"PATH": f"{fake_bin}{os.pathsep}{tools}", "HOME": str(root)}, - capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL, check=False) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertIn("ran True", proc.stdout) @@ -3174,7 +3193,7 @@ class TermuxStorageIsSetUpByTheBootstrap(unittest.TestCase): f"TERMUX_VERSION=0.118 /bin/sh {shlex.quote(str(root / 'install.sh'))}") proc = subprocess.run( [shutil.which("script"), "-qec", command, "/dev/null"], - capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) return proc, root def test_it_runs_once_then_the_installer(self): @@ -3209,7 +3228,7 @@ class APyLauncherWithoutARuntimeIsPassed(unittest.TestCase): proc = subprocess.run( [shutil.which("pwsh"), "-NoProfile", "-File", str(folder / "install.ps1")], env={**os.environ, "PATH": f"{fake_bin}{os.pathsep}/usr/bin/nonexistent"}, - capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertIn("installer ran", proc.stdout) @@ -3231,7 +3250,7 @@ class APowerShellDownloadThatNeverAnswersEnds(unittest.TestCase): ["pwsh", "-NoProfile", "-File", str(folder / "install.ps1"), "--check"], env={**os.environ, "RETROBIOS_INSTALL_URL": f"https://127.0.0.1:{port}/install.py"}, - capture_output=True, text=True, timeout=150, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=150, stdin=subprocess.DEVNULL, check=False) self.assertLess(time.monotonic() - started, 120) self.assertNotEqual(proc.returncode, 0) self.assertIn("could not be downloaded", " ".join((proc.stdout + proc.stderr).split())) @@ -3251,6 +3270,7 @@ class ThePowerShellWrapperPassesTheStatusOn(unittest.TestCase): proc = subprocess.run( ["pwsh", "-NoProfile", "-File", str(folder / "install.ps1")], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, code, proc.stderr) self.assertNotIn("installer failed", proc.stdout + proc.stderr) @@ -3274,6 +3294,7 @@ class ThePowerShellWrapperPassesEveryArgument(unittest.TestCase): proc = subprocess.run( ["pwsh", "-NoProfile", "-File", str(folder / "install.ps1"), *args], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual(json.loads(proc.stdout), args) @@ -3707,7 +3728,7 @@ class ACardPreparedOnAComputerGetsItsBoard(unittest.TestCase): [sys.executable, "-c", code, str(REPO_ROOT), str(self.boot), "--platform", "batocera", "--dest", str(self.share), "--manifest", str(self.list), "--offline", "--check", "--events", *extra], - env=env, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + env=env, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) events = [json.loads(line) for line in proc.stdout.splitlines() if line.startswith("{")] return proc.stdout + proc.stderr, events @@ -3795,7 +3816,7 @@ class APlatformWithoutTargetsSaysSoOffline(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--platform", "misterfpga", "--dest", str(dest), "--target", "de10-nano", "--offline", "--no-input", "--dry-run", *extra], - capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) self.assertEqual(proc.returncode, 2, proc.stderr) self.assertIn("MiSTer FPGA has no hardware targets", proc.stderr) self.assertNotIn("targets/misterfpga.json", proc.stderr) @@ -3893,6 +3914,7 @@ class TheBoardTheSystemNamesIsTheTarget(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--every-board", "--target", "bcm2711", "--platform", "batocera", "--dry-run"], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(result.returncode, 2) self.assertIn("--every-board", result.stderr) @@ -4837,7 +4859,10 @@ class WindowsSeenFromWsl(unittest.TestCase): self.assertEqual(os.environ["USERPROFILE"], str(self.root / "c" / "Users" / "me")) self.assertEqual(os.environ["APPDATA"], str(self.root / "c" / "Users" / "me" / "AppData" / "Roaming")) - self.assertEqual(os.environ["ProgramFiles"], "") + # ProgramFiles among them: cmd answered %ProgramFiles% unexpanded. + for name in sorted(set(install._WINDOWS_VARIABLES) - answers.keys()): + with self.subTest(variable=name): + self.assertEqual(os.environ[name], "") def test_a_steam_client_outside_program_files_is_found(self): @@ -5331,7 +5356,7 @@ class AnUnknownNameIsAnEvent(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--dest", dest, "--check", "--events", "--no-input", *argv], env=env, capture_output=True, text=True, timeout=120, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) return proc.returncode, [json.loads(line) for line in proc.stdout.splitlines()] def test_each_refusal_says_why(self): @@ -5653,7 +5678,7 @@ class ThePowerShellOneLinerLeavesTheSessionAlone(unittest.TestCase): env = {**os.environ, "RETROBIOS_INSTALL_URL": "http://127.0.0.1/install.py"} env.pop("RETROBIOS_BOOTSTRAP", None) proc = subprocess.run(["pwsh", "-NoProfile", "-Command", script], cwd=REPO_ROOT, - env=env, capture_output=True, text=True, timeout=120) + env=env, capture_output=True, text=True, timeout=120, check=False) self.assertIn("must use HTTPS", proc.stderr) self.assertIn("EAP=Continue temporary=[] installer=[] bootstrap=[]", proc.stdout) @@ -7217,7 +7242,7 @@ class AStrippedPythonIsNamed(unittest.TestCase): return subprocess.run( [sys.executable, "-c", code, str(REPO_ROOT / "install.py"), *argv], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) def test_a_missing_c_module_is_named(self): for hidden in ("zlib", "unicodedata"): diff --git a/tests/test_install_experience.py b/tests/test_install_experience.py index aaf65c0ab..3f0a6adc8 100644 --- a/tests/test_install_experience.py +++ b/tests/test_install_experience.py @@ -648,7 +648,7 @@ class ADetectedFolderUnderAClosedOne(unittest.TestCase): os.chmod(lock, 0o000) try: runs = {name: subprocess.run(command + extra, env=env, capture_output=True, - text=True, timeout=60, stdin=subprocess.DEVNULL) + text=True, timeout=60, stdin=subprocess.DEVNULL, check=False) for name, extra in (("check", ["--check"]), ("install", []))} kinds = install.tell_apart([("retroarch", lock / "system", "RetroArch"), ("retroarch", repo.dest, "RetroArch")]) @@ -684,7 +684,7 @@ class AHomeThisUserCannotOpen(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--verbose", *extra], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(home, 0o755) for name, proc in runs.items(): @@ -710,7 +710,7 @@ class AHomeThisUserCannotOpen(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--platform", "retroarch"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(home, 0o755) self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) @@ -809,7 +809,7 @@ class TheFrontendsOwnFolderClosed(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--platform", "retroarch", "--dry-run", "--no-input"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(flatpak, 0o755) self.assertNotIn("Traceback", proc.stderr) @@ -877,7 +877,7 @@ class APartlyClosedHome(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--verbose", *extra], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(closed, 0o755) refusal = (f"Could not look for setups: this user cannot open {closed} " @@ -942,7 +942,7 @@ class AnUnreadableRetroArchConfigIsSaid(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--events"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(cfg, 0o644) self.assertNotIn("Traceback", proc.stderr) @@ -1251,7 +1251,7 @@ class NotFoundWithAClosedFolder(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--platform", platform, "--dry-run", "--no-input", "--events"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(closed, 0o755) events = [json.loads(line) for line in proc.stdout.splitlines()] @@ -1329,7 +1329,7 @@ class ADetectedClosedFolderSaysWhereItCameFrom(unittest.TestCase): proc = subprocess.run( [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(lock, 0o755) self.cfg = cfg @@ -1373,7 +1373,7 @@ class OfflineWithNothingFound(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--offline", "--check", "--no-input"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) said = proc.stdout + proc.stderr self.assertEqual(proc.returncode, 1, said) self.assertNotIn("emudeck", said.lower()) diff --git a/tests/test_install_expert.py b/tests/test_install_expert.py index 419e56b3c..a69dcdc63 100644 --- a/tests/test_install_expert.py +++ b/tests/test_install_expert.py @@ -25,6 +25,8 @@ import unittest from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent +# install.py runs on 3.8, the scripts it is compared with need 3.9. +BUILDER_FLOOR = (3, 9) sys.path.insert(0, str(REPO_ROOT / "scripts")) _spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py") @@ -44,7 +46,7 @@ class RealListParity(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - if sys.version_info < (3, 9): + if sys.version_info < BUILDER_FLOOR: # The builder's floor: install.py alone keeps 3.8. raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer") import generate_pack as gp @@ -261,7 +263,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase): _copy("b.bin", b"b", slot=_slot(_claims(px68k=2), groups=("x68000",)))] self.assertEqual(self.drops(entries), set()) - @unittest.skipIf(sys.version_info < (3, 9), "slot.py needs Python 3.9 or newer") + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "slot.py needs Python 3.9 or newer") def test_random_slots_against_the_builder(self): import random @@ -293,7 +295,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase): for name in entries] self.assertEqual(self.drops(listed, reach), expected) - @unittest.skipIf(sys.version_info < (3, 9), "slot.py needs Python 3.9 or newer") + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "slot.py needs Python 3.9 or newer") def test_a_destination_two_groups_name_apart(self): """One destination a platform declares under one name and a core under another: each group looks its own name up, as the builder @@ -583,7 +585,7 @@ class ExpertRuns(Lists): self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) self.assertIn("which --source truth needs", proc.stderr) - @unittest.skipIf(sys.version_info < (3, 9), "validate_schemas.py needs Python 3.9 or newer") + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "validate_schemas.py needs Python 3.9 or newer") def test_the_schema_check_reads_a_null_truth_list(self): from unittest import mock diff --git a/tests/test_install_filesystems.py b/tests/test_install_filesystems.py index 8392dc2e4..9f6adf31c 100644 --- a/tests/test_install_filesystems.py +++ b/tests/test_install_filesystems.py @@ -38,7 +38,7 @@ class AndroidMediaScanner(unittest.TestCase): proc = subprocess.run(self.repo.command("--yes", "--no-input", *options), env={**self.repo.env(), "RETROBIOS_OS": os_name}, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) return self.repo, proc def test_an_android_install_writes_one(self): diff --git a/tests/test_install_pack.py b/tests/test_install_pack.py index 8bfffc8b6..817ed53ab 100644 --- a/tests/test_install_pack.py +++ b/tests/test_install_pack.py @@ -10,6 +10,7 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import argparse import functools import hashlib import http.server @@ -632,7 +633,7 @@ class PartSizes(unittest.TestCase): for text in ("big", "1K", "-5M"): with self.subTest(text=text), \ mock.patch("sys.stderr", io.StringIO()), \ - self.assertRaises(Exception): + self.assertRaises(argparse.ArgumentTypeError): install.parse_part_size(text) diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 3f34215b4..551e8d6b8 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -379,10 +379,8 @@ class DecliningTheSizePointsAtTheChoice(unittest.TestCase): mock.patch.object(install, "_is_terminal", return_value=True), \ mock.patch("builtins.input", lambda _prompt="": next(replies)), \ contextlib.redirect_stdout(out): - try: + with contextlib.suppress(SystemExit): install.main() - except SystemExit: - pass self.assertEqual(repo.installed(), []) return out.getvalue() @@ -1561,6 +1559,7 @@ class AnUnknownNativeNameIsRefusedBeforeAnyWork(unittest.TestCase): [sys.executable, f"scripts/{script}", "--platform", "batocera", "--system", "psxx", "--db", missing, *extra], cwd=REPO_ROOT, capture_output=True, text=True, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) self.assertIn("unknown system psxx. Close matches: psx.", proc.stderr) @@ -1572,6 +1571,7 @@ class AnUnknownNativeNameIsRefusedBeforeAnyWork(unittest.TestCase): [sys.executable, "scripts/verify.py", "--platform", "batocera", "--system", "psx", "--json"], cwd=REPO_ROOT, capture_output=True, text=True, timeout=600, + check=False, ) if "database" in proc.stderr and proc.returncode: self.skipTest("database.json is not built") diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 7b44676a5..7555d886a 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -41,6 +41,8 @@ from pathlib import Path, PurePosixPath, PureWindowsPath from unittest import mock REPO_ROOT = Path(__file__).resolve().parent.parent +# install.py runs on 3.8, the scripts it is compared with need 3.9. +BUILDER_FLOOR = (3, 9) sys.path.insert(0, str(REPO_ROOT)) sys.path.insert(0, str(REPO_ROOT / "tests")) @@ -949,6 +951,13 @@ class Widgets(unittest.TestCase): def golden_states() -> dict: """One state per screen, filled as a run fills it.""" + states = _golden_setup_states() + states.update(_golden_plan_states()) + states.update(_golden_run_states()) + return states + + +def _golden_setup_states() -> dict: states = {} states["setup"] = fresh_state() states["setup"].notes = ["ES-DE found: its BIOS files go to each emulator, not to " @@ -985,6 +994,11 @@ def golden_states() -> dict: checking.platform, checking.dest, checking.stack = "retroarch", SYSTEM_DIR, ["checking"] checking.manifest, checking.started, checking.now = MANIFEST, 10.0, 14.2 states["checking"] = checking + return states + + +def _golden_plan_states() -> dict: + states = {} states["plan"] = checked_state() done = checked_state() done.check = {**CHECK, "present": 5, "missing": 0, "wrong_hash": 0, "bytes_needed": 0, @@ -1039,6 +1053,11 @@ def golden_states() -> dict: confirm.dry = {**CHECK, "files": 1, "present": 0, "missing": 1, "wrong_hash": 0, "bytes_needed": 16384, "not_installable": 0} states["confirm"] = confirm + return states + + +def _golden_run_states() -> dict: + states = {} installing = checked_state() installing.stack.append("installing") installing.run, installing.running = "install", True @@ -2509,7 +2528,7 @@ class WorkFolders(unittest.TestCase): self.addCleanup(signal.signal, number, previous) interrupt = signal.getsignal(signal.SIGINT) - def starting(*_args, **_kwargs): + def starting(*_args, number=number, **_kwargs): os.kill(os.getpid(), number) return fresh_state(), [("fetch", "retroarch")] @@ -2521,7 +2540,7 @@ class WorkFolders(unittest.TestCase): with mock.patch.object(install, "_TuiTerminal", self.Terminal), \ mock.patch.object(install.tempfile, "mkdtemp", return_value=str(work)), \ mock.patch.object(self.Terminal, "enter", - lambda _t: entered.append(True)), \ + lambda _t, entered=entered: entered.append(True)), \ mock.patch.object(install, "tui_start", side_effect=starting), \ mock.patch.object(install, "_open_local_sources"), \ mock.patch.object(install, "_tui_fetch") as fetch, \ @@ -7597,7 +7616,7 @@ class _CardFixtures: listing = self.root / f"{plat}.json" install_list = {"manifest_version": 2, "platform": plat, "files": files} listing.write_text(json.dumps(install_list)) - if sys.version_info < (3, 9): + if sys.version_info < BUILDER_FLOOR: # generate_pack.py's context managers need Python 3.9. return listing, None, {} sys.path.insert(0, str(REPO_ROOT / "scripts")) @@ -7725,7 +7744,7 @@ class _LineModeFindings(_CardFixtures): region=["us"]) self.assertEqual(code, 0, text) - @unittest.skipIf(sys.version_info < (3, 9), + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "generate_pack.py's context managers need Python 3.9") def test_a_pack_names_its_list_only_when_that_list_records_it(self): """A MinUI pack sent --core to install/minui.json, @@ -9225,7 +9244,7 @@ class PacksWordingAndDocs(unittest.TestCase): # a pack's own list records its systems. - @unittest.skipIf(sys.version_info < (3, 9), + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "generate_pack.py's context managers need Python 3.9") def test_a_pack_records_the_systems_of_its_files(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) @@ -14673,7 +14692,7 @@ class ProvenCardsAndCounts(unittest.TestCase): # Root cause 6: the pages say what the installer shows. - @unittest.skipIf(sys.version_info < (3, 9), + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "the site generator needs Python 3.9") def test_which_pack_names_the_first_screen(self): """Which-pack said the command opens a screen @@ -16148,7 +16167,7 @@ class EmulatorChoiceMatchesTheEmulatorPack(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - if sys.version_info < (3, 9): + if sys.version_info < BUILDER_FLOOR: # The builder's floor: install.py alone keeps 3.8. raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer") sys.path.insert(0, str(REPO_ROOT / "scripts")) diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index 80656f21e..c78e79e98 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -23,12 +23,13 @@ import urllib.error from pathlib import Path from unittest import mock -REPO_ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(REPO_ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) -import common # noqa: E402 +import common import largefiles -import check_release_assets # noqa: E402 +import check_release_assets + +REPO_ROOT = Path(__file__).resolve().parent.parent PAYLOAD_A = b"A" * (256 * 1024) PAYLOAD_B = b"B" * (256 * 1024) diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index 77e16d58f..3e698b321 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -273,6 +273,7 @@ class LauncherGapTest(unittest.TestCase): "--platforms-dir", self.platforms_dir, "--emulators-dir", self.emulators_dir, "--db", str(db_path), "--json"], cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) report = json.loads(result.stdout) diff --git a/tests/test_mame_ref_audit.py b/tests/test_mame_ref_audit.py index 7f6113739..210381ab8 100644 --- a/tests/test_mame_ref_audit.py +++ b/tests/test_mame_ref_audit.py @@ -14,12 +14,13 @@ import tempfile import unittest from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import mame_ref_audit from mame_ref_audit import declares +ROOT = Path(__file__).resolve().parent.parent + DRIVER = [ "// a driver file", diff --git a/tests/test_manifest_entry.py b/tests/test_manifest_entry.py index ad18dfe2d..cf6022218 100644 --- a/tests/test_manifest_entry.py +++ b/tests/test_manifest_entry.py @@ -68,8 +68,11 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase): with mock.patch.object(gp, "compute_hashes", return_value=hashes): gp._manifest_core_entries( [extra], {}, self.db, str(REPO_ROOT / "bios"), "", str(REPO_ROOT), - {}, True, set(), False, set(), set(), set(), files, {}, - record, pack_only, SelectionIndex.build({}, {}, {}, []), + {}, True, + region_drops=set(), case_insensitive=False, seen_destinations=set(), + seen_lower=set(), seen_parents=set(), manifest_files=files, + omitted_by_destination={}, record_omission=record, + pack_only_sizes=pack_only, selection=SelectionIndex.build({}, {}, {}, []), ) return files, omitted, pack_only diff --git a/tests/test_measurements.py b/tests/test_measurements.py index c3f7ac589..61fb94f04 100644 --- a/tests/test_measurements.py +++ b/tests/test_measurements.py @@ -84,7 +84,7 @@ def full_record(emulator: str, subject: str, when: str, kind: str = "check", } if kind == "check": groups: dict[str, list[str]] = {} - for variant, value in zip(variants, values): + for variant, _value in zip(variants, values): key = json.dumps(variant["repetitions"][0]["observables"][observable], sort_keys=True) groups.setdefault(key, []).append(variant["label"]) record["check"] = { diff --git a/tests/test_no_case_collisions.py b/tests/test_no_case_collisions.py index a724cfca2..027b4df1b 100644 --- a/tests/test_no_case_collisions.py +++ b/tests/test_no_case_collisions.py @@ -42,6 +42,7 @@ class TestNoCaseCollisions(unittest.TestCase): listed = subprocess.run( ["git", "ls-files", "-z", "--", "bios"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) if listed.returncode != 0 or not listed.stdout: self.skipTest("not a git checkout with bios/") diff --git a/tests/test_optional_dependencies.py b/tests/test_optional_dependencies.py index be912f07f..241d0d07a 100644 --- a/tests/test_optional_dependencies.py +++ b/tests/test_optional_dependencies.py @@ -9,10 +9,12 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import ast import re import subprocess import sys import unittest +from collections.abc import Iterator from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent @@ -69,6 +71,47 @@ MAINTENANCE_TOOLS = { } +def _is_type_checking(test: ast.expr) -> bool: + if isinstance(test, ast.Name): + return test.id == "TYPE_CHECKING" + return (isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING" + and isinstance(test.value, ast.Name) and test.value.id == "typing") + + +def _runtime_nodes(node: ast.AST) -> Iterator[ast.AST]: + """Every node that can run: the body of an `if TYPE_CHECKING:` never does.""" + yield node + for child in ast.iter_child_nodes(node): + if isinstance(child, ast.If) and _is_type_checking(child.test): + for branch in child.orelse: + yield from _runtime_nodes(branch) + continue + yield from _runtime_nodes(child) + + +def _foreign_imports(source: str, file_name: str, local: set[str]) -> list[str]: + """The top-level packages a script imports at run time beyond the + standard library, pyyaml and the repository's own modules.""" + allowed = {"yaml"} + found = [] + for node in _runtime_nodes(ast.parse(source)): + if isinstance(node, ast.Import): + names = [a.name.split(".")[0] for a in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + names = [node.module.split(".")[0]] + else: + continue + for name in names: + if name in sys.stdlib_module_names or name in local or name in allowed: + continue + if name == "jsonschema" and file_name == "validate_schemas.py": + continue + if MAINTENANCE_TOOLS.get(file_name) == name: + continue + found.append(name) + return found + + class ScriptsNeedOnlyPyyaml(unittest.TestCase): """The build scripts need the standard library and pyyaml. jsonschema is validate_schemas.py's alone. CI installs jsonschema with its whole tree @@ -76,8 +119,6 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase): there and fail for a contributor following the documented setup.""" def test_no_script_imports_another_package(self): - import ast - scripts = Path(__file__).resolve().parents[1] / "scripts" local = {p.stem for p in scripts.rglob("*.py")} | { p.name for p in scripts.iterdir() if p.is_dir() @@ -85,26 +126,35 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase): # install.py is the repository's own single file, stdlib only (its # tests hold it to that): generate_games_index reads its narrowing. local.add("install") - allowed = {"yaml"} - found = [] - for path in sorted(scripts.rglob("*.py")): - for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): - if isinstance(node, ast.Import): - names = [a.name.split(".")[0] for a in node.names] - elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: - names = [node.module.split(".")[0]] - else: - continue - for name in names: - if name in sys.stdlib_module_names or name in local or name in allowed: - continue - if name == "jsonschema" and path.name == "validate_schemas.py": - continue - if MAINTENANCE_TOOLS.get(path.name) == name: - continue - found.append(f"{path.relative_to(scripts)}: {name}") + found = [ + f"{path.relative_to(scripts)}: {name}" + for path in sorted(scripts.rglob("*.py")) + for name in _foreign_imports(path.read_text(encoding="utf-8"), path.name, local) + ] self.assertEqual(found, []) + def test_an_import_only_a_type_checker_runs_is_no_dependency(self): + guarded = ( + "from typing import TYPE_CHECKING\n" + "import typing\n" + "if TYPE_CHECKING:\n" + " from typing_extensions import Unpack\n" + "if typing.TYPE_CHECKING:\n" + " import typing_extensions\n" + ) + self.assertEqual(_foreign_imports(guarded, "x.py", set()), []) + self.assertEqual(_foreign_imports("import typing_extensions\n", "x.py", set()), + ["typing_extensions"]) + # The else branch of the guard runs: it stays a dependency. + branch = ( + "from typing import TYPE_CHECKING\n" + "if TYPE_CHECKING:\n" + " pass\n" + "else:\n" + " import typing_extensions\n" + ) + self.assertEqual(_foreign_imports(branch, "x.py", set()), ["typing_extensions"]) + class TheDownloaderRunsWithoutPyyaml(unittest.TestCase): """download.py is the documented Windows downloader, "stdlib only". It diff --git a/tests/test_pack_failures.py b/tests/test_pack_failures.py index 3296c9edc..d335377c7 100644 --- a/tests/test_pack_failures.py +++ b/tests/test_pack_failures.py @@ -47,11 +47,11 @@ class FailedPlatformFailsTheRun(unittest.TestCase): def test_pack_mode(self): with mock.patch.object(gp, "generate_pack", _boom), \ - mock.patch.object(gp, "verify_and_finalize_packs", return_value=True): - with self.assertRaises(SystemExit) as ctx: - gp._run_platform_packs( - self._args(), [(["retropie"], "retropie")], {}, {}, {}, {}, {}, None - ) + mock.patch.object(gp, "verify_and_finalize_packs", return_value=True), \ + self.assertRaises(SystemExit) as ctx: + gp._run_platform_packs( + self._args(), [(["retropie"], "retropie")], {}, {}, {}, {}, {}, None + ) self.assertEqual(ctx.exception.code, 1) def test_manifest_mode(self): diff --git a/tests/test_pack_grouping.py b/tests/test_pack_grouping.py index 5a45a6740..f7cf06114 100644 --- a/tests/test_pack_grouping.py +++ b/tests/test_pack_grouping.py @@ -34,7 +34,8 @@ class SlotPassReadsTheRegionGrouping(unittest.TestCase): config = load_platform_config("retroarch", "platforms") drops, _fallbacks, _undecided = gp._select_variants( config, config["systems"], "emulators", db, - config.get("base_destination", ""), profiles, None, "full", None, True, + config.get("base_destination", ""), profiles, None, "full", + regions=None, one_per_slot=True, ) names = {os.path.basename(d) for d in drops} for name in ("jp_mcd1_9111.bin", "eu_mcd1_9210.bin"): @@ -68,7 +69,7 @@ class VariantGroupSpansSystems(unittest.TestCase): drops, _fallbacks, _undecided = gp._select_variants( config, config["systems"], "emulators", db, config.get("base_destination", ""), profiles, None, "full", - region_mod.parse_requested("us"), False, + regions=region_mod.parse_requested("us"), one_per_slot=False, ) names = {os.path.basename(d) for d in drops} for name in ("jp_mcd1_9111.bin", "eu_mcd2_9306.bin"): diff --git a/tests/test_pack_integrity.py b/tests/test_pack_integrity.py index a7e7c704e..0fa857329 100644 --- a/tests/test_pack_integrity.py +++ b/tests/test_pack_integrity.py @@ -92,6 +92,7 @@ class PackIntegrityTest(unittest.TestCase): capture_output=True, text=True, cwd=REPO_ROOT, + check=False, ) if result.returncode == 0: return diff --git a/tests/test_pin_build.py b/tests/test_pin_build.py index 6b27c186f..3a15fa91e 100644 --- a/tests/test_pin_build.py +++ b/tests/test_pin_build.py @@ -124,6 +124,15 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase): self.assertEqual(row.items, ["raine"]) +def _names_the_pin(value: str, profile: dict, source: str, pins: set, versions: set) -> bool: + if profile.get("pin_follows"): + # A build of the branch tip names the repository it + # clones, at no revision: RetroPie's advmame. + return value.split()[-1].rstrip("/").removesuffix(".git") == source + token = value.split()[-1].rsplit("/", 1)[-1].removesuffix(".tar.gz") + return value in pins or any(token in v or v in value for v in versions) + + class EveryBuildReferenceNamesThePin(unittest.TestCase): """Reads the repository: a pin_build value is what the platform builds, so it is the profile's source_commit or names its core_version, and the @@ -147,23 +156,20 @@ class EveryBuildReferenceNamesThePin(unittest.TestCase): source = str(profile.get("source") or "").rstrip("/").removesuffix(".git") - def names_it(value: str) -> bool: - if profile.get("pin_follows"): - # A build of the branch tip names the repository it - # clones, at no revision: RetroPie's advmame. - return value.split()[-1].rstrip("/").removesuffix(".git") == source - token = value.split()[-1].rsplit("/", 1)[-1].removesuffix(".tar.gz") - return value in pins or any(token in v or v in value for v in versions) - # A reference that only dates a config_reads entry names the build # the platform reads that file at, not this profile's pin. justifies_pin = profile.get("pin_frozen") or profile.get("pin_follows") - if justifies_pin and not any(names_it(str(r["value"])) for r in references): + if justifies_pin and not any( + _names_the_pin(str(r["value"]), profile, source, pins, versions) + for r in references + ): disagree.append(name) - for reference in references: - if not cf.pin_build_revision(reference, REPO_ROOT / "platforms"): - disagree.append(f"{name}: {reference['platform']} is not read from " - f"{reference['repo']}") + disagree.extend( + f"{name}: {reference['platform']} is not read from " + f"{reference['repo']}" + for reference in references + if not cf.pin_build_revision(reference, REPO_ROOT / "platforms") + ) self.assertEqual(disagree, []) diff --git a/tests/test_profile_paths.py b/tests/test_profile_paths.py index eea16aea9..fd19be8f4 100644 --- a/tests/test_profile_paths.py +++ b/tests/test_profile_paths.py @@ -59,9 +59,11 @@ class StandaloneDestinations(unittest.TestCase): if not isinstance(entry, dict): continue dest = _destination(entry) - for folder in FRONTEND_FOLDERS: - if dest.startswith(folder) and folder not in allowed: - wrong.append(f"{name}: {entry.get('name')} at {dest}") + wrong.extend( + f"{name}: {entry.get('name')} at {dest}" + for folder in FRONTEND_FOLDERS + if dest.startswith(folder) and folder not in allowed + ) self.assertEqual(wrong, []) def test_every_allowed_folder_is_read(self): diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index cb6a005a2..cd2cde195 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -5099,9 +5099,10 @@ class TestRateLimitEndsOneProfile(unittest.TestCase): return_value={"cemu": {}, "after": {}}), \ mock.patch.object(profile_sync, "_check_quota"), \ mock.patch.object(profile_sync, "build_report", side_effect=build), \ - contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - with self.assertRaises(SystemExit) as caught: - profile_sync.main() + contextlib.redirect_stdout(out), \ + contextlib.redirect_stderr(err), \ + self.assertRaises(SystemExit) as caught: + profile_sync.main() finally: sys.argv = saved self.assertEqual(caught.exception.code, 1) @@ -5316,9 +5317,10 @@ class TestOutputModesApplyTheirFlags(unittest.TestCase): return_value={"clean": {}, "drift": {}}), \ mock.patch.object(profile_sync, "_check_quota"), \ mock.patch.object(profile_sync, "build_report", side_effect=build), \ - contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as caught: - profile_sync.main() + contextlib.redirect_stdout(out), \ + contextlib.redirect_stderr(io.StringIO()), \ + self.assertRaises(SystemExit) as caught: + profile_sync.main() finally: sys.argv = saved self.assertEqual(caught.exception.code, 1) diff --git a/tests/test_prose_style.py b/tests/test_prose_style.py index b31e1dc36..715580712 100644 --- a/tests/test_prose_style.py +++ b/tests/test_prose_style.py @@ -368,8 +368,10 @@ class NoClauseSemicolons(unittest.TestCase): offenders = [] for path in files: text = path.read_text(encoding="utf-8") - for line in _semicolons(extract(text)): - offenders.append(f"{path.relative_to(ROOT)}: {line[:100]}") + offenders.extend( + f"{path.relative_to(ROOT)}: {line[:100]}" + for line in _semicolons(extract(text)) + ) self.assertEqual(offenders, [], "\n".join(offenders[:40])) def test_markdown(self): @@ -405,9 +407,11 @@ class NoClauseSemicolons(unittest.TestCase): offenders = [] for page in sorted((ROOT / "wiki").glob("*.md")): text = FENCED.sub("", page.read_text(encoding="utf-8")) - for title in re.findall(r"(?m)^#{1,4} (.+)$", text): - if _sentence_case(title) != title: - offenders.append(f"{page.name}: {title}") + offenders.extend( + f"{page.name}: {title}" + for title in re.findall(r"(?m)^#{1,4} (.+)$", text) + if _sentence_case(title) != title + ) self.assertEqual(offenders, [], "\n".join(offenders)) def test_yaml_prose_and_comments(self): @@ -441,8 +445,10 @@ class NoClauseSemicolons(unittest.TestCase): offenders = [] for path in sorted((ROOT / "schemas").glob("*.json")): text = path.read_text(encoding="utf-8") - for line in _semicolons(text) + GLYPHS.findall(text): - offenders.append(f"{path.relative_to(ROOT)}: {line[:100]}") + offenders.extend( + f"{path.relative_to(ROOT)}: {line[:100]}" + for line in _semicolons(text) + GLYPHS.findall(text) + ) self.assertEqual(offenders, [], "\n".join(offenders)) diff --git a/tests/test_region.py b/tests/test_region.py index bb3303d4a..280ed9675 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -571,11 +571,11 @@ class TestProfileConformance(unittest.TestCase): f"{os.path.basename(path)}: {f.get('name')} not a list" ) continue - for value in raw: - if value not in region.REGIONS: - offenders.append( - f"{os.path.basename(path)}: {f.get('name')} -> {value!r}" - ) + offenders.extend( + f"{os.path.basename(path)}: {f.get('name')} -> {value!r}" + for value in raw + if value not in region.REGIONS + ) self.assertEqual(offenders, [], "\n".join(offenders)) def test_index_builds_over_every_repo_profile(self): diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index 87a8cb5b0..16b4c5ef8 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -209,6 +209,7 @@ class APlatformWithoutAPackFailsNoCheck(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", "--output-dir", directory], capture_output=True, text=True, cwd=REPO_ROOT, timeout=600, + check=False, ) swept = {line.split(":")[0].strip() for line in proc.stdout.splitlines() if "SKIP (no pack in" in line} diff --git a/tests/test_romfolders_es.py b/tests/test_romfolders_es.py index bb75a8576..b2b3abb99 100644 --- a/tests/test_romfolders_es.py +++ b/tests/test_romfolders_es.py @@ -16,8 +16,7 @@ import sys import unittest from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) from romfolders import setup_paths, split_refs from scraper.romfolders import ( @@ -30,6 +29,8 @@ from scraper.romfolders import ( from scraper.romfolders.__main__ import dump_setup from scraper.romfolders.es import _module_valid +ROOT = Path(__file__).resolve().parent.parent + FIXTURES = ROOT / "tests" / "fixtures" / "romfolders" / "es" ROMFOLDERS = ROOT / "platforms" / "romfolders" ES_SETUPS = ( diff --git a/tests/test_shipped_content.py b/tests/test_shipped_content.py index 1e368df9a..860edc874 100644 --- a/tests/test_shipped_content.py +++ b/tests/test_shipped_content.py @@ -17,6 +17,7 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import contextlib import hashlib import json import os @@ -116,10 +117,8 @@ class ShippedFilesSatisfyTheirDeclaration(unittest.TestCase): # md5_composite computes and what the resolver matches on. # A variant carries its hash after the extension # (cdimono1.zip.e6714b3d), so the name is not the test. - try: + with contextlib.suppress(zipfile.BadZipFile, OSError): digests["md5"].append(common.md5_composite(str(blob_path))) - except (zipfile.BadZipFile, OSError): - pass # A declared MD5 can be shorter than 32 characters: compare by prefix. satisfied = any( all( diff --git a/tests/test_site_console_folders.py b/tests/test_site_console_folders.py index 9d3a895ce..8a207d6e7 100644 --- a/tests/test_site_console_folders.py +++ b/tests/test_site_console_folders.py @@ -47,6 +47,7 @@ class OneFolderPerConsole(unittest.TestCase): listed = subprocess.run( ["git", "ls-files", "-z", "--", "bios"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) if listed.returncode != 0 or not listed.stdout: self.skipTest("not a git checkout with bios/") diff --git a/tests/test_site_content_data.py b/tests/test_site_content_data.py index 8345a0a54..0f0b684e2 100644 --- a/tests/test_site_content_data.py +++ b/tests/test_site_content_data.py @@ -135,9 +135,11 @@ class NoPlatformProseInScripts(unittest.TestCase): scripts = REPO_ROOT / "scripts" for path in [scripts / name for name in _RENDERERS] + sorted(scripts.glob("site*.py")): for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): - for match in _PLATFORM_BRANCH.finditer(line): - if (match.group(1) or match.group(2)) in platforms: - found.append(f"{path.name}:{number}: {line.strip()}") + found.extend( + f"{path.name}:{number}: {line.strip()}" + for match in _PLATFORM_BRANCH.finditer(line) + if (match.group(1) or match.group(2)) in platforms + ) self.assertEqual(found, [], "a guide field says what one platform needs") diff --git a/tests/test_site_copy.py b/tests/test_site_copy.py index 9a316fab5..dfd08dac5 100644 --- a/tests/test_site_copy.py +++ b/tests/test_site_copy.py @@ -151,6 +151,164 @@ def guide_part(markdown: str) -> str: return markdown[: match.start()] if match else markdown +class _PageParser: + """The state parse() carries from one line to the next.""" + + def __init__(self) -> None: + self.page = Page() + self.seen_words = 0 + self.details = 0 # depth of collapsed blocks + self.tab = 0 # the tab of a group being read, 0 outside a group + self.fence: str | None = None + self.current: list[str] = [] + self.kind = "paragraph" + self.run = 0 + + def flush(self) -> None: + page = self.page + if self.current: + body = strip_inline(" ".join(self.current)) + if WORD.search(body): + kind = self.kind + term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else "" + block = Block(kind, body, self.details > 0, term, self.tab > 1) + page.blocks.append(block) + if (page.before_action is None and not block.collapsed + and not block.hidden and kind not in ("table", "heading")): + self.seen_words += count_words(body) + self.current = [] + if self.kind in ("item", "definition", "heading"): + self.kind = "paragraph" + + def act(self) -> None: + self.flush() + if self.page.before_action is None: + self.page.before_action = self.seen_words + + def end_run(self) -> None: + if self.run: + self.page.list_runs.append(self.run) + self.run = 0 + + def feed(self, raw: str) -> None: + line = raw.rstrip() + stripped = line.strip() + indent = len(line) - len(line.lstrip()) + if self.fence: + if stripped.startswith(self.fence): + self.fence = None + return + if self._markup(stripped): + return + if stripped.startswith("#"): + self._heading(stripped) + return + if stripped.startswith("|"): + self._table_row(stripped) + return + self._prose(stripped, indent) + + def _markup(self, stripped: str) -> bool: + """Fences, blank lines and HTML: True when the line is consumed.""" + if stripped.startswith(("```", "~~~")): + self.fence = stripped[:3] + if self.tab < 2: + self.act() + return True + if not stripped: + self.flush() + return True + if stripped.startswith("import ") and stripped.endswith(";"): + return True + if stripped.startswith(":::"): + self.flush() + return True + if self._container(stripped): + return True + if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith( + (" bool: + """Collapsed blocks and tab groups: True when the line is consumed.""" + if stripped.startswith(""): + self.flush() + self.details = max(0, self.details - 1) + return True + if stripped.startswith(""): + self.flush() + self.tab = 0 + return True + return False + + def _heading(self, stripped: str) -> None: + self.flush() + self.end_run() + self.kind = "heading" + self.current = [re.sub(r"\s*\{[^}]*\}\s*$", "", stripped.lstrip("#").strip())] + self.flush() + self.kind = "paragraph" + + def _table_row(self, stripped: str) -> None: + if self.kind != "table": + self.flush() + self.kind = "table" + if not re.fullmatch(r"\|[\s:|-]+\|?", stripped): + self.current.append(stripped.replace("|", " ")) + + def _prose(self, stripped: str, indent: int) -> None: + if self.kind == "table": + self.flush() + self.kind = "paragraph" + item = re.match(r"(?:[-*+]|\d+\.)\s+(.*)", stripped) + definition = re.match(r":\s+(.*)", stripped) + if item: + self.flush() + self.kind = "item" + self.run += 1 + self.current = [item.group(1)] + return + if definition: + self.flush() + page = self.page + if page.blocks and page.blocks[-1].kind == "paragraph": + page.blocks[-1].kind = "term" + self.kind = "definition" + self.current = [definition.group(1)] + return + if self.kind == "item" and indent == 0: + self.flush() + self.kind = "paragraph" + if self.kind == "paragraph": + self.end_run() + if not self.current and self.kind in ("item", "definition") and indent == 0: + self.kind = "paragraph" + self.current.append(stripped) + + def finish(self) -> Page: + self.flush() + if self.run: + self.page.list_runs.append(self.run) + return self.page + + def parse(markdown: str) -> Page: """Blocks of prose a reader sees, code and HTML left out. @@ -161,131 +319,10 @@ def parse(markdown: str) -> Page: text = guide_part(markdown) text = re.sub(r"", "", text, flags=re.S) text = re.sub(r"", "", text, flags=re.S) - page = Page() - seen_words = 0 - details = 0 # depth of collapsed blocks - tab = 0 # the tab of a group being read, 0 outside a group - fence: str | None = None - current: list[str] = [] - kind = "paragraph" - run = 0 - - def flush() -> None: - nonlocal current, seen_words, kind - if current: - body = strip_inline(" ".join(current)) - if WORD.search(body): - term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else "" - block = Block(kind, body, details > 0, term, tab > 1) - page.blocks.append(block) - if (page.before_action is None and not block.collapsed - and not block.hidden and kind not in ("table", "heading")): - seen_words += count_words(body) - current = [] - if kind in ("item", "definition", "heading"): - kind = "paragraph" - - def act() -> None: - flush() - if page.before_action is None: - page.before_action = seen_words - + parser = _PageParser() for raw in text.splitlines(): - line = raw.rstrip() - stripped = line.strip() - indent = len(line) - len(line.lstrip()) - if fence: - if stripped.startswith(fence): - fence = None - continue - if stripped.startswith(("```", "~~~")): - fence = stripped[:3] - if tab < 2: - act() - continue - if not stripped: - flush() - continue - if stripped.startswith("import ") and stripped.endswith(";"): - continue - if stripped.startswith(":::"): - flush() - continue - if stripped.startswith(""): - flush() - details = max(0, details - 1) - continue - if stripped.startswith(""): - flush() - tab = 0 - continue - if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith( - (" list[str]: @@ -298,9 +335,11 @@ def banned(block: Block, level: str) -> list[str]: return [] for sentence in split_sentences(text) or [text]: lower = sentence.lower() - for phrase in FILLER: - if re.search(rf"(? None: diff --git a/tests/test_site_nav.py b/tests/test_site_nav.py index cda3ad846..a2e9f2816 100644 --- a/tests/test_site_nav.py +++ b/tests/test_site_nav.py @@ -657,11 +657,13 @@ class BuiltSearchAndCrumbs(unittest.TestCase): for path in (DIST / "systems").rglob("index.html"): # The search fields are attributes on empty spans. The title # meta reads the visible h1. - for match in re.finditer(r'<(\w+)[^>]*data-pagefind-meta="(?:files|aliases|devices|consoles|terms):' - r'[^>]*>([^<]*)', - path.read_text(encoding="utf-8")): - if match[2].strip(): - texts.append(str(path.relative_to(DIST))) + texts.extend( + str(path.relative_to(DIST)) + for match in re.finditer(r'<(\w+)[^>]*data-pagefind-meta="(?:files|aliases|devices|consoles|terms):' + r'[^>]*>([^<]*)', + path.read_text(encoding="utf-8")) + if match[2].strip() + ) self.assertEqual(texts, []) def test_a_setups_console_page_names_its_setup(self) -> None: diff --git a/tests/test_site_system_sections.py b/tests/test_site_system_sections.py index 3d1cbe1e2..df5a09e6c 100644 --- a/tests/test_site_system_sections.py +++ b/tests/test_site_system_sections.py @@ -20,6 +20,7 @@ import json import os import sys import unittest +from collections.abc import Iterable from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] @@ -89,6 +90,57 @@ def _archives_held(fe: dict, db: dict) -> set[str]: return held +def _entries_by_system(platforms: list[dict], profiles: dict) -> dict[str, list[dict]]: + entries: dict[str, list[dict]] = {} + for config in platforms: + for sys_id, system in config.get("systems", {}).items(): + entries.setdefault(sys_id, []).extend(system.get("files") or []) + for profile in profiles.values(): + systems = [str(s) for s in profile.get("systems") or []] + for fe in profile.get("files") or []: + if not isinstance(fe, dict): + continue + owners = {str(fe["system"])} if fe.get("system") else set() + owners.update(str(s) for s in fe.get("systems") or []) + if not owners and len(systems) == 1: + owners = set(systems) + for owner in owners: + entries.setdefault(owner, []).append(fe) + return entries + + +def _held_sections( + ids: Iterable[str], entries: dict[str, list[dict]], board_sections: dict, db: dict +) -> dict[str, set[tuple[str, str]]]: + """Id -> the (manufacturer, console) sections holding its files.""" + from common import resolve_local_file + + # Where each content has a card. + places: dict[str, set[tuple[str, str, str]]] = {} + for mfr, consoles in board_sections.items(): + for console, files in consoles.items(): + for f in files: + places.setdefault(f["sha1"], set()).add((mfr, console, f["name"])) + by_path = {entry.get("path"): sha1 for sha1, entry in db["files"].items()} + held: dict[str, set[tuple[str, str]]] = {} + for sys_id in ids: + sections: set[tuple[str, str]] = set() + for fe in entries.get(sys_id, []): + if fe.get("category") == "bios_zip": + for sha1 in _archives_held(fe, db): + sections.update((m, c) for m, c, _ in places.get(sha1, set())) + continue + local, status = resolve_local_file(fe, db) + if not _accepts(fe, local, status): + continue + sha1 = by_path.get(local) + if sha1 is not None: + sections.update((m, c) for m, c, _ in places.get(sha1, set())) + if sections: + held[sys_id] = sections + return held + + @unittest.skipUnless((REPO_ROOT / "database.json").exists(), "database.json is not built") class SystemLinks(unittest.TestCase): @@ -101,7 +153,6 @@ class SystemLinks(unittest.TestCase): list_registered_platforms, load_emulator_profiles, load_platform_config, - resolve_local_file, ) from generate_site import _group_by_manufacturer, arcade_board_sections @@ -124,46 +175,9 @@ class SystemLinks(unittest.TestCase): ] cls.ids = siterender.system_ids(profiles, platforms) - entries: dict[str, list[dict]] = {} - for config in platforms: - for sys_id, system in config.get("systems", {}).items(): - entries.setdefault(sys_id, []).extend(system.get("files") or []) - for profile in profiles.values(): - systems = [str(s) for s in profile.get("systems") or []] - for fe in profile.get("files") or []: - if not isinstance(fe, dict): - continue - owners = {str(fe["system"])} if fe.get("system") else set() - owners.update(str(s) for s in fe.get("systems") or []) - if not owners and len(systems) == 1: - owners = set(systems) - for owner in owners: - entries.setdefault(owner, []).append(fe) - - # Where each content has a card. - places: dict[str, set[tuple[str, str, str]]] = {} - for mfr, consoles in cls.sections.items(): - for console, files in consoles.items(): - for f in files: - places.setdefault(f["sha1"], set()).add((mfr, console, f["name"])) - by_path = {entry.get("path"): sha1 for sha1, entry in db["files"].items()} - # Id -> the (manufacturer, console) sections holding its files. - cls.held: dict[str, set[tuple[str, str]]] = {} - for sys_id in cls.ids: - sections: set[tuple[str, str]] = set() - for fe in entries.get(sys_id, []): - if fe.get("category") == "bios_zip": - for sha1 in _archives_held(fe, db): - sections.update((m, c) for m, c, _ in places.get(sha1, set())) - continue - local, status = resolve_local_file(fe, db) - if not _accepts(fe, local, status): - continue - sha1 = by_path.get(local) - if sha1 is not None: - sections.update((m, c) for m, c, _ in places.get(sha1, set())) - if sections: - cls.held[sys_id] = sections + entries = _entries_by_system(platforms, profiles) + cls.held: dict[str, set[tuple[str, str]]] = _held_sections( + cls.ids, entries, cls.sections, db) finally: os.chdir(previous) diff --git a/tests/test_system_pack_parity.py b/tests/test_system_pack_parity.py index 289c3fe7e..7bdad8fb4 100644 --- a/tests/test_system_pack_parity.py +++ b/tests/test_system_pack_parity.py @@ -28,6 +28,7 @@ def _run(*argv: str) -> str: result = subprocess.run( [sys.executable, *argv], cwd=REPO_ROOT, capture_output=True, text=True, timeout=1800, + check=False, ) if result.returncode != 0: raise AssertionError(result.stdout + result.stderr) diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index 08af24ae4..4ffff0d77 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -266,7 +266,7 @@ class AMissingBiosDirIsRefused(unittest.TestCase): def _scripts_taking(flag: str) -> list[Path]: - pattern = re.compile(r'add_argument\(\s*"%s"' % re.escape(flag)) + pattern = re.compile(rf'add_argument\(\s*"{re.escape(flag)}"') return [ path for path in sorted((REPO_ROOT / "scripts").glob("*.py")) + sorted((REPO_ROOT / "scripts" / "scraper").glob("*.py")) @@ -734,12 +734,14 @@ class ListingsKeepTheirColumns(unittest.TestCase): listing = subprocess.run( [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", "--list-systems"], cwd=REPO_ROOT, capture_output=True, text=True, timeout=300, + check=False, ).stdout.splitlines() starts = {line.index("[") for line in listing if "[" in line} self.assertEqual(len(starts), 1, listing[:5]) emulators = subprocess.run( [sys.executable, "scripts/verify.py", "--list-emulators"], cwd=REPO_ROOT, capture_output=True, text=True, timeout=300, + check=False, ).stdout.splitlines() ends = {line.index("]") + 1 for line in emulators if "]" in line} tails = {len(line) - len(line[line.index("]") + 1:].lstrip()) diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 3a7a203eb..9b74162f4 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -33,6 +33,57 @@ def _refuse(*_args, **_kwargs): raise urllib.error.HTTPError("https://api.github.com/x", 403, "rate limited", {}, None) +class _Body: + def __init__(self, body: str | bytes): + self.body = body.encode() if isinstance(body, str) else body + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return self.body + + +def _serve_batocera(boards: list[str], refuse_board: bool): + def urlopen(request, *_a, **_k): + url = request.full_url + if "/tags" in url: + return _Body(b'[{"name": "batocera-43"}]') + if "/contents/configs" in url: + return _Body(json.dumps([{"name": b} for b in boards]).encode()) + if "/contents/buildroot" in url: + return _Body(b'{"sha": "0123abc"}') + if url.endswith("x86_wow64.board"): + # Builds the 32-bit Wine package, not an image. + return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86=y\n") + if url.endswith(".board"): + if refuse_board: + _refuse() + return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86_64=y\n" + b"BR2_PACKAGE_BATOCERA_SYSTEM=y\n") + if "/git/trees/" in url: + return _Body(b'{"tree": [], "truncated": false}') + if url.endswith("retroarch.mk"): + return _Body(b"RETROARCH_CONF_OPTS = --enable-networking\n") + if url.startswith("https://raw.githubusercontent.com/") and url.count("/") == 6: + return _Body(b'source "$BR2_EXTERNAL_BATOCERA_PATH/' + b'package/batocera/core/batocera-system/Config.in"\n') + if url.endswith("Config.in"): + return _Body(b"config BR2_PACKAGE_BATOCERA_SYSTEM\n" + b"\tselect BR2_PACKAGE_MGBA\n\n" + b"config BR2_TARGET_BATOCERA_IMAGES\n\tstring \"x\"\n" + b"\tdefault \"x86_64\" if BR2_PACKAGE_BATOCERA_TARGET_X86_64\n") + return _Body( + b"gba:\n emulators:\n libretro:\n" + b" mgba: {requireAnyOf: [BR2_PACKAGE_MGBA]}\n" + ) + + return urlopen + + class FailedRequestsStopTheScrape(unittest.TestCase): def test_every_scraper_raises(self): for module in ( @@ -66,68 +117,18 @@ class FailedRequestsStopTheScrape(unittest.TestCase): def test_batocera_needs_its_boards(self): """No board listed, or one board unreadable, used to print a warning and write the targets file without those boards.""" - - class _Body: - def __init__(self, body: bytes): - self.body = body - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def read(self): - return self.body - - def serve(boards: list[str], refuse_board: bool): - def urlopen(request, *_a, **_k): - url = request.full_url - if "/tags" in url: - return _Body(b'[{"name": "batocera-43"}]') - if "/contents/configs" in url: - return _Body(json.dumps([{"name": b} for b in boards]).encode()) - if "/contents/buildroot" in url: - return _Body(b'{"sha": "0123abc"}') - if url.endswith("x86_wow64.board"): - # Builds the 32-bit Wine package, not an image. - return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86=y\n") - if url.endswith(".board"): - if refuse_board: - _refuse() - return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86_64=y\n" - b"BR2_PACKAGE_BATOCERA_SYSTEM=y\n") - if "/git/trees/" in url: - return _Body(b'{"tree": [], "truncated": false}') - if url.endswith("retroarch.mk"): - return _Body(b"RETROARCH_CONF_OPTS = --enable-networking\n") - if url.startswith("https://raw.githubusercontent.com/") and url.count("/") == 6: - return _Body(b'source "$BR2_EXTERNAL_BATOCERA_PATH/' - b'package/batocera/core/batocera-system/Config.in"\n') - if url.endswith("Config.in"): - return _Body(b"config BR2_PACKAGE_BATOCERA_SYSTEM\n" - b"\tselect BR2_PACKAGE_MGBA\n\n" - b"config BR2_TARGET_BATOCERA_IMAGES\n\tstring \"x\"\n" - b"\tdefault \"x86_64\" if BR2_PACKAGE_BATOCERA_TARGET_X86_64\n") - return _Body( - b"gba:\n emulators:\n libretro:\n" - b" mgba: {requireAnyOf: [BR2_PACKAGE_MGBA]}\n" - ) - - return urlopen - for boards, refuse_board in (([], False), (["batocera-x86_64.board"], True)): with self.subTest(boards=boards), mock.patch.object( batocera_targets_scraper.urllib.request, "urlopen", - serve(boards, refuse_board), + _serve_batocera(boards, refuse_board), ), self.assertRaises(RuntimeError): batocera_targets_scraper.Scraper().fetch_targets() with mock.patch.object( batocera_targets_scraper.urllib.request, "urlopen", - serve(["batocera-x86_64.board", "batocera-x86_wow64.board"], False), + _serve_batocera(["batocera-x86_64.board", "batocera-x86_wow64.board"], False), ): targets = batocera_targets_scraper.Scraper().fetch_targets()["targets"] self.assertEqual(targets["x86_64"]["cores"], ["mgba"]) @@ -434,41 +435,28 @@ class KnulliPerBoard(unittest.TestCase): raw = f"https://raw.githubusercontent.com/knulli-cfw/knulli-linux/{pin}/" api = "https://api.github.com/repos/knulli-cfw/knulli-linux/contents/" seen: list[str] = [] - - class _Body: - def __init__(self, body: str): - self.body = body.encode() - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def read(self): - return self.body + names = [p.removeprefix("configs/") for p in self.FILES if p.startswith("configs/")] + exact = { + f"{api}configs?ref={pin}": json.dumps([{"name": n} for n in names]), + f"{api}buildroot?ref={pin}": '{"sha": "c2d7985b"}', + f"{api}batocera?ref={pin}": '{"sha": "487014d9"}', + f"{raw}board/r16/retroarch.cfg": 'menu_show_core_updater = "false"\n', + f"{raw}package/retroarch/retroarch/retroarch.mk": + "RETROARCH_CONF_OPTS = --enable-networking\n", + ("https://raw.githubusercontent.com/batocera-linux/batocera.linux/" + "487014d9/package/batocera/emulators/ppsspp/Config.in"): + "config BR2_PACKAGE_PPSSPP\n\tselect BR2_PACKAGE_PPSSPP_ASSETS\n", + } def urlopen(request, *_a, **_k): url = request.full_url seen.append(url) - if url == f"{api}configs?ref={pin}": - names = [p.removeprefix("configs/") for p in self.FILES if p.startswith("configs/")] - return _Body(json.dumps([{"name": n} for n in names])) - if url == f"{api}buildroot?ref={pin}": - return _Body('{"sha": "c2d7985b"}') - if url == f"{api}batocera?ref={pin}": - return _Body('{"sha": "487014d9"}') + if url in exact: + return _Body(exact[url]) if "/git/trees/" in url: # A board config that hides the downloader leaves its URL. cfg = "board/r16/retroarch.cfg" if "knulli-linux" in url else "x" return _Body(json.dumps({"tree": [{"path": cfg}], "truncated": False})) - if url == f"{raw}board/r16/retroarch.cfg": - return _Body('menu_show_core_updater = "false"\n') - if url == f"{raw}package/retroarch/retroarch/retroarch.mk": - return _Body("RETROARCH_CONF_OPTS = --enable-networking\n") - if url == ("https://raw.githubusercontent.com/batocera-linux/batocera.linux/" - "487014d9/package/batocera/emulators/ppsspp/Config.in"): - return _Body("config BR2_PACKAGE_PPSSPP\n\tselect BR2_PACKAGE_PPSSPP_ASSETS\n") if url == f"{raw}package/utils/vtree/Config.in": raise urllib.error.HTTPError(url, 404, "Not Found", {}, None) if url.endswith("/c2d7985b/arch/Config.in.arm"): @@ -478,7 +466,7 @@ class KnulliPerBoard(unittest.TestCase): path = url.removeprefix(raw) if path in self.FILES: return _Body(self.FILES[path]) - _refuse() + return _refuse() with mock.patch.object(batocera_targets_scraper.urllib.request, "urlopen", urlopen): data = knulli_targets_scraper.Scraper().fetch_targets() diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index 21601cd10..c3f3f8f14 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -58,6 +58,7 @@ class ABuildbotNameSelectsItsProfile(unittest.TestCase): return subprocess.run( [sys.executable, "scripts/cross_reference.py", "--emulator", name], cwd=REPO_ROOT, capture_output=True, text=True, timeout=600, + check=False, ) by_core, by_profile = report("pcfx"), report("beetle_pcfx") self.assertEqual(by_core.returncode, 0, by_core.stderr) diff --git a/tests/test_upstream.py b/tests/test_upstream.py index 1b11229a2..ae7e444f1 100644 --- a/tests/test_upstream.py +++ b/tests/test_upstream.py @@ -379,9 +379,9 @@ class TestGoneUpstream(unittest.TestCase): self._serve(urllib.error.URLError( socket.gaierror(socket.EAI_NONAME, "Name or service not known") )) - with mock.patch.object(upstream, "_resolver_answers", return_value=True): - with self.assertRaises(upstream.GoneError): - upstream._fetch("https://host/x") + with mock.patch.object(upstream, "_resolver_answers", return_value=True), \ + self.assertRaises(upstream.GoneError): + upstream._fetch("https://host/x") self.assertEqual(self.calls, 1) self.assertEqual(self.slept, []) @@ -391,9 +391,9 @@ class TestGoneUpstream(unittest.TestCase): for errno, resolver in ((socket.EAI_NONAME, False), (socket.EAI_AGAIN, True)): with self.subTest(errno=errno, resolver=resolver): self._serve(urllib.error.URLError(socket.gaierror(errno, "no"))) - with mock.patch.object(upstream, "_resolver_answers", return_value=resolver): - with self.assertRaises(upstream.UpstreamError) as caught: - upstream._fetch("https://host/x") + with mock.patch.object(upstream, "_resolver_answers", return_value=resolver), \ + self.assertRaises(upstream.UpstreamError) as caught: + upstream._fetch("https://host/x") self.assertNotIsInstance(caught.exception, upstream.GoneError) def test_a_gone_error_is_still_an_upstream_error(self): @@ -1066,9 +1066,9 @@ class TestGitlabDirectoryArchive(unittest.TestCase): git.assert_called_once() def test_an_empty_archive_is_an_error_not_an_empty_directory(self): - with mock.patch.object(upstream, "_fetch", return_value=_tarball({"p/other/x": "y"})): - with self.assertRaises(upstream.UpstreamError): - upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name) + with mock.patch.object(upstream, "_fetch", return_value=_tarball({"p/other/x": "y"})), \ + self.assertRaises(upstream.UpstreamError): + upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name) if __name__ == "__main__": diff --git a/tests/test_validate_pr.py b/tests/test_validate_pr.py index b43cb8c4e..a4f2f5592 100644 --- a/tests/test_validate_pr.py +++ b/tests/test_validate_pr.py @@ -192,7 +192,7 @@ class ADeclaredFileBesideItsHeldNameIsAVariant(_Fixture): left the copy to land on the held file of that name.""" def test_place_copies_it_beside_the_held_name(self): - import hashlib # noqa: PLC0415 + import hashlib data = b"declared revision" emulators = self.tmp / "emulators" diff --git a/tests/test_verify_all_dir.py b/tests/test_verify_all_dir.py index cc2b325ee..815816cd7 100644 --- a/tests/test_verify_all_dir.py +++ b/tests/test_verify_all_dir.py @@ -35,6 +35,7 @@ class AllReadsTheGivenDirectory(unittest.TestCase): [sys.executable, "scripts/verify.py", "--all", "--platforms-dir", str(plat), "--json"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) self.assertEqual(run.returncode, 0, run.stderr[-2000:]) self.assertEqual(list(json.loads(run.stdout)), ["solo"]) diff --git a/tests/test_verify_emulator_evidence.py b/tests/test_verify_emulator_evidence.py index 9247d6caf..85a35c219 100644 --- a/tests/test_verify_emulator_evidence.py +++ b/tests/test_verify_emulator_evidence.py @@ -63,7 +63,7 @@ def _pack_files(root: Path, emulators: Path, db: dict) -> set[str]: os.chdir(root) try: generate_pack.generate_emulator_pack( - ["demo"], str(emulators), db, "bios", "", False, {}, offline=True, + ["demo"], str(emulators), db, "bios", "", False, zip_contents={}, offline=True, record=record, ) finally: