diff --git a/pyproject.toml b/pyproject.toml index 0053ce36f..092f7f7a1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -90,6 +90,7 @@ select = ["E", "F", "W", "B", "C90", "SIM", "PERF", "UP", "RET", "PIE", "PLR09", ignore = [ "E501", # long lines are wrapped by hand where it reads better "UP006", "UP007", "UP035", "UP045", # install.py keeps 3.8 spellings + "UP036", # the runtime floor guards (sys.version_info < (3, 9)) are the point "SIM300", # an ALL_CAPS name is not always a constant (_SYSTEM_ROOT) "SIM108", # a ternary is not always clearer than an if block "PERF203", # try in a loop is the per-item error report 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/common.py b/scripts/common.py index 2cacada9a..bd9ce05fe 100644 --- a/scripts/common.py +++ b/scripts/common.py @@ -6,8 +6,10 @@ and file resolution - eliminates DRY violations across scripts. from __future__ import annotations -from collections.abc import Callable, Collection, Iterable, Mapping +from collections.abc import Callable, Collection, Iterable, Iterator, Mapping from collections import Counter +import dataclasses +from dataclasses import dataclass import argparse import filecmp @@ -21,10 +23,74 @@ import signal import sys import zipfile from pathlib import Path -from typing import Any, TextIO +from typing import TYPE_CHECKING, Any, TextIO, TypedDict from alternatives import derive_member_requirements +if TYPE_CHECKING: + from typing_extensions import Unpack + +# Re-exported so the existing call sites keep working while the +# modules above become the place to import from. +from safeparse import ( + parse_untrusted_xml as parse_untrusted_xml, + require_yaml as require_yaml, + yaml_load as yaml_load, + _pick_yaml_loader as _pick_yaml_loader, + _YAML_LOADER as _YAML_LOADER, +) +from hashing import ( + compute_hashes as compute_hashes, + md5sum as md5sum, + md5_composite as md5_composite, + parse_md5_list as parse_md5_list, + cut_md5_owner as cut_md5_owner, + _ALL_ALGORITHMS as _ALL_ALGORITHMS, + _md5_composite_cache as _md5_composite_cache, +) +from ziptools import ( + check_inside_zip as check_inside_zip, + build_zip_contents_index as build_zip_contents_index, + MAX_ZIP_MEMBERS as MAX_ZIP_MEMBERS, + MAX_ZIP_MEMBER_SIZE as MAX_ZIP_MEMBER_SIZE, + MAX_ZIP_TOTAL_SIZE as MAX_ZIP_TOTAL_SIZE, + MAX_ZIP_COMPRESSION_RATIO as MAX_ZIP_COMPRESSION_RATIO, + safe_extract_zip as safe_extract_zip, + _zip_contents_cache as _zip_contents_cache, + _BOUNDED_RATIO_METHODS as _BOUNDED_RATIO_METHODS, + zip_member_crcs as zip_member_crcs, + zip_member_names as zip_member_names, +) +from artifacts import ( + write_if_changed as write_if_changed, + write_text_atomic as write_text_atomic, + copy_file_atomic as copy_file_atomic, + plain_file_mode as plain_file_mode, + set_plain_mode as set_plain_mode, + ArtifactDirectoryMissing as ArtifactDirectoryMissing, + ArtifactLockBusy as ArtifactLockBusy, + artifact_lock as artifact_lock, + hold_artifact_lock as hold_artifact_lock, + hold_repository_outputs as hold_repository_outputs, + publish_hold as publish_hold, + repository_output_lock as repository_output_lock, + _TIMESTAMP_PATTERNS as _TIMESTAMP_PATTERNS, + _strip_timestamps as _strip_timestamps, +) +from largefiles import ( + LARGE_FILES_RELEASE as LARGE_FILES_RELEASE, + LARGE_FILES_REPO as LARGE_FILES_REPO, + LARGE_FILES_CACHE as LARGE_FILES_CACHE, + fetch_large_file as fetch_large_file, +) +from dumpcatalog import ( + DEFAULT_PROVENANCE_DIR as DEFAULT_PROVENANCE_DIR, + load_provenance_snapshots as load_provenance_snapshots, + build_provenance_index as build_provenance_index, + annotate_provenance as annotate_provenance, + write_provenance_snapshot as write_provenance_snapshot, +) + # Every build script imports this module. verify.py, slots.py, validate_pr.py # and cross_reference.py started under 3.8 and stopped halfway on a # str.removeprefix AttributeError, which named no version. @@ -139,9 +205,9 @@ _casefold_index_cache: list[tuple[dict, int, dict[str, list[str]]]] = [] def _casefold_name_index(by_name: dict) -> dict[str, list[str]]: """Build (and cache) a casefolded view of the by_name index.""" if _casefold_index_cache: - source, size, folded = _casefold_index_cache[0] + source, size, cached = _casefold_index_cache[0] if source is by_name and size == len(by_name): - return folded + return cached folded: dict[str, list[str]] = {} for name, sha1s in by_name.items(): folded.setdefault(name.casefold(), []).extend(sha1s) @@ -482,55 +548,33 @@ def _inherited_yaml(platform_name: str, platforms_dir: str) -> tuple[dict, list[ return merged, [platform_name, *chain] -def load_platform_config(platform_name: str, platforms_dir: str = "platforms") -> dict: - """Load a platform config with inheritance and shared group resolution. +def _cached_platform_yaml(path: str) -> dict: + """A registry or shared-group file, parsed once per real path.""" + real = os.path.realpath(path) + if real not in _shared_yml_cache: + with open(path) as f: + _shared_yml_cache[real] = source_yaml(f) or {} + return _shared_yml_cache[real] - This is the SINGLE implementation used by generate_pack, generate_readme, - verify, and auto_fetch. No other copy should exist. - """ - cache_key = (platform_name, os.path.realpath(platforms_dir)) - if cache_key in _platform_config_cache: - return _platform_config_cache[cache_key] - config, chain = _inherited_yaml(platform_name, platforms_dir) +def _merge_registry_cores(config: dict, reg_entry: dict, depth: int) -> None: + """Merge cores (union for lists, override for all_libretro), a + parent's only where the platform names none.""" + reg_cores = reg_entry.get("cores") + if reg_cores is None or not (depth == 0 or "cores" not in config): + return + cfg_cores = config.get("cores") + if reg_cores == "all_libretro": + config["cores"] = "all_libretro" + elif isinstance(reg_cores, list) and isinstance(cfg_cores, list): + merged_set = {str(c) for c in cfg_cores} | {str(c) for c in reg_cores} + config["cores"] = sorted(merged_set) + elif isinstance(reg_cores, list) and cfg_cores is None: + config["cores"] = reg_cores - shared_path = os.path.join(platforms_dir, "_shared.yml") - # Merge metadata from _registry.yml. The registry is our curated source, - # while the scraped YAML may be incomplete (missing cores, metadata fields). - # Registry fields supplement (not replace) the scraped config. - registry_path = os.path.join(platforms_dir, "_registry.yml") - if os.path.exists(registry_path): - reg_real = os.path.realpath(registry_path) - if reg_real not in _shared_yml_cache: - with open(registry_path) as f: - _shared_yml_cache[reg_real] = source_yaml(f) or {} - reg = _shared_yml_cache[reg_real] - # The platform's own entry first, then its parents' for what it does - # not say: RetroPie's status, scraper and install are its own, its - # verification mode is RetroArch's. - for depth, name in enumerate(chain): - reg_entry = reg.get("platforms", {}).get(name, {}) - - # Merge cores (union for lists, override for all_libretro), a - # parent's only where the platform names none. - reg_cores = reg_entry.get("cores") - if reg_cores is not None and (depth == 0 or "cores" not in config): - cfg_cores = config.get("cores") - if reg_cores == "all_libretro": - config["cores"] = "all_libretro" - elif isinstance(reg_cores, list) and isinstance(cfg_cores, list): - merged_set = {str(c) for c in cfg_cores} | {str(c) for c in reg_cores} - config["cores"] = sorted(merged_set) - elif isinstance(reg_cores, list) and cfg_cores is None: - config["cores"] = reg_cores - - # Merge all registry fields absent from config (except cores, - # handled above with union logic). No hardcoded list: any field - # added to the registry is automatically available in the config. - for key, val in reg_entry.items(): - if key != "cores" and key not in config: - config[key] = val +def _apply_shared_groups(config: dict, shared_groups: dict) -> None: + """Add each included shared group's files to the systems naming it.""" # A shared group's file joins a system unless the platform already has # it there. Case only makes two names one where the filesystem folds it: # Lakka and RetroPie run on Linux, and np2kai opens 2608_bd.wav beside @@ -538,56 +582,59 @@ def load_platform_config(platform_name: str, platforms_dir: str = "platforms") - def fold(destination: str) -> str: return destination.lower() if config.get("case_insensitive_fs") else destination - if os.path.exists(shared_path): - shared_real = os.path.realpath(shared_path) - if shared_real not in _shared_yml_cache: - with open(shared_path) as f: - _shared_yml_cache[shared_real] = source_yaml(f) or {} - shared = _shared_yml_cache[shared_real] - shared_groups = shared.get("shared_groups", {}) - for system in config.get("systems", {}).values(): - for group_name in system.get("includes", []): - if group_name in shared_groups: - existing = { - (f.get("name"), f.get("destination", f.get("name"))) - for f in system.get("files", []) - } - existing_lower = { - fold(f.get("destination", f.get("name", ""))) - for f in system.get("files", []) - } - for gf in shared_groups[group_name]: - key = (gf.get("name"), gf.get("destination", gf.get("name"))) - dest_lower = fold(gf.get("destination", gf.get("name", ""))) - if key not in existing and dest_lower not in existing_lower: - # Marked as ours: the platform's own file does not - # carry it, and an export must not count it kept. - system.setdefault("files", []).append( - {**gf, "shared_group": group_name} - ) - existing.add(key) - - # Recalbox hashes a .zip by its members, so a plain md5 never answers one - # of its archive declarations: the resolver reads the mark per entry. - if config.get("zip_digest") == "composite": - config["systems"] = { - sys_id: { - **system, - "files": [ - {**f, "zip_digest": "composite"} - if str(f.get("name", "")).lower().endswith(".zip") - else f - for f in system.get("files", []) - ], + for system in config.get("systems", {}).values(): + for group_name in system.get("includes", []): + if group_name not in shared_groups: + continue + existing = { + (f.get("name"), f.get("destination", f.get("name"))) + for f in system.get("files", []) } - for sys_id, system in config.get("systems", {}).items() - } + existing_lower = { + fold(f.get("destination", f.get("name", ""))) + for f in system.get("files", []) + } + for gf in shared_groups[group_name]: + key = (gf.get("name"), gf.get("destination", gf.get("name"))) + dest_lower = fold(gf.get("destination", gf.get("name", ""))) + if key not in existing and dest_lower not in existing_lower: + # Marked as ours: the platform's own file does not + # carry it, and an export must not count it kept. + system.setdefault("files", []).append( + {**gf, "shared_group": group_name} + ) + existing.add(key) - # Each entry carries the system that declares it: a hashless name match is - # narrowed to the maker folder that system names (resolve_local_file). - # A system that names its own cores (EmuELEC, AmberELEC, KNULLI) also - # passes them on, so another emulator's tree is foreign to its entries. - # Fresh dicts, since a YAML anchor can share one entry between systems. + +def _mark_composite_archives(config: dict) -> None: + """Mark every .zip entry as hashed by its members. + + Recalbox hashes a .zip by its members, so a plain md5 never answers one + of its archive declarations: the resolver reads the mark per entry. + """ + config["systems"] = { + sys_id: { + **system, + "files": [ + {**f, "zip_digest": "composite"} + if str(f.get("name", "")).lower().endswith(".zip") + else f + for f in system.get("files", []) + ], + } + for sys_id, system in config.get("systems", {}).items() + } + + +def _tag_platform_systems(config: dict) -> None: + """Each entry carries the system that declares it. + + A hashless name match is narrowed to the maker folder that system names + (resolve_local_file). A system that names its own cores (EmuELEC, + AmberELEC, KNULLI) also passes them on, so another emulator's tree is + foreign to its entries. Fresh dicts, since a YAML anchor can share one + entry between systems. + """ config["systems"] = { sys_id: { **system, @@ -609,21 +656,69 @@ def load_platform_config(platform_name: str, platforms_dir: str = "platforms") - for sys_id, system in config.get("systems", {}).items() } + +def _attach_rom_folders(config: dict, platform_name: str, platforms_dir: str) -> None: + """Where the platform's games live, as its rom folders file records it + from the OS's own source (platforms/romfolders/.yml, roms_root).""" + romfolders = os.path.join(platforms_dir, "romfolders", f"{platform_name}.yml") + if not os.path.exists(romfolders): + return + with open(romfolders) as f: + roms_root = (source_yaml(f) or {}).get("roms_root") + if isinstance(roms_root, dict): + config["_roms_root"] = roms_root + with open(romfolders) as f: + folders = (source_yaml(f) or {}).get("folders") + if isinstance(folders, list): + config["_rom_folders"] = [row for row in folders if isinstance(row, dict)] + + +def load_platform_config(platform_name: str, platforms_dir: str = "platforms") -> dict: + """Load a platform config with inheritance and shared group resolution. + + This is the SINGLE implementation used by generate_pack, generate_readme, + verify, and auto_fetch. No other copy should exist. + """ + cache_key = (platform_name, os.path.realpath(platforms_dir)) + if cache_key in _platform_config_cache: + return _platform_config_cache[cache_key] + + config, chain = _inherited_yaml(platform_name, platforms_dir) + + shared_path = os.path.join(platforms_dir, "_shared.yml") + # Merge metadata from _registry.yml. The registry is our curated source, + # while the scraped YAML may be incomplete (missing cores, metadata fields). + # Registry fields supplement (not replace) the scraped config. + registry_path = os.path.join(platforms_dir, "_registry.yml") + if os.path.exists(registry_path): + reg = _cached_platform_yaml(registry_path) + # The platform's own entry first, then its parents' for what it does + # not say: RetroPie's status, scraper and install are its own, its + # verification mode is RetroArch's. + for depth, name in enumerate(chain): + reg_entry = reg.get("platforms", {}).get(name, {}) + _merge_registry_cores(config, reg_entry, depth) + + # Merge all registry fields absent from config (except cores, + # handled above with union logic). No hardcoded list: any field + # added to the registry is automatically available in the config. + for key, val in reg_entry.items(): + if key != "cores" and key not in config: + config[key] = val + + if os.path.exists(shared_path): + shared = _cached_platform_yaml(shared_path) + _apply_shared_groups(config, shared.get("shared_groups", {})) + + if config.get("zip_digest") == "composite": + _mark_composite_archives(config) + + _tag_platform_systems(config) + # The registry key, which per-platform profile fields (installed_on, # not_bundled_on) name: the display name differs (MiSTer FPGA). config["_key"] = platform_name - # Where the platform's games live, as its rom folders file records it - # from the OS's own source (platforms/romfolders/.yml, roms_root). - romfolders = os.path.join(platforms_dir, "romfolders", f"{platform_name}.yml") - if os.path.exists(romfolders): - with open(romfolders) as f: - roms_root = (source_yaml(f) or {}).get("roms_root") - if isinstance(roms_root, dict): - config["_roms_root"] = roms_root - with open(romfolders) as f: - folders = (source_yaml(f) or {}).get("folders") - if isinstance(folders, list): - config["_rom_folders"] = [row for row in folders if isinstance(row, dict)] + _attach_rom_folders(config, platform_name, platforms_dir) _platform_config_cache[cache_key] = config return config @@ -1076,18 +1171,24 @@ def resolution_is_hash_exact(status: str) -> bool: return status in HASH_EXACT_RESOLUTION_STATUSES +class DeclaredHashes(TypedDict): + """What an entry declares about its content, as declared_hash_verdict reads it.""" + + has_strong_hash: bool + sha1_candidates: Collection[str] + sha256_candidates: Collection[str] + md5_list: list[str] + crc_candidates: Collection[str] + zipped_file: str | None + declared_size: int | list[int] | None + + def declared_hash_verdict( candidate: str, *, - has_strong_hash: bool, - sha1_candidates: set, - sha256_candidates: set, - md5_list: list, - crc_candidates: set, - zipped_file: str | None, - declared_size: int | list[int] | None, file_entry: dict | None = None, db: dict | None = None, + **declared: Unpack[DeclaredHashes], ) -> str: """Judge a candidate found by name against everything the entry declares. @@ -1096,7 +1197,13 @@ def declared_hash_verdict( about its content is checked here before the walk may return it, including the size and Adler-32 the name steps over bios/ apply. """ - if not has_strong_hash: + sha1_candidates = declared["sha1_candidates"] + sha256_candidates = declared["sha256_candidates"] + md5_list = declared["md5_list"] + crc_candidates = declared["crc_candidates"] + zipped_file = declared["zipped_file"] + declared_size = declared["declared_size"] + if not declared["has_strong_hash"]: if file_entry is not None and not ( name_match_size_ok(file_entry, os.path.getsize(candidate)) and adler32_fits(file_entry, candidate, db) @@ -1149,7 +1256,7 @@ def _resolve_in_data_dirs( rather than shipping the file. """ mismatch: str | None = None - for _key, dd_entry in data_dir_registry.items(): + for dd_entry in data_dir_registry.values(): cache_dir = dd_entry.get("local_cache", "") if not cache_dir or not os.path.isdir(cache_dir): continue @@ -1262,7 +1369,7 @@ def _resolve_agnostic( prefix = file_entry.get("agnostic_path_prefix", "") if not prefix: return None - for _sha1, entry in files_db.items(): + for entry in files_db.values(): path = entry.get("path", "") if not path.startswith(prefix): continue @@ -1611,6 +1718,774 @@ def _warn_unreadable_archive(path: str, exc: Exception) -> None: print(f"warning: unreadable archive {path}: {exc}", file=sys.stderr) +Resolution = tuple[str, str] + + +@dataclass(frozen=True) +class _Lookup: + """One entry as resolve_local_file reads it: its names and declared hashes.""" + + file_entry: dict + db: dict + dest_hint: str + name: str + zipped_file: str | None + names_to_try: list[str] + own_names: list[str] + md5_list: list[str] + sha1_candidates: list[str] + sha256_candidates: list[str] + crc_candidates: dict[str, None] + declared_size: Any + files_db: dict + by_name: dict + by_path_suffix: dict + composite_only: bool + + @property + def has_strong_hash(self) -> bool: + return bool( + self.sha1_candidates or self.sha256_candidates or self.md5_list or self.crc_candidates + ) + + +def _lookup_names(name: str, aliases: list, dest_hint: str) -> tuple[list[str], list[str]]: + """The names an entry answers to, and the part of them that is its own.""" + names_to_try = [name] + [a for a in aliases if a != name] + + # When name contains a path separator (e.g. "res/tilemap.bin"), also + # try the basename since by_name indexes filenames without directories + if "/" in name: + name_base = name.rsplit("/", 1)[-1] + if name_base and name_base not in names_to_try: + names_to_try.append(name_base) + + # When dest_hint contains a path, also try its basename as a name + # (handles emulator profiles where name: is descriptive and path: is + # the actual filename, e.g. name: "MDA font ROM", path: "mda.rom") + own_names = list(names_to_try) + if dest_hint: + hint_base = dest_hint.rsplit("/", 1)[-1] if "/" in dest_hint else dest_hint + if hint_base and hint_base not in names_to_try: + names_to_try.append(hint_base) + return names_to_try, own_names + + +def _lookup( + file_entry: dict, db: dict, dest_hint: str, md5_list: list[str], *, composite_only: bool +) -> _Lookup: + """Read the names and every declared hash of an entry once.""" + sha1 = file_entry.get("sha1") + name = file_entry.get("name", "") + names_to_try, own_names = _lookup_names(name, file_entry.get("aliases", []), dest_hint) + sha1_candidates = [ + str(value).strip().lower() + for value in (sha1 if isinstance(sha1, list) else [sha1] if sha1 else []) + if str(value).strip() + ] + sha256_raw = file_entry.get("sha256") + sha256_values = sha256_raw if isinstance(sha256_raw, list) else [sha256_raw] + sha256_candidates = [ + candidate.strip().lower() + for value in sha256_values + if value + for candidate in str(value).split(",") + if len(candidate.strip()) == 64 + ] + # One value, a list, or a comma-separated string, like the other hashes. + crc_values = file_entry.get("crc32") or [] + # Kept in the order declared, which is the order a lookup tries them. + crc_candidates = dict.fromkeys( + candidate.strip().lower().removeprefix("0x") + for value in (crc_values if isinstance(crc_values, list) else [crc_values]) + for candidate in str(value).split(",") + if candidate.strip() + ) + indexes = db.get("indexes", {}) + return _Lookup( + file_entry=file_entry, + db=db, + dest_hint=dest_hint, + name=name, + zipped_file=file_entry.get("zipped_file"), + names_to_try=names_to_try, + own_names=own_names, + md5_list=md5_list, + sha1_candidates=sha1_candidates, + sha256_candidates=sha256_candidates, + crc_candidates=crc_candidates, + declared_size=file_entry.get("size"), + files_db=db.get("files", {}), + by_name=indexes.get("by_name", {}), + by_path_suffix=indexes.get("by_path_suffix", {}), + composite_only=composite_only, + ) + + +def _record_match_status(q: _Lookup, match_sha1: str) -> str | None: + """Return hash evidence when a DB record satisfies every declaration.""" + entry = q.files_db.get(match_sha1) + if not entry: + return None + statuses: list[str] = [] + if q.sha1_candidates: + if match_sha1.lower() not in q.sha1_candidates: + return None + statuses.append("sha1_exact") + if q.sha256_candidates: + if str(entry.get("sha256", "")).lower() not in q.sha256_candidates: + return None + statuses.append("sha256_exact") + # With zipped_file the MD5 identifies the member, not the container. + if q.md5_list and not q.zipped_file: + actual_md5 = str(entry.get("md5", "")).lower() + if actual_md5 not in q.md5_list: + return None + statuses.append("md5_exact") + if q.crc_candidates: + if str(entry.get("crc32", "")).lower() not in q.crc_candidates: + return None + if q.declared_size is not None: + allowed_sizes = ( + q.declared_size if isinstance(q.declared_size, list) else [q.declared_size] + ) + if entry.get("size") not in allowed_sizes: + return None + statuses.append("crc32_exact") + return statuses[0] if statuses else None + + +def _held_record(q: _Lookup, match_sha1: str) -> Resolution | None: + """The record's path and evidence, when it satisfies the entry and is on disk.""" + path = q.files_db[match_sha1]["path"] + status = _record_match_status(q, match_sha1) + if status and os.path.exists(path): + return path, status + return None + + +def _by_sha1(q: _Lookup) -> Resolution | None: + """SHA1 exact match (accept list-valued sha1 from profiles).""" + for cand in q.sha1_candidates: + if cand in q.files_db: + found = _held_record(q, cand) + if found: + return found + return None + + +def _by_sha256(q: _Lookup) -> Resolution | None: + """SHA256 exact match, through the by_sha256 index.""" + if not q.sha256_candidates: + return None + by_sha256 = q.db.get("indexes", {}).get("by_sha256", {}) + for cand in q.sha256_candidates: + match = by_sha256.get(cand) + if match and match in q.files_db: + found = _held_record(q, match) + if found: + return found + return None + + +def _by_crc32(q: _Lookup) -> Resolution | None: + """CRC32 lookup, only when no stronger hash is declared.""" + if ( + not q.crc_candidates + or q.zipped_file + or q.md5_list + or q.sha1_candidates + or q.sha256_candidates + ): + return None + by_crc32 = q.db.get("indexes", {}).get("by_crc32", {}) + crc_matches: list[Resolution] = [] + for crc in q.crc_candidates: + match = by_crc32.get(crc) + if match and match in q.files_db: + found = _held_record(q, match) + if found: + crc_matches.append(found) + # A primary copy over a .variants/ one, as everywhere else. + for path, status in crc_matches: + if "/.variants/" not in path: + return path, status + if crc_matches: + return crc_matches[0] + return None + + +def _md5_hits(q: _Lookup) -> Iterator[tuple[str, str, str]]: + """Each held record a declared md5 names: path, evidence, md5 asked. + + Skipped for zipped_file: the md5 is the inner ROM's, not the container's. + """ + if not q.md5_list or q.zipped_file or q.composite_only: + return + by_md5 = q.db.get("indexes", {}).get("by_md5", {}) + for md5_candidate in q.md5_list: + sha1_match = by_md5.get(md5_candidate) + if sha1_match and sha1_match in q.files_db: + found = _held_record(q, sha1_match) + if found: + yield found[0], found[1], md5_candidate + + +def _named_or_variant(names: frozenset[str], candidate_path: str) -> bool: + """Whether a path's file name is one of these names, or a variant of one.""" + bn = os.path.basename(candidate_path) + if bn in names: + return True + # .variants/ pattern: filename like "neogeo.zip.fc398ab4" + return any(bn.startswith(n + ".") for n in names) + + +def _tail_candidates(q: _Lookup, start: int, tail: str, owners: set[str]) -> list[str]: + """The records a destination tail names, ranked, ambiguity read.""" + candidates = _rank_tail_candidates( + q.by_path_suffix.get(tail, []), start, tail, q.files_db, owners, + frozenset(_owner_tokens(q.file_entry)), + ) + raw = q.by_path_suffix.get(tail, []) + if start and len(raw) > 1: + # Ambiguity is read before the foreign trees are set aside: + # PCSX2x6's bin/resources/GameIndex.yaml met four copies + # under resources/GameIndex.yaml, three in other emulators' + # trees, and the fourth (PCSX2's console database, not + # PCSX2x6's arcade one) passed for proof. Only the asker's own + # tree still answers a tail several files share. + candidates = [ + h for h in candidates + if _own_tree(q.files_db.get(h, {}).get("path", ""), owners) + ] + return candidates + + +def _tail_match(q: _Lookup, candidates: list[str]) -> Resolution | None: + """The first candidate of a tail on disk that the entry accepts.""" + for match_sha1 in candidates: + if match_sha1 not in q.files_db: + continue + path = q.files_db[match_sha1]["path"] + if not os.path.exists(path): + continue + if not q.has_strong_hash: + # A path names the file, the size the code checks still + # bounds it, as on the name step: ZEsarUX's 48 KB + # cpc6128.rom is not cap32's 32 KB one at the same tail. + if not name_match_size_ok( + q.file_entry, q.files_db[match_sha1].get("size") + ) or not adler32_fits(q.file_entry, path, q.db) or not content_fits( + q.file_entry, path + ): + continue + return path, "path_exact" + status = _record_match_status(q, match_sha1) + if status: + return path, status + return None + + +def _by_path_suffix(q: _Lookup) -> tuple[Resolution | None, bool]: + """The file at the destination's tail, and whether the indexed one is absent.""" + own_file_absent = False + if not (q.dest_hint and q.by_path_suffix): + return None, own_file_absent + # A destination is written from the emulator's point of view + # ("pcsx2/resources/GameIndex.yaml") and the index from the repo's + # layout, so the two meet on a tail rather than on the whole string. + # Longest tail first, and never down to the bare filename: that is the + # weaker step below, and five files answer to GameIndex.yaml. + # Two kinds of ambiguity appear once every tail is indexed. A + # shortened tail can be claimed by several emulators shipping the same + # asset tree, and it then proves nothing: skip it. The full tail can be + # claimed twice as well, one storing it at the root of its own + # directory and one nested deeper. There the file whose path carries + # the least on top of the destination is the one that IS the + # destination. + # The descent drops at most one leading segment. A destination and the + # tree differ by the wrapper directory at most. Beyond that the tail + # stops describing this file and starts describing whichever emulator + # happens to store the same asset tree. + hint_parts = q.dest_hint.split("/") + # The asking profile and the destination's own directories both name + # whose tree a copy may come from. + owners = _owner_tokens(q.file_entry) | _affinity_tokens("/".join(hint_parts[:-1])) + for start in range(min(2, len(hint_parts) - 1)): + candidates = _tail_candidates(q, start, "/".join(hint_parts[start:]), owners) + if start and len(candidates) > 1: + continue + # The index names the file this destination designates. Not on + # disk, it is a release asset the checkout does not hold, and no + # other file of that name is it. + if not start and candidates and not any( + os.path.exists(q.files_db.get(h, {}).get("path", "")) + for h in candidates + ): + own_file_absent = True + found = _tail_match(q, candidates) + if found: + return found, own_file_absent + return None, own_file_absent + + +def _by_data_dir_tail(q: _Lookup, data_dir_registry: dict | None) -> Resolution | None: + """The same tail in a data directory, for a platform's hashless entry.""" + # by_path_suffix indexes bios/ + # only, so AmberELEC's Machines/MSX - Arabic/config.ini fell through to + # the name step and got msx-emu's ColecoVision config.ini, while + # data/bluemsx held blueMSX's own at that very path. A platform + # declaration is resolved without a hint, and its destination is that + # path. The descent and the ambiguity rule are those of the bios/ tails. + # A profile's entry is not asked here: it names its owner, the name step + # sends it to its data directories when another emulator's copy answers, + # and a dump it declares outranks the free one its tree bundles at the + # same path (Dolphin's dsp_coef.bin over Sys/GC's). + tail_hint = q.dest_hint or str(q.file_entry.get("destination") or "") + if ( + tail_hint + and data_dir_registry + and not q.has_strong_hash + and not _owner_tokens(q.file_entry) + ): + hit = _data_dir_tail(tail_hint, data_dir_registry, q.file_entry, q.db) + if hit: + return hit, "path_exact" + return None + + +def _name_size_ok(q: _Lookup, match_sha1: str) -> bool: + """Whether a record found by name has the shape the entry's code checks.""" + record = q.files_db.get(match_sha1, {}) + return name_match_size_ok(q.file_entry, record.get("size")) and adler32_fits( + q.file_entry, record.get("path", ""), q.db + ) and content_fits(q.file_entry, record.get("path", "")) + + +def _exact_name_candidates(q: _Lookup) -> list[str]: + """The held files answering to the entry's names, exact casing.""" + candidates: list[str] = [] + # The entry's own names first, the destination's basename only when + # none of them answers. melonDS Nightly's dsi_nand.bin is read at + # dsi/nand.bin: with the DSi image absent from the checkout, the + # basename let the Wii nand.bin outrank the entry's own DSi variant. + # A name whose held file no declaration proves, while declarations + # of that name prove another dump beside it, means that dump: the + # DSi devkit boot ROMs filed as dsi_bios7.bin went to RetroBat. + by_proven_name = q.db.get("indexes", {}).get("by_proven_name", {}) + for tier in (q.own_names, q.names_to_try[len(q.own_names):]): + for try_name in tier: + for match_sha1 in ( + by_proven_name.get(try_name) or q.by_name.get(try_name, []) + ): + if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + path = q.files_db[match_sha1]["path"] + if os.path.exists(path) and path not in candidates: + candidates.append(path) + if candidates: + break + return candidates + + +def _add_variant_primaries(q: _Lookup, candidates: list[str]) -> None: + """Add the primaries that variants answering the exact casing stand in for.""" + # Only variants answer the exact casing, but the primary they + # stand in for may be stored under another one: x1 asked for + # IPLROM.X1 and got Recalbox's second md5 while iplrom.x1, the + # dump every platform pins, sat in the same directory. A primary + # counts here only in a variant's own directory and under its own + # file name: an alias (iplrom.x1t names a font in System.dat) or + # another machine's font.rom is not that file. + homes = {p.split("/.variants/", 1)[0] for p in candidates} + folded = _casefold_name_index(q.by_name) + for try_name in q.names_to_try: + wanted = try_name.rsplit("/", 1)[-1].casefold() + for match_sha1 in folded.get(try_name.casefold(), []): + path = q.files_db.get(match_sha1, {}).get("path", "") + if ( + "/.variants/" not in path + and os.path.dirname(path) in homes + and os.path.basename(path).casefold() == wanted + and _name_size_ok(q, match_sha1) + and os.path.exists(path) + and path not in candidates + ): + candidates.append(path) + + +def _add_casefold_candidates(q: _Lookup, candidates: list[str], owners: set[str]) -> None: + """Add the held files answering to the entry's names in another casing.""" + # Case-insensitive fallback: upstream platforms disagree on + # casing (VEC_MineStorm.vec vs VEC_Minestorm.vec). Two casings + # can name two contents (FONT.ROM and font.rom), so this only + # runs when no casing matches exactly, or when only another + # emulator's tree does: xm6typeg got XM6 Utility's synthesized + # SCSIINROM.DAT while the X68000 dump sat as scsiinrom.dat. + # Another casing in another emulator's tree proves nothing: + # reminiscence's music module reunion took skyline's + # zoneinfo/Indian/Reunion. + folded = _casefold_name_index(q.by_name) + for try_name in q.names_to_try: + for match_sha1 in folded.get(try_name.casefold(), []): + if match_sha1 in q.files_db and _name_size_ok(q, match_sha1): + path = q.files_db[match_sha1]["path"] + if _foreign_tree(path, owners): + continue + if os.path.exists(path) and path not in candidates: + candidates.append(path) + + +def _same_maker(q: _Lookup, candidates: list[str], makers: frozenset[str]) -> list[str]: + """The candidates filed under the system's maker, or its shadowed aliases.""" + candidates = [p for p in candidates if not other_maker(p, makers, q.db)] + if candidates: + return candidates + # The name belongs to another maker's file here. An emulator + # of this system may still read it as an alias of one of its + # own files, an alias by_name leaves out because a primary + # already carries the name: QUASI88 reads DISK.ROM as + # n88sub.rom. + shadowed = q.db.get("indexes", {}).get("by_shadowed_alias", {}) + for try_name in q.own_names: + for match_sha1 in shadowed.get(try_name, []): + path = q.files_db.get(match_sha1, {}).get("path", "") + if ( + _maker_folder(path, str(q.db.get("bios_dir") or "bios")) + in makers + and _name_size_ok(q, match_sha1) + and os.path.exists(path) + and path not in candidates + ): + candidates.append(path) + return candidates + + +def _choose_by_name( + q: _Lookup, + candidates: list[str], + owners: set[str], + exact_foreign: bool, + data_dir_registry: dict | None, +) -> Resolution | None: + """The best of the files a name step found, or the data directory's own.""" + if q.zipped_file: + candidates = [p for p in candidates if ".zip" in os.path.basename(p)] + members = q.file_entry.get("members") or contents_members(q.file_entry) + if members or (len(candidates) > 1 and q.name.casefold().endswith(".zip")): + # Another emulator's own copy takes no part in the ranking: + # Demul's naomi.zip holds more NAOMI BIOS rows than any MAME + # set and broke the superset the MAME cores were served. + candidates = [ + p for p in candidates if not _foreign_tree(p, owners) + ] or candidates + if members: + candidates = _holding_members(candidates, members) + elif len(candidates) > 1 and q.name.casefold().endswith(".zip"): + candidates = _covering_archives(candidates) + candidates = _by_affinity(candidates, q.file_entry, q.dest_hint) + best = candidates[0] if candidates else "" + # A copy outside another emulator's tree comes first: the + # affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served + # upstream PCSX2 the patches.zip of ARMSX2. + candidates = [ + p for p in candidates if not _foreign_tree(p, owners) + ] or candidates + primary = [p for p in candidates if "/.variants/" not in p] + if not (primary or candidates): + return None + chosen = primary[0] if primary else candidates[0] + # The best of them is another emulator's own copy, served or + # set aside: the name says nothing about this profile's file, + # and a data directory it reads may hold it. Dolphin got + # Dolphin-MMJR's codehandler.bin while data/dolphin-sys held + # its own, and blueMSX got the 16 KB RS232.ROM once msx-emu's + # 8 KB copy was set aside, while data/bluemsx held its own, + # and MSX2P.ROM of another dump once only msx-emu answered + # the exact casing. + if data_dir_registry and (exact_foreign or _foreign_tree(best, owners)): + hit, _mismatch = _resolve_in_data_dirs( + q.names_to_try, data_dir_registry, + functools.partial( + declared_hash_verdict, + has_strong_hash=False, + sha1_candidates=set(), + sha256_candidates=set(), + md5_list=[], + crc_candidates=set(), + zipped_file=q.zipped_file, + declared_size=q.declared_size, + file_entry=q.file_entry, + db=q.db, + ), + ) + if hit: + return hit + return chosen, "name_exact" + + +def _by_name( + q: _Lookup, makers: frozenset[str], data_dir_registry: dict | None +) -> tuple[Resolution | None, bool]: + """Any file with that name or alias (existence check). + + The second value says the name proved nothing, which makes the entry + unsourceable for the steps after this one. + """ + candidates = _exact_name_candidates(q) + if candidates and all("/.variants/" in p for p in candidates): + _add_variant_primaries(q, candidates) + owners = _owner_tokens(q.file_entry) + # Only another emulator's tree answers the exact casing: what it + # holds there says nothing about this entry's file. + exact_foreign = bool(candidates) and all( + _foreign_tree(p, owners) for p in candidates + ) + if not candidates or exact_foreign: + _add_casefold_candidates(q, candidates, owners) + # A platform entry names no profile, but a system that lists its + # cores says whose files it asks for. A name only another emulator's + # tree answers is no evidence, and the data directories hold those + # emulators' trees too: EmuELEC's VVVVVV data.zip was served xrick's + # archive of the same name, then xrick's data directory copy. + core_owners = { + token + for core in q.file_entry.get("platform_cores") or () + for token in _affinity_tokens(str(core)) + } + if ( + not owners + and core_owners + and candidates + and all(_foreign_tree(p, core_owners) for p in candidates) + ): + return None, True + if makers and candidates: + candidates = _same_maker(q, candidates, makers) + if not candidates: + return None, False + return _choose_by_name(q, candidates, owners, exact_foreign, data_dir_registry), False + + +def _named_candidates(q: _Lookup, makers: frozenset[str]) -> list[tuple[str, str, int | None]]: + """Every held file of the entry's names: path, md5, size.""" + named: list[tuple[str, str, int | None]] = [] + seen_paths = set() + for try_name in q.names_to_try: + for match_sha1 in q.by_name.get(try_name, []): + if match_sha1 in q.files_db: + entry = q.files_db[match_sha1] + path = entry["path"] + if os.path.exists(path) and path not in seen_paths: + seen_paths.add(path) + named.append( + (path, entry.get("md5", ""), entry.get("size")) + ) + + if q.zipped_file: + named = [c for c in named if ".zip" in os.path.basename(c[0])] + # Another maker's file is no mismatch of this one, it is another file. + named = [c for c in named if not other_maker(c[0], makers, q.db)] + # A size the emulator itself verifies settles a name collision, so a + # candidate that fits is preferred over one that does not: "ROM" answers + # both an Apple IIgs image and a Macintosh one. It ranks rather than + # excludes, because a present file of the wrong size is reported as + # present and untested, and dropping it would report it as absent. + sized = [ + c for c in named + if name_match_size_ok(q.file_entry, c[2]) and content_fits(q.file_entry, c[0]) + ] + if sized: + named = sized + return named + + +def _named_md5_match(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution | None: + """A named file whose md5, or archive composite, is a declared one. + + Sorts *named* in place for a composite-only entry, as the steps after + this one read it. + """ + md5_set = set(q.md5_list) + if not md5_set or q.sha1_candidates or q.sha256_candidates or q.crc_candidates: + return None + if q.composite_only: + named.sort(key=lambda c: "/.variants/" in c[0]) + for path, db_md5, _size in named: + if ".zip" in os.path.basename(path): + try: + composite = md5_composite(path).lower() + # A zipped_file md5 is the member's: one member of + # another name has the same composite, and Batocera + # looks the member up by name. + if composite in md5_set and ( + not q.zipped_file + or check_inside_zip(path, q.zipped_file, composite) == "ok" + ): + return path, "md5_composite_exact" + except (zipfile.BadZipFile, OSError) as exc: + _warn_unreadable_archive(path, exc) + if db_md5.lower() in md5_set and not q.composite_only: + return path, "md5_exact" + return None + + +def _zipped_named( + q: _Lookup, named: list[tuple[str, str, int | None]], zipped_file: str +) -> Resolution | None: + """When zipped_file is set, only accept candidates that contain it.""" + valid = [] + for path, m, size in named: + try: + with zipfile.ZipFile(path) as zf: + inner_names = {n.casefold() for n in zf.namelist()} + if zipped_file.casefold() in inner_names: + valid.append((path, m, size)) + except (zipfile.BadZipFile, OSError) as exc: + _warn_unreadable_archive(path, exc) + # The archive whose member carries the declared md5 is the one: + # neogeo.zip is held twice, each with its own sfix.sfix, and the + # first by name was returned as a mismatch while the other matched. + for path, _m, _size in sorted(valid, key=lambda c: "/.variants/" in c[0]): + if any(check_inside_zip(path, zipped_file, md5) == "ok" for md5 in q.md5_list): + return path, "zip_exact" + if valid: + primary = [c[0] for c in valid if "/.variants/" not in c[0]] + return (primary[0] if primary else valid[0][0]), "hash_mismatch" + # No candidate contains the zipped_file: fall through to step 5 + return None + + +def _ranked_mismatch(q: _Lookup, named: list[tuple[str, str, int | None]]) -> Resolution: + """The named file the entry would take, reported as a hash mismatch.""" + ordered = _by_affinity([c[0] for c in named], q.file_entry, q.dest_hint) + primary = [c for c in ordered if "/.variants/" not in c] + return (primary[0] if primary else ordered[0]), "hash_mismatch" + + +def _by_zip_contents(q: _Lookup, zip_contents: dict | None) -> Resolution | None: + """zipped_file content match via pre-built index. + + Last resort: matches inner ROM MD5 across ALL ZIPs in the repo, so only + used when name-based resolution failed entirely. + """ + if not ( + q.zipped_file + and q.md5_list + and zip_contents + and not (q.sha1_candidates or q.sha256_candidates or q.crc_candidates) + ): + return None + for md5_candidate in q.md5_list: + if md5_candidate in zip_contents: + zip_sha1 = zip_contents[md5_candidate] + if zip_sha1 in q.files_db: + path = q.files_db[zip_sha1]["path"] + if os.path.exists(path): + return path, "zip_exact" + return None + + +def _by_mame_clone( + q: _Lookup, zip_contents: dict | None, depth: int, data_dir_registry: dict | None +) -> Resolution | None: + """If a file was deduped, resolve via canonical.""" + clone_map = get_mame_clone_map(q.db.get("bios_dir")) + canonical = clone_map.get(q.name) + if not canonical or canonical == q.name: + return None + canonical_entry = { + field: q.file_entry[field] + for field in ( + "size", "min_size", "max_size", "size_multiple", "validation", + *sorted(CONTENT_CHECKS), + ) + if field in q.file_entry + } + canonical_entry["name"] = canonical + result = resolve_local_file( + canonical_entry, + q.db, + zip_contents, + q.dest_hint, + _depth=depth + 1, + data_dir_registry=data_dir_registry, + ) + if result[0] and result[1] != "hash_mismatch": + return result[0], "mame_clone" + return None + + +def _in_data_dirs(q: _Lookup, data_dir_registry: dict) -> tuple[Resolution | None, str | None]: + """Data directory fallback: scan data/ caches for matching filename.""" + verdict = functools.partial( + declared_hash_verdict, + has_strong_hash=q.has_strong_hash, + sha1_candidates=q.sha1_candidates, + sha256_candidates=q.sha256_candidates, + md5_list=q.md5_list, + crc_candidates=set(q.crc_candidates), + zipped_file=q.zipped_file, + declared_size=q.declared_size, + file_entry=q.file_entry, + db=q.db, + ) + return _resolve_in_data_dirs(q.names_to_try, data_dir_registry, verdict) + + +def _resolve_layout( + file_entry: dict, + db: dict, + zip_contents: dict | None, + dest_hint: str, + *, + depth: int, + data_dir_registry: dict | None, +) -> tuple[str | None, str]: + """Resolve an entry whose launcher moves it, at both destinations.""" + layout = file_entry.get("layout_path") + plain = {k: v for k, v in file_entry.items() if k != "layout_path"} + # A destination outside the BIOS tree says nothing of the collection: + # EmuELEC's roms/mame/konamigv.zip is not bios/Arcade/MAME's set. + outside = file_entry.get("unprefixed") or file_entry.get("root") + answers = [ + resolve_local_file( + plain, db, zip_contents, dest_hint=hint, _depth=depth, + data_dir_registry=data_dir_registry, + ) + for hint in ((str(layout),) if outside else (dest_hint, str(layout))) + ] + for found in answers: + if found[0] is not None and ( + resolution_is_hash_exact(found[1]) or found[1] == "path_exact" + ): + return found + for found in answers: + if found[0] is not None and found[1] not in ("not_found", "hash_mismatch"): + return found + return next((found for found in answers if found[0] is not None), answers[0]) + + +def _entry_hint(file_entry: dict, dest_hint: str) -> str: + """The destination tail the collection indexes the entry under.""" + # A platform that hands each core a system directory of its own (MinUI's + # Bios//) writes that folder in front of the core's path. The tail + # the collection indexes is the core's path alone. + system_dir = file_entry.get("system_dir") + if system_dir and dest_hint.startswith(f"{system_dir}/"): + dest_hint = dest_hint[len(system_dir) + 1:] + return dest_hint + + +def _name_as_hint(name: str, dest_hint: str) -> str: + """A name written with its directory is the destination when no path is given.""" + # gam4980/E.BIN resolved by its basename took another model's OS + # in verify --emulator and the emulator pack, while the platform pack, + # which passes the destination, served the GAM4980's. + if not dest_hint and "/" in name.strip("/"): + return name + return dest_hint + + def resolve_local_file( file_entry: dict, db: dict, @@ -1636,68 +2511,18 @@ def resolve_local_file( A path or filename is never allowed to override a declared strong hash. """ - sha1 = file_entry.get("sha1") - name = file_entry.get("name", "") - # A platform that hands each core a system directory of its own (MinUI's - # Bios//) writes that folder in front of the core's path. The tail - # the collection indexes is the core's path alone. - system_dir = file_entry.get("system_dir") - if system_dir and dest_hint.startswith(f"{system_dir}/"): - dest_hint = dest_hint[len(system_dir) + 1:] + dest_hint = _entry_hint(file_entry, dest_hint) # A launcher that moves the layout (EmuDeck links azahar's sysdata to # bios/azahar/keys) changes where the file goes, not the tail the # collection indexes it under. Both are asked, and the stronger proof # wins: a content or path match over a name, the destination on a tie. layout = file_entry.get("layout_path") if layout and layout != dest_hint: - plain = {k: v for k, v in file_entry.items() if k != "layout_path"} - # A destination outside the BIOS tree says nothing of the collection: - # EmuELEC's roms/mame/konamigv.zip is not bios/Arcade/MAME's set. - outside = file_entry.get("unprefixed") or file_entry.get("root") - answers = [ - resolve_local_file( - plain, db, zip_contents, dest_hint=hint, _depth=_depth, - data_dir_registry=data_dir_registry, - ) - for hint in ((str(layout),) if outside else (dest_hint, str(layout))) - ] - for found in answers: - if found[0] is not None and ( - resolution_is_hash_exact(found[1]) or found[1] == "path_exact" - ): - return found - for found in answers: - if found[0] is not None and found[1] not in ("not_found", "hash_mismatch"): - return found - return next((found for found in answers if found[0] is not None), answers[0]) - # A name written with its directory is the destination when no path is - # given: gam4980/E.BIN resolved by its basename took another model's OS - # in verify --emulator and the emulator pack, while the platform pack, - # which passes the destination, served the GAM4980's. - if not dest_hint and "/" in name.strip("/"): - dest_hint = name - zipped_file = file_entry.get("zipped_file") - aliases = file_entry.get("aliases", []) - names_to_try = [name] + [a for a in aliases if a != name] - - # When name contains a path separator (e.g. "res/tilemap.bin"), also - # try the basename since by_name indexes filenames without directories - if "/" in name: - name_base = name.rsplit("/", 1)[-1] - if name_base and name_base not in names_to_try: - names_to_try.append(name_base) - - # When dest_hint contains a path, also try its basename as a name - # (handles emulator profiles where name: is descriptive and path: is - # the actual filename, e.g. name: "MDA font ROM", path: "mda.rom") - own_names = list(names_to_try) - if dest_hint: - hint_base = dest_hint.rsplit("/", 1)[-1] if "/" in dest_hint else dest_hint - if hint_base and hint_base not in names_to_try: - names_to_try.append(hint_base) - + return _resolve_layout( + file_entry, db, zip_contents, dest_hint, + depth=_depth, data_dir_registry=data_dir_registry, + ) md5_list = parse_md5_list(file_entry.get("md5")) - files_db = db.get("files", {}) by_md5 = db.get("indexes", {}).get("by_md5", {}) # A value cut short stands for the one held md5 it starts, and only # then (cut_md5_owner): the dump it names is still name-guarded below. @@ -1705,248 +2530,58 @@ def resolve_local_file( cut: owner for cut in md5_list if len(cut) < 32 and (owner := cut_md5_owner(cut, by_md5)) } - md5_list = [cut_owners.get(value, value) for value in md5_list] - sha1_candidates = [ - str(value).strip().lower() - for value in (sha1 if isinstance(sha1, list) else [sha1] if sha1 else []) - if str(value).strip() - ] - sha256_raw = file_entry.get("sha256") - sha256_values = sha256_raw if isinstance(sha256_raw, list) else [sha256_raw] - sha256_candidates = [ - candidate.strip().lower() - for value in sha256_values - if value - for candidate in str(value).split(",") - if len(candidate.strip()) == 64 - ] - # One value, a list, or a comma-separated string, like the other hashes. - crc_values = file_entry.get("crc32") or [] - # Kept in the order declared, which is the order a lookup tries them. - crc_candidates = dict.fromkeys( - candidate.strip().lower().removeprefix("0x") - for value in (crc_values if isinstance(crc_values, list) else [crc_values]) - for candidate in str(value).split(",") - if candidate.strip() - ) - declared_size = file_entry.get("size") - has_strong_hash = bool( - sha1_candidates or sha256_candidates or md5_list or crc_candidates - ) - by_name = db.get("indexes", {}).get("by_name", {}) - by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {}) - - def _record_match_status(match_sha1: str) -> str | None: - """Return hash evidence when a DB record satisfies every declaration.""" - entry = files_db.get(match_sha1) - if not entry: - return None - statuses: list[str] = [] - if sha1_candidates: - if match_sha1.lower() not in sha1_candidates: - return None - statuses.append("sha1_exact") - if sha256_candidates: - if str(entry.get("sha256", "")).lower() not in sha256_candidates: - return None - statuses.append("sha256_exact") - # With zipped_file the MD5 identifies the member, not the container. - if md5_list and not zipped_file: - actual_md5 = str(entry.get("md5", "")).lower() - if actual_md5 not in md5_list: - return None - statuses.append("md5_exact") - if crc_candidates: - if str(entry.get("crc32", "")).lower() not in crc_candidates: - return None - if declared_size is not None: - allowed_sizes = ( - declared_size if isinstance(declared_size, list) else [declared_size] - ) - if entry.get("size") not in allowed_sizes: - return None - statuses.append("crc32_exact") - return statuses[0] if statuses else None - - # 1. SHA1 exact match (accept list-valued sha1 from profiles) - for cand in sha1_candidates: - if cand in files_db: - path = files_db[cand]["path"] - status = _record_match_status(cand) - if status and os.path.exists(path): - return path, status - - # 1b. SHA256 exact match (profiles hashed from sources that publish - # sha256, e.g. MesenCE). A full sha256 is a strong identifier. - if sha256_candidates: - by_sha256 = db.get("indexes", {}).get("by_sha256", {}) - for cand in sha256_candidates: - match = by_sha256.get(cand) - if match and match in files_db: - path = files_db[match]["path"] - status = _record_match_status(match) - if status and os.path.exists(path): - return path, status - - # 1c. CRC32 lookup, only when no stronger hash is declared. A declared - # size confirms it when available. A handful of emulators validate CRC32 - # alone, so those entries retain the same (weaker) evidence as the core. - if ( - crc_candidates - and not zipped_file - and not md5_list - and not sha1_candidates - and not sha256_candidates - ): - by_crc32 = db.get("indexes", {}).get("by_crc32", {}) - crc_matches: list[tuple[str, str]] = [] - for crc in crc_candidates: - match = by_crc32.get(crc) - if match and match in files_db: - path = files_db[match]["path"] - status = _record_match_status(match) - if status and os.path.exists(path): - crc_matches.append((path, status)) - # A primary copy over a .variants/ one, as everywhere else. - for path, status in crc_matches: - if "/.variants/" not in path: - return path, status - if crc_matches: - return crc_matches[0] - - # 2. MD5 direct lookup (skip for zipped_file: md5 is inner ROM, not container) - # Guard: only accept if the found file's name matches the requested name - # (or is a .variants/ derivative). Prevents cross-contamination when an - # unrelated file happens to share the same MD5 in the index. - _name_set = set(names_to_try) - - def _md5_name_ok(candidate_path: str) -> bool: - bn = os.path.basename(candidate_path) - if bn in _name_set: - return True - # .variants/ pattern: filename like "neogeo.zip.fc398ab4" - return any(bn.startswith(n + ".") for n in _name_set) - # A frontend that hashes an archive by its members (Recalbox) never reads # the container's own md5: neocd.bin's md5 is also the composite of a # one-member neocdz.zip, and the raw ROM shipped under the archive's name. composite_only = file_entry.get("zip_digest") == "composite" + q = _lookup( + file_entry, db, _name_as_hint(file_entry.get("name", ""), dest_hint), + [cut_owners.get(value, value) for value in md5_list], + composite_only=composite_only, + ) + has_strong_hash = q.has_strong_hash + # Guard of step 2: only accept if the found file's name matches the + # requested name (or is a .variants/ derivative). Prevents + # cross-contamination when an unrelated file happens to share the same + # MD5 in the index. + _md5_name_ok = functools.partial(_named_or_variant, frozenset(q.names_to_try)) - if md5_list and not zipped_file and not composite_only: - for md5_candidate in md5_list: - sha1_match = by_md5.get(md5_candidate) - if sha1_match and sha1_match in files_db: - path = files_db[sha1_match]["path"] - # A full md5 as declared is a strong identifier: trusted - # without name guard. One completed from a cut value still - # needs the name check to avoid cross-contamination. - status = _record_match_status(sha1_match) - if status and os.path.exists(path): - if md5_candidate not in cut_owners.values() or _md5_name_ok(path): - return path, status + found = ( + # 1. SHA1 exact match (accept list-valued sha1 from profiles) + _by_sha1(q) + # 1b. SHA256 exact match (profiles hashed from sources that publish + # sha256, e.g. MesenCE). A full sha256 is a strong identifier. + or _by_sha256(q) + # 1c. CRC32 lookup, only when no stronger hash is declared. A declared + # size confirms it when available. A handful of emulators validate CRC32 + # alone, so those entries retain the same (weaker) evidence as the core. + or _by_crc32(q) + # 2. MD5 direct lookup (skip for zipped_file: md5 is inner ROM, not container) + # A full md5 as declared is a strong identifier: trusted without + # name guard. One completed from a cut value still needs the name + # check to avoid cross-contamination. + or next( + ( + (path, status) + for path, status, md5_candidate in _md5_hits(q) + if md5_candidate not in cut_owners.values() or _md5_name_ok(path) + ), + None, + ) + ) + if found: + return found # 2b. Path suffix lookup is useful for same-named regional files, but it # is identity evidence only when no content hash was declared. A stale # or incorrect destination can therefore never mask a hash mismatch. - own_file_absent = False - if dest_hint and by_path_suffix: - # A destination is written from the emulator's point of view - # ("pcsx2/resources/GameIndex.yaml") and the index from the repo's - # layout, so the two meet on a tail rather than on the whole string. - # Longest tail first, and never down to the bare filename: that is the - # weaker step below, and five files answer to GameIndex.yaml. - # Two kinds of ambiguity appear once every tail is indexed. A - # shortened tail can be claimed by several emulators shipping the same - # asset tree, and it then proves nothing: skip it. The full tail can be - # claimed twice as well, one storing it at the root of its own - # directory and one nested deeper. There the file whose path carries - # the least on top of the destination is the one that IS the - # destination. - # The descent drops at most one leading segment. A destination and the - # tree differ by the wrapper directory at most. Beyond that the tail - # stops describing this file and starts describing whichever emulator - # happens to store the same asset tree. - hint_parts = dest_hint.split("/") - # The asking profile and the destination's own directories both name - # whose tree a copy may come from. - owners = _owner_tokens(file_entry) | _affinity_tokens("/".join(hint_parts[:-1])) - for start in range(min(2, len(hint_parts) - 1)): - tail = "/".join(hint_parts[start:]) - candidates = _rank_tail_candidates( - by_path_suffix.get(tail, []), start, tail, files_db, owners, - frozenset(_owner_tokens(file_entry)), - ) - raw = by_path_suffix.get(tail, []) - if start and len(raw) > 1: - # Ambiguity is read before the foreign trees are set aside: - # PCSX2x6's bin/resources/GameIndex.yaml met four copies - # under resources/GameIndex.yaml, three in other emulators' - # trees, and the fourth (PCSX2's console database, not - # PCSX2x6's arcade one) passed for proof. Only the asker's own - # tree still answers a tail several files share. - candidates = [ - h for h in candidates - if _own_tree(files_db.get(h, {}).get("path", ""), owners) - ] - if start and len(candidates) > 1: - continue - # The index names the file this destination designates. Not on - # disk, it is a release asset the checkout does not hold, and no - # other file of that name is it. - if not start and candidates and not any( - os.path.exists(files_db.get(h, {}).get("path", "")) - for h in candidates - ): - own_file_absent = True - for match_sha1 in candidates: - if match_sha1 not in files_db: - continue - path = files_db[match_sha1]["path"] - if not os.path.exists(path): - continue - if not has_strong_hash: - # A path names the file, the size the code checks still - # bounds it, as on the name step: ZEsarUX's 48 KB - # cpc6128.rom is not cap32's 32 KB one at the same tail. - if not name_match_size_ok( - file_entry, files_db[match_sha1].get("size") - ) or not adler32_fits(file_entry, path, db) or not content_fits( - file_entry, path - ): - continue - return path, "path_exact" - status = _record_match_status(match_sha1) - if status: - return path, status - - # 2c. The same tail in a data directory. by_path_suffix indexes bios/ - # only, so AmberELEC's Machines/MSX - Arabic/config.ini fell through to - # the name step and got msx-emu's ColecoVision config.ini, while - # data/bluemsx held blueMSX's own at that very path. A platform - # declaration is resolved without a hint, and its destination is that - # path. The descent and the ambiguity rule are those of the bios/ tails. - # A profile's entry is not asked here: it names its owner, the name step - # sends it to its data directories when another emulator's copy answers, - # and a dump it declares outranks the free one its tree bundles at the - # same path (Dolphin's dsp_coef.bin over Sys/GC's). - tail_hint = dest_hint or str(file_entry.get("destination") or "") - if ( - tail_hint - and data_dir_registry - and not has_strong_hash - and not _owner_tokens(file_entry) - ): - hit = _data_dir_tail(tail_hint, data_dir_registry, file_entry, db) - if hit: - return hit, "path_exact" + found, own_file_absent = _by_path_suffix(q) + # 2c. The same tail in a data directory. + found = found or _by_data_dir_tail(q, data_dir_registry) + if found: + return found # 3. No MD5 = any file with that name or alias (existence check) - def _size_ok(match_sha1: str) -> bool: - record = files_db.get(match_sha1, {}) - return name_match_size_ok(file_entry, record.get("size")) and adler32_fits( - file_entry, record.get("path", ""), db - ) and content_fits(file_entry, record.get("path", "")) - # An entry the profile documents as unsourceable is one the collection # cannot hold: a font that only exists inside a paid package, cheat codes # written per title. A file answering to its name is therefore a homonym @@ -1958,324 +2593,52 @@ def resolve_local_file( # A platform's own hashless entry whose system names a maker takes no copy # filed under another maker: AmberELEC's nec-pc-88 DISK.ROM, which QUASI88 # reads as the 2 KB PC-88 disk ROM, got the 16 KB MSX one by name. - makers = frozenset() if has_strong_hash else system_makers(file_entry, db) + makers: frozenset[str] = frozenset() if has_strong_hash else system_makers(file_entry, db) if not has_strong_hash and not unsourceable: - candidates = [] - # The entry's own names first, the destination's basename only when - # none of them answers. melonDS Nightly's dsi_nand.bin is read at - # dsi/nand.bin: with the DSi image absent from the checkout, the - # basename let the Wii nand.bin outrank the entry's own DSi variant. - # A name whose held file no declaration proves, while declarations - # of that name prove another dump beside it, means that dump: the - # DSi devkit boot ROMs filed as dsi_bios7.bin went to RetroBat. - by_proven_name = db.get("indexes", {}).get("by_proven_name", {}) - for tier in (own_names, names_to_try[len(own_names):]): - for try_name in tier: - for match_sha1 in ( - by_proven_name.get(try_name) or by_name.get(try_name, []) - ): - if match_sha1 in files_db and _size_ok(match_sha1): - path = files_db[match_sha1]["path"] - if os.path.exists(path) and path not in candidates: - candidates.append(path) - if candidates: - break - if candidates and all("/.variants/" in p for p in candidates): - # Only variants answer the exact casing, but the primary they - # stand in for may be stored under another one: x1 asked for - # IPLROM.X1 and got Recalbox's second md5 while iplrom.x1, the - # dump every platform pins, sat in the same directory. A primary - # counts here only in a variant's own directory and under its own - # file name: an alias (iplrom.x1t names a font in System.dat) or - # another machine's font.rom is not that file. - homes = {p.split("/.variants/", 1)[0] for p in candidates} - folded = _casefold_name_index(by_name) - for try_name in names_to_try: - wanted = try_name.rsplit("/", 1)[-1].casefold() - for match_sha1 in folded.get(try_name.casefold(), []): - path = files_db.get(match_sha1, {}).get("path", "") - if ( - "/.variants/" not in path - and os.path.dirname(path) in homes - and os.path.basename(path).casefold() == wanted - and _size_ok(match_sha1) - and os.path.exists(path) - and path not in candidates - ): - candidates.append(path) - owners = _owner_tokens(file_entry) - # Only another emulator's tree answers the exact casing: what it - # holds there says nothing about this entry's file. - exact_foreign = bool(candidates) and all( - _foreign_tree(p, owners) for p in candidates - ) - if not candidates or exact_foreign: - # Case-insensitive fallback: upstream platforms disagree on - # casing (VEC_MineStorm.vec vs VEC_Minestorm.vec). Two casings - # can name two contents (FONT.ROM and font.rom), so this only - # runs when no casing matches exactly, or when only another - # emulator's tree does: xm6typeg got XM6 Utility's synthesized - # SCSIINROM.DAT while the X68000 dump sat as scsiinrom.dat. - # Another casing in another emulator's tree proves nothing: - # reminiscence's music module reunion took skyline's - # zoneinfo/Indian/Reunion. - folded = _casefold_name_index(by_name) - for try_name in names_to_try: - for match_sha1 in folded.get(try_name.casefold(), []): - if match_sha1 in files_db and _size_ok(match_sha1): - path = files_db[match_sha1]["path"] - if _foreign_tree(path, owners): - continue - if os.path.exists(path) and path not in candidates: - candidates.append(path) - # A platform entry names no profile, but a system that lists its - # cores says whose files it asks for. A name only another emulator's - # tree answers is no evidence, and the data directories hold those - # emulators' trees too: EmuELEC's VVVVVV data.zip was served xrick's - # archive of the same name, then xrick's data directory copy. - core_owners = { - token - for core in file_entry.get("platform_cores") or () - for token in _affinity_tokens(str(core)) - } - if ( - not owners - and core_owners - and candidates - and all(_foreign_tree(p, core_owners) for p in candidates) - ): - candidates = [] - unsourceable = True - if makers and candidates: - candidates = [p for p in candidates if not other_maker(p, makers, db)] - if not candidates: - # The name belongs to another maker's file here. An emulator - # of this system may still read it as an alias of one of its - # own files, an alias by_name leaves out because a primary - # already carries the name: QUASI88 reads DISK.ROM as - # n88sub.rom. - shadowed = db.get("indexes", {}).get("by_shadowed_alias", {}) - for try_name in own_names: - for match_sha1 in shadowed.get(try_name, []): - path = files_db.get(match_sha1, {}).get("path", "") - if ( - _maker_folder(path, str(db.get("bios_dir") or "bios")) - in makers - and _size_ok(match_sha1) - and os.path.exists(path) - and path not in candidates - ): - candidates.append(path) - if candidates: - if zipped_file: - candidates = [p for p in candidates if ".zip" in os.path.basename(p)] - members = file_entry.get("members") or contents_members(file_entry) - if members or (len(candidates) > 1 and name.casefold().endswith(".zip")): - # Another emulator's own copy takes no part in the ranking: - # Demul's naomi.zip holds more NAOMI BIOS rows than any MAME - # set and broke the superset the MAME cores were served. - candidates = [ - p for p in candidates if not _foreign_tree(p, owners) - ] or candidates - if members: - candidates = _holding_members(candidates, members) - elif len(candidates) > 1 and name.casefold().endswith(".zip"): - candidates = _covering_archives(candidates) - candidates = _by_affinity(candidates, file_entry, dest_hint) - best = candidates[0] if candidates else "" - # A copy outside another emulator's tree comes first: the - # affinity read pcsx2 in bios/Other/armsx2/pcsx2/ and served - # upstream PCSX2 the patches.zip of ARMSX2. - candidates = [ - p for p in candidates if not _foreign_tree(p, owners) - ] or candidates - primary = [p for p in candidates if "/.variants/" not in p] - if primary or candidates: - chosen = primary[0] if primary else candidates[0] - # The best of them is another emulator's own copy, served or - # set aside: the name says nothing about this profile's file, - # and a data directory it reads may hold it. Dolphin got - # Dolphin-MMJR's codehandler.bin while data/dolphin-sys held - # its own, and blueMSX got the 16 KB RS232.ROM once msx-emu's - # 8 KB copy was set aside, while data/bluemsx held its own, - # and MSX2P.ROM of another dump once only msx-emu answered - # the exact casing. - if data_dir_registry and (exact_foreign or _foreign_tree(best, owners)): - hit, _mismatch = _resolve_in_data_dirs( - names_to_try, data_dir_registry, - functools.partial( - declared_hash_verdict, - has_strong_hash=False, - sha1_candidates=set(), - sha256_candidates=set(), - md5_list=[], - crc_candidates=set(), - zipped_file=zipped_file, - declared_size=declared_size, - file_entry=file_entry, - db=db, - ), - ) - if hit: - return hit - return chosen, "name_exact" + found, unsourceable = _by_name(q, makers, data_dir_registry) + if found: + return found # 4. Name + alias fallback with md5_composite + direct MD5 per candidate - md5_set = set(md5_list) - named: list[tuple[str, str, int | None]] = [] - seen_paths = set() - for try_name in names_to_try: - for match_sha1 in by_name.get(try_name, []): - if match_sha1 in files_db: - entry = files_db[match_sha1] - path = entry["path"] - if os.path.exists(path) and path not in seen_paths: - seen_paths.add(path) - named.append( - (path, entry.get("md5", ""), entry.get("size")) - ) - - if zipped_file: - named = [c for c in named if ".zip" in os.path.basename(c[0])] - # Another maker's file is no mismatch of this one, it is another file. - named = [c for c in named if not other_maker(c[0], makers, db)] - # A size the emulator itself verifies settles a name collision, so a - # candidate that fits is preferred over one that does not: "ROM" answers - # both an Apple IIgs image and a Macintosh one. It ranks rather than - # excludes, because a present file of the wrong size is reported as - # present and untested, and dropping it would report it as absent. - sized = [ - c for c in named - if name_match_size_ok(file_entry, c[2]) and content_fits(file_entry, c[0]) - ] - if sized: - named = sized - + named = _named_candidates(q, makers) if named: - if md5_set and not (sha1_candidates or sha256_candidates or crc_candidates): - if composite_only: - named.sort(key=lambda c: "/.variants/" in c[0]) - for path, db_md5, _size in named: - if ".zip" in os.path.basename(path): - try: - composite = md5_composite(path).lower() - # A zipped_file md5 is the member's: one member of - # another name has the same composite, and Batocera - # looks the member up by name. - if composite in md5_set and ( - not zipped_file - or check_inside_zip(path, zipped_file, composite) == "ok" - ): - return path, "md5_composite_exact" - except (zipfile.BadZipFile, OSError) as exc: - _warn_unreadable_archive(path, exc) - if db_md5.lower() in md5_set and not composite_only: - return path, "md5_exact" - # When zipped_file is set, only accept candidates that contain it - if zipped_file: - valid = [] - for path, m, size in named: - try: - with zipfile.ZipFile(path) as zf: - inner_names = {n.casefold() for n in zf.namelist()} - if zipped_file.casefold() in inner_names: - valid.append((path, m, size)) - except (zipfile.BadZipFile, OSError) as exc: - _warn_unreadable_archive(path, exc) - # The archive whose member carries the declared md5 is the one: - # neogeo.zip is held twice, each with its own sfix.sfix, and the - # first by name was returned as a mismatch while the other matched. - for path, _m, _size in sorted(valid, key=lambda c: "/.variants/" in c[0]): - if any(check_inside_zip(path, zipped_file, md5) == "ok" for md5 in md5_list): - return path, "zip_exact" - if valid: - primary = [c[0] for c in valid if "/.variants/" not in c[0]] - return (primary[0] if primary else valid[0][0]), "hash_mismatch" - # No candidate contains the zipped_file: fall through to step 5 + found = _named_md5_match(q, named) + if q.zipped_file: + found = found or _zipped_named(q, named, q.zipped_file) elif not unsourceable: - ordered = _by_affinity([c[0] for c in named], file_entry, dest_hint) - primary = [c for c in ordered if "/.variants/" not in c] - return (primary[0] if primary else ordered[0]), "hash_mismatch" + found = found or _ranked_mismatch(q, named) + if found: + return found # 5. zipped_file content match via pre-built index (last resort: # matches inner ROM MD5 across ALL ZIPs in the repo, so only use # when name-based resolution failed entirely) - if ( - zipped_file - and md5_list - and zip_contents - and not (sha1_candidates or sha256_candidates or crc_candidates) - ): - for md5_candidate in md5_list: - if md5_candidate in zip_contents: - zip_sha1 = zip_contents[md5_candidate] - if zip_sha1 in files_db: - path = files_db[zip_sha1]["path"] - if os.path.exists(path): - return path, "zip_exact" + found = _by_zip_contents(q, zip_contents) # MAME clone fallback: if a file was deduped, resolve via canonical. The # clone name is a name step like the others: an unsourceable entry skips # it, and the size the code checks travels with it (dedup only merges # identical bytes, so the canonical copy has the clone's size). if _depth < 3 and not has_strong_hash and not unsourceable: - clone_map = get_mame_clone_map(db.get("bios_dir")) - canonical = clone_map.get(name) - if canonical and canonical != name: - canonical_entry = { - field: file_entry[field] - for field in ( - "size", "min_size", "max_size", "size_multiple", "validation", - *sorted(CONTENT_CHECKS), - ) - if field in file_entry - } - canonical_entry["name"] = canonical - result = resolve_local_file( - canonical_entry, - db, - zip_contents, - dest_hint, - _depth=_depth + 1, - data_dir_registry=data_dir_registry, - ) - if result[0] and result[1] != "hash_mismatch": - return result[0], "mame_clone" + found = found or _by_mame_clone(q, zip_contents, _depth, data_dir_registry) + if found: + return found # Data directory fallback: scan data/ caches for matching filename - data_dir_mismatch: str | None = None # Without a hash the cache walk matches on filename alone, which is the # step an unsourceable entry has to skip: hiscore.dat names one file per # driver set, so FBNeo's copy would answer for MAME's. if data_dir_registry and (has_strong_hash or not unsourceable): - verdict = functools.partial( - declared_hash_verdict, - has_strong_hash=has_strong_hash, - sha1_candidates=sha1_candidates, - sha256_candidates=sha256_candidates, - md5_list=md5_list, - crc_candidates=set(crc_candidates), - zipped_file=zipped_file, - declared_size=declared_size, - file_entry=file_entry, - db=db, - ) - hit, data_dir_mismatch = _resolve_in_data_dirs( - names_to_try, data_dir_registry, verdict - ) - if hit: - return hit + found, data_dir_mismatch = _in_data_dirs(q, data_dir_registry) + if found: + return found if data_dir_mismatch and not unsourceable: return data_dir_mismatch, "hash_mismatch" - agnostic = _resolve_agnostic(file_entry, files_db, has_strong_hash) - if agnostic: - return agnostic - - return None, "not_found" + return _resolve_agnostic(file_entry, q.files_db, has_strong_hash) or (None, "not_found") _mame_clone_map_cache: dict[str, dict[str, str]] = {} @@ -3262,6 +3625,137 @@ def platform_layouts( ] +@dataclass +class _StandaloneLaunches: + """Where a platform's launches of a standalone emulator read its files.""" + + emu_name: str + profile: dict + standalone_cores: set[str] + per_system: bool + index: Mapping[str, set[str]] + # A profile system the platform launches under a system of its own, as + # its list says for one entry, is launched there for every entry. + family: dict[str, set[str]] + # The systems the launcher records name. + named_systems: frozenset[str] + # The layout folders a search setting stands for (standalone_pools). + pool_folders: set[str] + # Bindings can depend on the system an entry is launched for, so each + # set of launch systems gets its own. + by_systems: dict[frozenset[str], dict[str, tuple[str, str]]] = dataclasses.field(default_factory=dict) + + @classmethod + def of(cls, emu_name: str, profile: dict, standalone_cores: set[str]) -> _StandaloneLaunches: + names = {emu_name, *(str(c) for c in profile.get("cores") or [])} + per_system = bool( + profile.get("standalone_directories") or profile.get("standalone_pools") + ) and any(h.systems and h.emulator in names for h in _handed(standalone_cores)) + index = system_file_index(standalone_cores) if per_system else {} + # A profile system the platform launches under a system of its own, as + # its list says for one entry, is launched there for every entry: + # Recalbox lists mc10.rom under trs80coco, so alice.rom is read there. + family: dict[str, set[str]] = {} + for f in (profile.get("files") or []) if per_system else []: + if isinstance(f, dict): + own = entry_launch_systems(f, {}) + for system in own: + family.setdefault(system, set()).update(entry_launch_systems(f, index) - own) + + # The systems the launcher records name: a launch for one of them reads + # the folder its record gives, every other launch the folder the records + # naming none give. + named_systems = frozenset().union(*( + h.systems for h in _handed(standalone_cores) if h.emulator in names + )) if per_system else frozenset() + + # The layout folders a search setting stands for (standalone_pools): + # bound, the launcher passes the setting and the default is not read. + from launchers import pool_folders as _pool_folders + + pool_folders = {v.strip("/") for v in _pool_folders(profile).values()} - {""} + return cls( + emu_name, profile, standalone_cores, per_system, index, family, + named_systems, pool_folders, + ) + + def launch_systems(self, entry: dict) -> frozenset[str]: + systems: frozenset[str] = frozenset() + if self.per_system: + own = entry_launch_systems(entry, {}) + systems = entry_launch_systems(entry, self.index) + if systems == own: + systems = systems.union(*(self.family.get(s, set()) for s in own)) + if systems == own: + # The platform's list names none of the entry's names: its + # own system selects the launch that offers it as a machine + # (RetroBat runs XRoar's coco3 under coco). + systems = systems.union(*( + self.index.get(MACHINE_KEY + _norm_system_id(s), set()) for s in own + )) + return systems + + def bindings_for(self, systems: frozenset[str]) -> dict[str, tuple[str, str]]: + if systems not in self.by_systems: + self.by_systems[systems] = standalone_bindings_for( + self.emu_name, self.profile, self.standalone_cores, systems + ) + return self.by_systems[systems] + + def bindings_of(self, entry: dict) -> dict[str, tuple[str, str]]: + return self.bindings_for(self.launch_systems(entry)) + + def passed_setting(self, entry: dict) -> bool: + layout = str(standalone_layout_path(entry, self.profile) or "") + bindings = self.bindings_of(entry) + return any( + folder in bindings and (layout == folder or layout.startswith(folder + "/")) + for folder in self.pool_folders + ) + + def destinations(self, entry: dict) -> list[tuple[str, str] | None]: + """Each place the entry's launches read it from, in launch order. + + An entry of a system a record names is read where that record puts + it. One also launched for systems no record names is read, for those + launches, where the records naming none put it: EmuELEC starts + AdvanceMAME with dir_rom roms/arcade for arcade and roms/mame for + mame and cps1-3 (advmame.sh:26-30), and an arcade set is read in both. + """ + systems = self.launch_systems(entry) + found = [standalone_destination(entry, self.profile, self.bindings_for(systems))] + # A system the platform's list or machines put the entry under + # stands for the entry's own ids: XRoar's coco3 is launched as coco. + own = entry_launch_systems(entry, {}) + launched = (systems - own) | (own & self.named_systems) if systems != own else systems + if launched & self.named_systems and launched - self.named_systems: + generic = standalone_destination(entry, self.profile, self.bindings_for(frozenset())) + if generic not in found: + found.append(generic) + return found + + def placed_files(self) -> list: + """The profile's files, each layout entry at the folders its launches read.""" + files = [] + for f in self.profile.get("files") or []: + if not isinstance(f, dict) or standalone_layout_path(f, self.profile) is None: + files.append(f) + continue + places = [p for p in self.destinations(f) if p is not None and p[0] != "outside"] + if not places: + files.append({**f, "unplaced": OUTSIDE_BIOS_FOLDER}) + continue + moved = f + if f.get("bundled") and self.passed_setting(f): + # The copy installed with the emulator sits where the setting + # pointed before the launcher moved it: RetroBat passes MAME + # -hash bios/mame/hash (Mame64.Generator.cs:172, 177-178), and + # the hash/ beside mame.exe is no longer read. + moved = {k: v for k, v in f.items() if k != "bundled"} + files.extend(_placed_entry(moved, self.profile, placed) for placed in places) + return files + + def _build_layouts( emu_name: str, profile: dict, standalone_cores: set[str] ) -> list[tuple[dict, bool]]: @@ -3278,97 +3772,13 @@ def _build_layouts( return [(profile, False)] return [(system_dir_view(profile, d), False) for d in directories] standalone = profile - # Bindings can depend on the system an entry is launched for, so each - # set of launch systems gets its own. - by_systems: dict[frozenset[str], dict[str, tuple[str, str]]] = {} - names = {emu_name, *(str(c) for c in profile.get("cores") or [])} - per_system = bool( - profile.get("standalone_directories") or profile.get("standalone_pools") - ) and any(h.systems and h.emulator in names for h in _handed(standalone_cores)) - index = system_file_index(standalone_cores) if per_system else {} - # A profile system the platform launches under a system of its own, as - # its list says for one entry, is launched there for every entry: - # Recalbox lists mc10.rom under trs80coco, so alice.rom is read there. - family: dict[str, set[str]] = {} - for f in (profile.get("files") or []) if per_system else []: - if isinstance(f, dict): - own = entry_launch_systems(f, {}) - for system in own: - family.setdefault(system, set()).update(entry_launch_systems(f, index) - own) - - # The systems the launcher records name: a launch for one of them reads - # the folder its record gives, every other launch the folder the records - # naming none give. - named_systems = frozenset().union(*( - h.systems for h in _handed(standalone_cores) if h.emulator in names - )) if per_system else frozenset() - - def launch_systems(entry: dict) -> frozenset[str]: - systems: frozenset[str] = frozenset() - if per_system: - own = entry_launch_systems(entry, {}) - systems = entry_launch_systems(entry, index) - if systems == own: - systems = systems.union(*(family.get(s, set()) for s in own)) - if systems == own: - # The platform's list names none of the entry's names: its - # own system selects the launch that offers it as a machine - # (RetroBat runs XRoar's coco3 under coco). - systems = systems.union(*( - index.get(MACHINE_KEY + _norm_system_id(s), set()) for s in own - )) - return systems - - def bindings_for(systems: frozenset[str]) -> dict[str, tuple[str, str]]: - if systems not in by_systems: - by_systems[systems] = standalone_bindings_for( - emu_name, profile, standalone_cores, systems - ) - return by_systems[systems] - - def bindings_of(entry: dict) -> dict[str, tuple[str, str]]: - return bindings_for(launch_systems(entry)) - - # The layout folders a search setting stands for (standalone_pools): - # bound, the launcher passes the setting and the default is not read. - from launchers import pool_folders as _pool_folders - - pool_folders = {v.strip("/") for v in _pool_folders(profile).values()} - {""} - - def passed_setting(entry: dict) -> bool: - layout = str(standalone_layout_path(entry, profile) or "") - bindings = bindings_of(entry) - return any( - folder in bindings and (layout == folder or layout.startswith(folder + "/")) - for folder in pool_folders - ) - - def destinations(entry: dict) -> list[tuple[str, str] | None]: - """Each place the entry's launches read it from, in launch order. - - An entry of a system a record names is read where that record puts - it. One also launched for systems no record names is read, for those - launches, where the records naming none put it: EmuELEC starts - AdvanceMAME with dir_rom roms/arcade for arcade and roms/mame for - mame and cps1-3 (advmame.sh:26-30), and an arcade set is read in both. - """ - systems = launch_systems(entry) - found = [standalone_destination(entry, profile, bindings_for(systems))] - # A system the platform's list or machines put the entry under - # stands for the entry's own ids: XRoar's coco3 is launched as coco. - own = entry_launch_systems(entry, {}) - launched = (systems - own) | (own & named_systems) if systems != own else systems - if launched & named_systems and launched - named_systems: - generic = standalone_destination(entry, profile, bindings_for(frozenset())) - if generic not in found: - found.append(generic) - return found + launches = _StandaloneLaunches.of(emu_name, profile, standalone_cores) layout_entries = [ f for f in profile.get("files") or [] if isinstance(f, dict) and standalone_layout_path(f, profile) is not None ] - if any(bindings_of(f) for f in layout_entries): + if any(launches.bindings_of(f) for f in layout_entries): # The standalone view carries the platform's destination, so every # reader of standalone_path (builder, manifest, verify, slots) places # the file in the folder the platform hands the emulator. @@ -3376,24 +3786,7 @@ def _build_layouts( # platform keeps outside the BIOS tree: UAE4All2's kick.rom in # RetroPie's $md_inst. It is marked, never left at the BIOS root # where the emulator does not read it. - files = [] - for f in profile.get("files") or []: - if not isinstance(f, dict) or standalone_layout_path(f, profile) is None: - files.append(f) - continue - places = [p for p in destinations(f) if p is not None and p[0] != "outside"] - if not places: - files.append({**f, "unplaced": OUTSIDE_BIOS_FOLDER}) - continue - moved = f - if f.get("bundled") and passed_setting(f): - # The copy installed with the emulator sits where the setting - # pointed before the launcher moved it: RetroBat passes MAME - # -hash bios/mame/hash (Mame64.Generator.cs:172, 177-178), and - # the hash/ beside mame.exe is no longer read. - moved = {k: v for k, v in f.items() if k != "bundled"} - files.extend(_placed_entry(moved, profile, placed) for placed in places) - standalone = {**profile, "files": files} + standalone = {**profile, "files": launches.placed_files()} dual = {c.removeprefix(DUAL_MODE_PREFIX) for c in standalone_cores if c.startswith(DUAL_MODE_PREFIX)} if "libretro" in str(profile.get("type", "")) and dual & { @@ -3641,6 +4034,125 @@ def _rom_search_sets( return frozenset(found | members) +def _search_reads(emu_name: str, searches: list, name: str) -> list[tuple[str, str]]: + """The (tree, folder) places a passed ROM search reads this set from.""" + stem = name.rsplit(".", 1)[0] + return sorted({ + tuple(where) for _emu, where, system, machines, any_machine, _ref, _build in searches + if where and stem in rom_search_sets(emu_name, system, machines, any_machine) + }) + + +def _roms_entry(entry: dict, tree: str, folder: str, rel: str) -> dict: + """The entry placed in a roms folder.""" + # Below the roms root inside the install tree (EmuELEC's + # /storage/roms): a plain dest the platform prefix skips, as a + # standalone entry placed there (_placed_entry). + where: dict[str, object] = ( + {"unprefixed": True} if tree == "install" else {"root": ROMS_ROOT} + ) + return {**entry, **where, "path": f"{folder}/{rel}", "layout_path": rel} + + +def _content_folder_boards(tags: list[str], names: set[str]) -> dict[tuple, set[str] | None]: + """Each roms folder the platform launches the core from, with its boards.""" + # A place keeps the boards its core is offered on there, every board + # when one folder offers it everywhere. + on_boards: dict[tuple, set[str] | None] = {} + for core, _folder, where, on in ( + json.loads(t[len(CONTENT_FOLDER_PREFIX):]) + for t in tags if t.startswith(CONTENT_FOLDER_PREFIX) + ): + if core not in names or not where: + continue + place = tuple(where) + known = on_boards.get(place, set()) + on_boards[place] = None if on is None or known is None else known | set(on) + return on_boards + + +def _libretro_content_layout( + emu_name: str, view: dict, tags: list[str], names: set[str], searches: list, +) -> dict: + """The libretro layout with each file read beside the content placed there.""" + on_boards = _content_folder_boards(tags, names) + folders = sorted(on_boards) + # The folders a passed `-rompath` replaces the build's own search + # path with stand for these: libretro MAME hands MAME + # /mame/bios unless the content's command line names + # another (retro_init.cpp Set_Path_Option, execute_game_cmd). + from launchers import pool_folders + + pools = set(pool_folders({"standalone_pools": view.get("libretro_pools")}).values()) + out: list = [] + changed = False + for f in view.get("files") or []: + if not isinstance(f, dict): + out.append(f) + continue + if _content_load(f) != "content_dir" or f.get("category") == "game_data": + # Game data read beside the content is the game's own. + out.append(f) + parent, _, rel = str(f.get("path") or "").rpartition("/") + if searches and parent in pools and rel: + reads = _search_reads(emu_name, searches, rel) + changed |= bool(reads) + out.extend(_roms_entry(f, tree, folder, rel) for tree, folder in reads) + continue + changed = True + plain = _without_libretro_load(f) + if not folders: + out.append({**plain, "unplaced": OUTSIDE_BIOS_FOLDER}) + continue + rel = str(f.get("path") or f.get("name") or "") + out.extend( + {**_roms_entry(plain, tree, folder, rel), + **({"boards": sorted(on)} if (on := on_boards[(tree, folder)]) is not None else {})} + for tree, folder in folders + ) + return {**view, "files": out} if changed else view + + +def _standalone_content_layout(emu_name: str, view: dict, searches: list) -> dict: + """The standalone layout with each set a passed search reads placed there.""" + pools = {str(v).strip("/") for v in (view.get("standalone_pools") or {}).values()} + if not searches or "" not in pools: + return view + out: list = [] + changed = False + for f in view.get("files") or []: + layout = ( + (f.get("layout_path") or standalone_layout_path(f, view)) if isinstance(f, dict) else None + ) + if not layout or "/" in layout: + out.append(f) + continue + reads = _search_reads(emu_name, searches, layout) + if f.get("unplaced") != OUTSIDE_BIOS_FOLDER: + # A set a launcher record placed stays there: EmuDeck's + # mame.ini rompath is read when Steam ROM Manager starts MAME + # with no `-rompath` (tools/launchers/mame.sh), and ES-DE's + # commands read the folders they pass. + out.append(f) + held = {(f.get("root") or "", f.get("standalone_path") or "")} + extra = [ + _placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads + ] + extra = [e for e in extra if (e.get("root") or "", e["standalone_path"]) not in held] + changed |= bool(extra) + out.extend(extra) + continue + if not reads: + out.append(f) + continue + changed = True + placed = {k: v for k, v in f.items() if k != "unplaced"} + out.extend( + _placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads + ) + return {**view, "files": out} if changed else view + + def content_layout( emu_name: str, view: dict, standalone: bool, standalone_cores: Iterable[str], ) -> dict: @@ -3667,112 +4179,15 @@ def content_layout( if CONTENT_SCOPE_TAG not in tags: return view names = {_core_key(n) for n in {emu_name, *(str(c) for c in view.get("cores") or [])}} - files = view.get("files") or [] - out: list = [] - changed = False searches = [ json.loads(t[len(ROM_SEARCH_PREFIX):]) for t in tags if t.startswith(ROM_SEARCH_PREFIX) ] build = "standalone" if standalone else "libretro" searches = [s for s in searches if _core_key(s[0]) in names and s[6] == build] - - def search_reads(name: str) -> list[tuple[str, str]]: - stem = name.rsplit(".", 1)[0] - return sorted({ - tuple(where) for _emu, where, system, machines, any_machine, _ref, _build in searches - if where and stem in rom_search_sets(emu_name, system, machines, any_machine) - }) - - def roms_entry(entry: dict, tree: str, folder: str, rel: str) -> dict: - # Below the roms root inside the install tree (EmuELEC's - # /storage/roms): a plain dest the platform prefix skips, as a - # standalone entry placed there (_placed_entry). - where: dict[str, object] = ( - {"unprefixed": True} if tree == "install" else {"root": ROMS_ROOT} - ) - return {**entry, **where, "path": f"{folder}/{rel}", "layout_path": rel} - if not standalone: - # A place keeps the boards its core is offered on there, every board - # when one folder offers it everywhere. - on_boards: dict[tuple, set[str] | None] = {} - for core, _folder, where, on in ( - json.loads(t[len(CONTENT_FOLDER_PREFIX):]) - for t in tags if t.startswith(CONTENT_FOLDER_PREFIX) - ): - if core not in names or not where: - continue - place = tuple(where) - known = on_boards.get(place, set()) - on_boards[place] = None if on is None or known is None else known | set(on) - folders = sorted(on_boards) - # The folders a passed `-rompath` replaces the build's own search - # path with stand for these: libretro MAME hands MAME - # /mame/bios unless the content's command line names - # another (retro_init.cpp Set_Path_Option, execute_game_cmd). - from launchers import pool_folders - - pools = set(pool_folders({"standalone_pools": view.get("libretro_pools")}).values()) - for f in files: - if not isinstance(f, dict): - out.append(f) - continue - if _content_load(f) != "content_dir" or f.get("category") == "game_data": - # Game data read beside the content is the game's own. - out.append(f) - parent, _, rel = str(f.get("path") or "").rpartition("/") - if searches and parent in pools and rel: - reads = search_reads(rel) - changed |= bool(reads) - out.extend(roms_entry(f, tree, folder, rel) for tree, folder in reads) - continue - changed = True - plain = _without_libretro_load(f) - if not folders: - out.append({**plain, "unplaced": OUTSIDE_BIOS_FOLDER}) - continue - rel = str(f.get("path") or f.get("name") or "") - out.extend( - {**roms_entry(plain, tree, folder, rel), - **({"boards": sorted(on)} if (on := on_boards[(tree, folder)]) is not None else {})} - for tree, folder in folders - ) - return {**view, "files": out} if changed else view - pools = {str(v).strip("/") for v in (view.get("standalone_pools") or {}).values()} - if not searches or "" not in pools: - return view - for f in files: - layout = ( - (f.get("layout_path") or standalone_layout_path(f, view)) if isinstance(f, dict) else None - ) - if not layout or "/" in layout: - out.append(f) - continue - reads = search_reads(layout) - if f.get("unplaced") != OUTSIDE_BIOS_FOLDER: - # A set a launcher record placed stays there: EmuDeck's - # mame.ini rompath is read when Steam ROM Manager starts MAME - # with no `-rompath` (tools/launchers/mame.sh), and ES-DE's - # commands read the folders they pass. - out.append(f) - held = {(f.get("root") or "", f.get("standalone_path") or "")} - extra = [ - _placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads - ] - extra = [e for e in extra if (e.get("root") or "", e["standalone_path"]) not in held] - changed |= bool(extra) - out.extend(extra) - continue - if not reads: - out.append(f) - continue - changed = True - placed = {k: v for k, v in f.items() if k != "unplaced"} - out.extend( - _placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads - ) - return {**view, "files": out} if changed else view + return _libretro_content_layout(emu_name, view, tags, names, searches) + return _standalone_content_layout(emu_name, view, searches) def _content_load(entry: dict) -> str: @@ -4409,6 +4824,25 @@ def designated_profiles(profiles: dict[str, dict], names: set[str]) -> set[str]: return {profile for c in names for profile in index.get(c, {c})} +def _destination_cores(profiles: dict[str, dict]) -> dict[str, set[str]]: + """Each lowercased destination with a directory -> the cores reading it.""" + dest_cores: dict[str, set[str]] = {} + for name, p in profiles.items(): + if p.get("type") == "alias": + continue + for f in p.get("files", []): + for key in ("path", "standalone_path"): + dest = f.get(key) + if not isinstance(dest, str): + continue + if dest.endswith("/"): + dest += f.get("name", "") + dest = sanitize_pack_path(dest).lower() + if "/" in dest: + dest_cores.setdefault(dest, set()).add(name) + return dest_cores + + def system_core_reach( systems: dict[str, dict], profiles: dict[str, dict], @@ -4448,20 +4882,7 @@ def system_core_reach( # The evidence only keeps: a path shared with an off-target core says # nothing of the other files, and Batocera's bbc runs on MAME, which no # profile ties to bbcb.zip, while CLK reads two of its ROMs. - dest_cores: dict[str, set[str]] = {} - for name, p in profiles.items(): - if p.get("type") == "alias": - continue - for f in p.get("files", []): - for key in ("path", "standalone_path"): - dest = f.get(key) - if not isinstance(dest, str): - continue - if dest.endswith("/"): - dest += f.get("name", "") - dest = sanitize_pack_path(dest).lower() - if "/" in dest: - dest_cores.setdefault(dest, set()).add(name) + dest_cores = _destination_cores(profiles) reach: dict[str, set[str] | None] = {} for sys_id, sys_data in systems.items(): @@ -4498,7 +4919,7 @@ def filter_systems_by_target( return { sys_id: sys_data for sys_id, sys_data in systems.items() - if reach[sys_id] is None or reach[sys_id] & available + if (cores := reach[sys_id]) is None or cores & available } @@ -4680,11 +5101,6 @@ def expand_platform_declared_names(config: dict, db: dict) -> set[str]: return set(platform_declarations(config, db)) -import re - - - - # Validation and mode filtering: extracted to validation.py for SoC. # Re-exported below for backward compatibility. @@ -4841,68 +5257,6 @@ def _unknown_target_message(target: str, platforms: list[str], platforms_dir: st "lists the targets of one platform.") -# Re-exported so the existing call sites keep working while the -# modules above become the place to import from. -from safeparse import ( # noqa: E402,F401 - parse_untrusted_xml, - require_yaml, - yaml_load, - _pick_yaml_loader, - _YAML_LOADER, -) -from hashing import ( # noqa: E402,F401 - compute_hashes, - md5sum, - md5_composite, - parse_md5_list, - cut_md5_owner, - _ALL_ALGORITHMS, - _md5_composite_cache, -) -from ziptools import ( # noqa: E402,F401 - check_inside_zip, - build_zip_contents_index, - MAX_ZIP_MEMBERS, - MAX_ZIP_MEMBER_SIZE, - MAX_ZIP_TOTAL_SIZE, - MAX_ZIP_COMPRESSION_RATIO, - safe_extract_zip, - _zip_contents_cache, - _BOUNDED_RATIO_METHODS, - zip_member_crcs, - zip_member_names, -) -from artifacts import ( # noqa: E402,F401 - write_if_changed, - write_text_atomic, - copy_file_atomic, - plain_file_mode, - set_plain_mode, - ArtifactDirectoryMissing, - ArtifactLockBusy, - artifact_lock, - hold_artifact_lock, - hold_repository_outputs, - publish_hold, - repository_output_lock, - _TIMESTAMP_PATTERNS, - _strip_timestamps, -) -from largefiles import ( # noqa: E402,F401 - LARGE_FILES_RELEASE, - LARGE_FILES_REPO, - LARGE_FILES_CACHE, - fetch_large_file, -) -from dumpcatalog import ( # noqa: E402,F401 - DEFAULT_PROVENANCE_DIR, - load_provenance_snapshots, - build_provenance_index, - annotate_provenance, - write_provenance_snapshot, -) - - def _exit_on_signal(signum: int, _frame: object) -> None: sys.exit(128 + signum) 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/dedup.py b/scripts/dedup.py index 97a198a7c..de3c83264 100644 --- a/scripts/dedup.py +++ b/scripts/dedup.py @@ -145,7 +145,7 @@ def _plan_group_removals( # True duplicates: same filename in multiple directories true_dupes_to_remove = [] - for name, name_paths in by_name.items(): + for name_paths in by_name.values(): if len(name_paths) > 1: name_paths.sort(key=path_priority) true_dupes_to_remove.extend(name_paths[1:]) @@ -194,6 +194,115 @@ def _plan_group_removals( return true_dupes_to_remove +def _read_clone_map(clone_path: str) -> object: + """The clone map an earlier run wrote, {} when there is none.""" + # Read before anything is removed: the map is cumulative, and a run that + # stopped on an unreadable one after deleting clones would lose them. + try: + with open(clone_path) as f: + return json.load(f) + except FileNotFoundError: + return {} + except json.JSONDecodeError as e: + raise SystemExit( + f"{clone_path} is not valid JSON ({e}). Restore it from git " + "before deduplicating again" + ) from e + + +def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]: + """Remove (or name, in a dry run) each copy beside the canonical file.""" + removed: list[str] = [] + for dup in true_dupes_to_remove: + if dup == canonical: + continue + if not os.path.exists(dup): + continue + if dry_run: + print(f" WOULD REMOVE: {dup}") + else: + try: + os.remove(dup) + except OSError as e: + print(f" WARNING: cannot remove {dup}: {e}") + continue + # Clean up empty .variants/ directories + parent = os.path.dirname(dup) + if os.path.basename(parent) == ".variants" and not os.listdir(parent): + os.rmdir(parent) + removed.append(dup) + return removed + + +def _settle_group(paths: list[str], true_dupes_to_remove: list[str], dry_run: bool) -> dict: + """Keep the best copy of one content and remove the others.""" + # Find the best canonical across all paths + all_paths = [p for p in paths if p not in true_dupes_to_remove] + if not all_paths: + # All copies were marked for removal: keep the best one + all_paths_sorted = sorted(paths, key=path_priority) + all_paths = [all_paths_sorted[0]] + true_dupes_to_remove = [p for p in paths if p != all_paths[0]] + + canonical = sorted(all_paths, key=path_priority)[0] + canonical_name = os.path.basename(canonical) + + all_names = set(os.path.basename(p) for p in paths) + alias_names = sorted(all_names - {canonical_name}) + + size = os.path.getsize(canonical) + removed = _remove_copies(canonical, true_dupes_to_remove, dry_run) + + if alias_names or true_dupes_to_remove: + action = "Would remove" if dry_run else "Removed" + dn = os.path.basename(canonical) + print(f" {dn} (keep: {canonical})") + if true_dupes_to_remove: + print(f" {action} {len(true_dupes_to_remove)} copies") + if alias_names: + print(f" MAME clones: {alias_names}") + return { + "canonical": canonical, + "removed": removed, + "aliases": alias_names, + "saved": size * len(removed), + } + + +def _remove_empty_dirs(bios_dir: str) -> int: + """Remove the directories the removals left empty, bottom up.""" + empty_cleaned = 0 + for root, dirs, files in os.walk(bios_dir, topdown=False): + if not files and not dirs and root != bios_dir: + os.rmdir(root) + empty_cleaned += 1 + return empty_cleaned + + +def _record_clone_map( + mame_clones: dict[str, dict], previous: object, clone_path: str, dry_run: bool +) -> None: + """Write the clone map, merged with what earlier runs recorded.""" + # A group is only visible while both copies are on disk, and this run + # has just deleted the clone. Writing only what was seen this time + # therefore erases every mapping an earlier run recorded, and the + # canonical zip stops answering to the names it stands in for. The + # older entries stay valid: their canonical file is still here. + if not dry_run and isinstance(previous, dict): + merged = dict(previous) + merged.update(mame_clones) + mame_clones = collapse_clone_chains(merged) + if dry_run: + print(f"\nWould write MAME clone map: {clone_path}") + else: + write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True)) + print(f"\nWrote MAME clone map: {clone_path}") + print( + f" {len(mame_clones)} canonical ZIPs with " + f"{sum(len(v['clones']) for v in mame_clones.values())} clones" + ) + + def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: """Remove true duplicates, map MAME device clones. @@ -208,21 +317,10 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: clone_path = os.path.join( os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json" ) - # Read before anything is removed: the map is cumulative, and a run that - # stopped on an unreadable one after deleting clones would lose them. - try: - with open(clone_path) as f: - previous = json.load(f) - except FileNotFoundError: - previous = {} - except json.JSONDecodeError as e: - raise SystemExit( - f"{clone_path} is not valid JSON ({e}). Restore it from git " - "before deduplicating again" - ) from e + previous = _read_clone_map(clone_path) sha1_groups = scan_duplicates(bios_dir) - results = {} + results: dict[str, dict] = {} total_removed = 0 total_saved = 0 mame_clones: dict[str, dict] = {} # canonical_name -> {sha1, clones: [names]} @@ -236,65 +334,13 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: if not true_dupes_to_remove: continue - # Find the best canonical across all paths - all_paths = [p for p in paths if p not in true_dupes_to_remove] - if not all_paths: - # All copies were marked for removal: keep the best one - all_paths_sorted = sorted(paths, key=path_priority) - all_paths = [all_paths_sorted[0]] - true_dupes_to_remove = [p for p in paths if p != all_paths[0]] - - canonical = sorted(all_paths, key=path_priority)[0] - canonical_name = os.path.basename(canonical) - - all_names = set(os.path.basename(p) for p in paths) - alias_names = sorted(all_names - {canonical_name}) - - size = os.path.getsize(canonical) - - results[sha1] = { - "canonical": canonical, - "removed": [], - "aliases": alias_names, - } - - for dup in true_dupes_to_remove: - if dup == canonical: - continue - if not os.path.exists(dup): - continue - if dry_run: - print(f" WOULD REMOVE: {dup}") - else: - try: - os.remove(dup) - except OSError as e: - print(f" WARNING: cannot remove {dup}: {e}") - continue - # Clean up empty .variants/ directories - parent = os.path.dirname(dup) - if os.path.basename(parent) == ".variants" and not os.listdir(parent): - os.rmdir(parent) - results[sha1]["removed"].append(dup) - total_removed += 1 - total_saved += size - - if alias_names or true_dupes_to_remove: - action = "Would remove" if dry_run else "Removed" - dn = os.path.basename(canonical) - print(f" {dn} (keep: {canonical})") - if true_dupes_to_remove: - print(f" {action} {len(true_dupes_to_remove)} copies") - if alias_names: - print(f" MAME clones: {alias_names}") + settled = _settle_group(paths, true_dupes_to_remove, dry_run) + total_removed += len(settled["removed"]) + total_saved += settled.pop("saved") + results[sha1] = settled # Clean up empty directories - if not dry_run: - empty_cleaned = 0 - for root, dirs, files in os.walk(bios_dir, topdown=False): - if not files and not dirs and root != bios_dir: - os.rmdir(root) - empty_cleaned += 1 + empty_cleaned = 0 if dry_run else _remove_empty_dirs(bios_dir) prefix = "Would remove" if dry_run else "Removed" print(f"\n{prefix}: {total_removed} files") @@ -305,29 +351,7 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: print(f"Cleaned {empty_cleaned} empty directories") if mame_clones: - # A group is only visible while both copies are on disk, and this run - # has just deleted the clone. Writing only what was seen this time - # therefore erases every mapping an earlier run recorded, and the - # canonical zip stops answering to the names it stands in for. The - # older entries stay valid: their canonical file is still here. - if not dry_run: - if isinstance(previous, dict): - merged = dict(previous) - merged.update(mame_clones) - mame_clones = collapse_clone_chains(merged) - if dry_run: - print(f"\nWould write MAME clone map: {clone_path}") - print( - f" {len(mame_clones)} canonical ZIPs with " - f"{sum(len(v['clones']) for v in mame_clones.values())} clones" - ) - else: - write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True)) - print(f"\nWrote MAME clone map: {clone_path}") - print( - f" {len(mame_clones)} canonical ZIPs with " - f"{sum(len(v['clones']) for v in mame_clones.values())} clones" - ) + _record_clone_map(mame_clones, previous, clone_path, dry_run) return results diff --git a/scripts/derivations.py b/scripts/derivations.py index 4840c104e..fcd1202c3 100644 --- a/scripts/derivations.py +++ b/scripts/derivations.py @@ -16,7 +16,7 @@ import hashlib import os import zipfile from collections import defaultdict -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Sequence # A held file larger than this is not read: no chip image is near it. MAX_SOURCE_SIZE = 64 * 1024 * 1024 @@ -61,7 +61,7 @@ TRANSFORMS: tuple[tuple[str, Callable[[int], int | None], Callable[[bytes], byte ) -def _gf2_times(matrix: list[int], vector: int) -> int: +def _gf2_times(matrix: Sequence[int], vector: int) -> int: total, row = 0, 0 while vector: if vector & 1: @@ -71,7 +71,7 @@ def _gf2_times(matrix: list[int], vector: int) -> int: return total -def _gf2_square(matrix: list[int]) -> list[int]: +def _gf2_square(matrix: Sequence[int]) -> list[int]: return [_gf2_times(matrix, matrix[n]) for n in range(32)] @@ -127,10 +127,10 @@ def _read(held: dict, archives: dict[str, zipfile.ZipFile] | None = None) -> byt if archives is None: with zipfile.ZipFile(held["archive"]) as zf: return zf.read(held["member"]) - zf = archives.get(held["archive"]) - if zf is None: - zf = archives[held["archive"]] = zipfile.ZipFile(held["archive"]) - return zf.read(held["member"]) + opened = archives.get(held["archive"]) + if opened is None: + opened = archives[held["archive"]] = zipfile.ZipFile(held["archive"]) + return opened.read(held["member"]) with open(held["path"], "rb") as handle: return handle.read() except (OSError, KeyError, zipfile.BadZipFile): @@ -160,13 +160,15 @@ def _held_sources(db: dict) -> list[dict]: infos = [i for i in zf.infolist() if not i.is_dir()] except (OSError, zipfile.BadZipFile): continue - for info in infos: - if 0 < info.file_size <= MAX_SOURCE_SIZE: - sources.append({ - "path": f"{path}/{info.filename}", "archive": path, - "member": info.filename, "size": info.file_size, - "crc32": f"{info.CRC:08x}", "group": path, - }) + sources.extend( + { + "path": f"{path}/{info.filename}", "archive": path, + "member": info.filename, "size": info.file_size, + "crc32": f"{info.CRC:08x}", "group": path, + } + for info in infos + if 0 < info.file_size <= MAX_SOURCE_SIZE + ) return sources @@ -201,13 +203,29 @@ def _derivable( found: dict[str, dict] = {} files = _held_sources(db) + _find_transformed(files, wanted, sizes, archives, found) + _find_concatenated(files, by_size_crc, sizes, archives, found) + return found + + +def _find_transformed( + files: list[dict], + wanted: dict[tuple[int, str], str], + sizes: set[int], + archives: dict[str, zipfile.ZipFile], + found: dict[str, dict], +) -> None: + """Record each wanted sha1 one transform of a held file produces.""" # The same chip sits in many archives. Its transforms are a function of # its bytes alone, and the first path read keeps the match, so a content # already transformed has nothing left to find. transformed: set[str] = set() for held in files: n = held["size"] - useful = [t for t in TRANSFORMS if t[1](n) in sizes] + useful = [ + (name, size_out, transform) for name, out_size, transform in TRANSFORMS + if (size_out := out_size(n)) is not None and size_out in sizes + ] if not useful: continue data = _read(held, archives) @@ -217,12 +235,21 @@ def _derivable( if content in transformed: continue transformed.add(content) - for name, out_size, transform in useful: + for name, size_out, transform in useful: out = transform(data) - sha1 = wanted.get((out_size(n), hashlib.sha1(out).hexdigest())) + sha1 = wanted.get((size_out, hashlib.sha1(out).hexdigest())) if sha1 and sha1 not in found: found[sha1] = {"from": [held["path"]], "transform": name} + +def _find_concatenated( + files: list[dict], + by_size_crc: dict[tuple[int, int], list[str]], + sizes: set[int], + archives: dict[str, zipfile.ZipFile], + found: dict[str, dict], +) -> None: + """Record each wanted sha1 two held files of one group make end to end.""" # Romsets repeat the same chip pairs: a combined crc is computed once. combined: dict[tuple[str, str, int], int] = {} by_dir: dict[str, list[dict]] = defaultdict(list) @@ -242,22 +269,33 @@ def _derivable( if total not in sizes: continue for second in seconds: - if first is second: - continue - key = (first["crc32"], second["crc32"], second["size"]) - crc = combined.get(key) - if crc is None: - crc = combined[key] = crc32_combine( - int(first["crc32"], 16), int(second["crc32"], 16), second["size"]) - candidates = [s for s in by_size_crc.get((total, crc), []) - if s not in found] - if not candidates: - continue - a, b = _read(first, archives), _read(second, archives) - if a is None or b is None: - continue - sha1 = hashlib.sha1(a + b).hexdigest() - if sha1 in candidates: - found[sha1] = {"from": [first["path"], second["path"]], - "transform": "concatenated"} - return found + if first is not second: + _try_pair(first, second, total, combined, by_size_crc, archives, found) + + +def _try_pair( + first: dict, + second: dict, + total: int, + combined: dict[tuple[str, str, int], int], + by_size_crc: dict[tuple[int, int], list[str]], + archives: dict[str, zipfile.ZipFile], + found: dict[str, dict], +) -> None: + """Record the wanted sha1 first + second makes, if their crc names one.""" + key = (first["crc32"], second["crc32"], second["size"]) + crc = combined.get(key) + if crc is None: + crc = combined[key] = crc32_combine( + int(first["crc32"], 16), int(second["crc32"], 16), second["size"]) + candidates = [s for s in by_size_crc.get((total, crc), []) + if s not in found] + if not candidates: + return + a, b = _read(first, archives), _read(second, archives) + if a is None or b is None: + return + sha1 = hashlib.sha1(a + b).hexdigest() + if sha1 in candidates: + found[sha1] = {"from": [first["path"], second["path"]], + "transform": "concatenated"} diff --git a/scripts/dumpcatalog.py b/scripts/dumpcatalog.py index 9eb766612..4c8ef5dc7 100644 --- a/scripts/dumpcatalog.py +++ b/scripts/dumpcatalog.py @@ -20,7 +20,7 @@ def load_provenance_snapshots(provenance_dir: str = DEFAULT_PROVENANCE_DIR) -> d entries written by the redump scraper or the pack importer. Missing directory means no snapshots: returns an empty dict. """ - snapshots = {} + snapshots: dict[str, dict] = {} prov_path = Path(provenance_dir) if not prov_path.is_dir(): return snapshots 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_db.py b/scripts/generate_db.py index 601a9571c..4c3c460a0 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -16,6 +16,7 @@ import os import shutil import sys import tempfile +from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path @@ -129,10 +130,52 @@ def _takes_primary(current: str, candidate: str) -> bool: return _emulator_tree(current) and not _emulator_tree(candidate) +def _add_scanned( + files: dict[str, dict], + aliases: dict[str, list[dict]], + filepath: Path, + rel_path: str, + size: int, + hashes: dict, +) -> None: + """Record a scanned file as its content's primary, or as an alias of it.""" + sha1 = hashes["sha1"] + entry = { + "path": rel_path, + "name": _canonical_name(filepath), + "size": size, + **hashes, + } + if sha1 not in files: + files[sha1] = entry + elif _takes_primary(files[sha1]["path"], rel_path): + aliases.setdefault(sha1, []).append( + {"name": files[sha1]["name"], "path": files[sha1]["path"]} + ) + files[sha1] = entry + else: + aliases.setdefault(sha1, []).append({"name": entry["name"], "path": rel_path}) + + +def _cached_hashes(cached: dict | None, mtime: float, size: int) -> dict | None: + """The cache's digests of a file that has not changed since.""" + if cached is None: + return None + fresh = cached.get("mtime") == mtime and cached.get("size") == size + # Rebuilding the hash dict by hand dropped whichever digest the + # list forgot, and the entry was then written back to the cache + # without it, so the loss survived every later run. Requiring the + # full set instead turns a partial cache entry into a miss, which + # heals it. + if fresh and all(name in cached for name in CACHED_HASHES): + return {name: cached[name] for name in CACHED_HASHES} + return None + + def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict, dict]: """Scan bios directory and compute hashes, using cache when possible.""" - files = {} - aliases = {} + files: dict[str, dict] = {} + aliases: dict[str, list[dict]] = {} new_cache = {} for filepath in sorted(bios_dir.rglob("*")): @@ -147,76 +190,10 @@ def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict, size = stat.st_size cache_key = rel_path - if not force and cache_key in cache: - cached = cache[cache_key] - fresh = cached.get("mtime") == mtime and cached.get("size") == size - # Rebuilding the hash dict by hand dropped whichever digest the - # list forgot, and the entry was then written back to the cache - # without it, so the loss survived every later run. Requiring the - # full set instead turns a partial cache entry into a miss, which - # heals it. - if fresh and all(name in cached for name in CACHED_HASHES): - hashes = {name: cached[name] for name in CACHED_HASHES} - sha1 = hashes["sha1"] - if sha1 in files: - if _takes_primary(files[sha1]["path"], rel_path): - if sha1 not in aliases: - aliases[sha1] = [] - aliases[sha1].append( - {"name": files[sha1]["name"], "path": files[sha1]["path"]} - ) - files[sha1] = { - "path": rel_path, - "name": _canonical_name(filepath), - "size": size, - **hashes, - } - else: - if sha1 not in aliases: - aliases[sha1] = [] - aliases[sha1].append( - {"name": _canonical_name(filepath), "path": rel_path} - ) - else: - entry = { - "path": rel_path, - "name": _canonical_name(filepath), - "size": size, - **hashes, - } - files[sha1] = entry - new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size} - continue - - hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size) - sha1 = hashes["sha1"] - if sha1 in files: - if _takes_primary(files[sha1]["path"], rel_path): - if sha1 not in aliases: - aliases[sha1] = [] - aliases[sha1].append( - {"name": files[sha1]["name"], "path": files[sha1]["path"]} - ) - files[sha1] = { - "path": rel_path, - "name": _canonical_name(filepath), - "size": size, - **hashes, - } - else: - if sha1 not in aliases: - aliases[sha1] = [] - aliases[sha1].append( - {"name": _canonical_name(filepath), "path": rel_path} - ) - else: - entry = { - "path": rel_path, - "name": _canonical_name(filepath), - "size": size, - **hashes, - } - files[sha1] = entry + hashes = None if force else _cached_hashes(cache.get(cache_key), mtime, size) + if hashes is None: + hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size) + _add_scanned(files, aliases, filepath, rel_path, size, hashes) new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size} return files, aliases, new_cache @@ -244,11 +221,11 @@ def _path_suffixes(rel_path: str) -> list[str]: def build_indexes(files: dict, aliases: dict) -> dict: """Build secondary indexes for fast lookup.""" - by_md5 = {} - by_name = {} - by_crc32 = {} - by_sha256 = {} - by_path_suffix = {} + by_md5: dict[str, str] = {} + by_name: dict[str, list[str]] = {} + by_crc32: dict[str, str] = {} + by_sha256: dict[str, str] = {} + by_path_suffix: dict[str, list[str]] = {} for sha1, entry in files.items(): by_md5[entry["md5"]] = sha1 @@ -624,25 +601,38 @@ class UnreadableSource(Exception): self.sources = sources -def _collect_all_aliases( - files: dict, - copies: dict | None = None, - shadowed: list[tuple[str, set[str], list[str]]] | None = None, -) -> dict: - """Collect alternate filenames from platform YAMLs, core-info, and known aliases. +@dataclass +class _AliasBook: + """The alternate names collected so far, and what designates a content.""" - Registers alternate names so generate_pack can resolve files stored under different names. - ``copies`` maps a sha1 to the other files the scan found with that content. - ``shadowed`` receives, per profile entry, its name, the contents its hashes - designate and the aliases a primary's name already carries. - """ + files: dict + md5_to_sha1: dict[str, str] + name_to_sha1: dict[str, str] + # The contents held under each name, every copy counted. + holders: dict[str, set[str]] + # The files a name designates once case is folded. + families: dict[str, set[str]] + # A name only .variants/ copies carry is not a primary's. + named_primaries: set[str] + aliases: dict[str, list[dict]] = field(default_factory=dict) + + def add(self, name: str, matched_sha1: str) -> None: + if not name or name in self.named_primaries: + return + if matched_sha1 not in self.aliases: + self.aliases[matched_sha1] = [] + existing = {a["name"] for a in self.aliases[matched_sha1]} + if name not in existing: + self.aliases[matched_sha1].append({"name": name, "path": ""}) + + +def _alias_book(files: dict, copies: dict | None) -> _AliasBook: + """Index the scanned files by md5, name and folded name.""" md5_to_sha1 = {} name_to_sha1 = {} - name_count: dict[str, int] = {} for sha1, entry in files.items(): md5_to_sha1[entry["md5"]] = sha1 name_to_sha1[entry["name"]] = sha1 - name_count[entry["name"]] = name_count.get(entry["name"], 0) + 1 # The contents held under each name, every copy counted and not only the # primary: which copy of identical bytes is primary follows path order. # Keyed on primaries alone, project64's 64DD_IPL_v12_JPN.bin stopped @@ -670,8 +660,6 @@ def _collect_all_aliases( for copy in copy_list: _hold(copy["name"], copy["path"], sha1) - aliases = {} - # A name only .variants/ copies carry is not a primary's: those copies are # the other revisions of whatever the name designates. Retroarch pins # bios_E.sms to v1.3, and with the name refused, Genesis Plus GX got the @@ -679,177 +667,210 @@ def _collect_all_aliases( named_primaries = { entry["name"] for entry in files.values() if "/.variants/" not in entry["path"] } + return _AliasBook(files, md5_to_sha1, name_to_sha1, holders, families, named_primaries) - def _add_alias(name: str, matched_sha1: str) -> None: - if not name or name in named_primaries: - return - if matched_sha1 not in aliases: - aliases[matched_sha1] = [] - existing = {a["name"] for a in aliases[matched_sha1]} - if name not in existing: - aliases[matched_sha1].append({"name": name, "path": ""}) + +def _platform_aliases(book: _AliasBook, unreadable: list[str]) -> None: + """Register the names platform YAMLs give a held content.""" + platforms_dir = Path("platforms") + if not platforms_dir.is_dir(): + return + for platform_name in list_registered_platforms( + str(platforms_dir) + ): + config_file = platforms_dir / f"{platform_name}.yml" + try: + with open(config_file) as f: + config = yaml_load(f) or {} + except (yaml.YAMLError, OSError) as e: + unreadable.append(f"{config_file}: {e}") + continue + + for system in config.get("systems", {}).values(): + for file_entry in system.get("files", []): + name = file_entry.get("name", "") + sha1 = file_entry.get("sha1", "") + md5 = file_entry.get("md5", "") + + # A zipped_file entry verifies a ROM INSIDE the + # archive, so its hash describes the member and not + # the file the name designates. Registering the name + # against that hash made d2fdc.zip an alias of a + # loose 256-byte state-machine-16.rom, which three + # platforms were then served in place of the archive. + if file_entry.get("zipped_file"): + continue + + matched = None + if sha1 and sha1 in book.files: + matched = sha1 + elif md5 and md5 in book.md5_to_sha1: + matched = book.md5_to_sha1[md5] + + if matched: + book.add(name, matched) + + +def _profile_entry_aliases( + book: _AliasBook, + file_entry: dict, + primary_names: set[str], + shadowed: list[tuple[str, set[str], list[str]]] | None, +) -> None: + """Register the aliases one profile entry gives the contents it designates.""" + entry_name = file_entry.get("name", "") + entry_aliases = _own_aliases(file_entry, primary_names) + # A profile may accept several revisions: each held one + # is designated by the entry, none of them by guess. + matched: set[str] = { + value for value in _as_list(file_entry.get("sha1")) + if value in book.files + } + matched |= { + book.md5_to_sha1[value] + for value in _as_list(file_entry.get("md5")) + if value in book.md5_to_sha1 + } + if matched: + # Proven by content, the profile's own name designates + # the file whatever the collection calls it. + entry_aliases.insert(0, entry_name) + if not entry_aliases: + return + if shadowed is not None: + taken = [ + alias for alias in entry_aliases + if alias != entry_name and alias in book.named_primaries + ] + if taken: + shadowed.append((entry_name, set(matched), taken)) + held = book.holders.get(entry_name, set()) + if ( + not matched + and len(held) == 1 + and len(book.families[entry_name.casefold()]) == 1 + ): + # A name carried by several contents names none of them: + # quasi88's disk.rom aliases went to whichever + # disk.rom the scan met last, a Tandy CoCo ROM. + matched = set(held) + for sha in sorted(matched): + for alias_name in entry_aliases: + book.add(alias_name, sha) + + +def _profile_aliases( + book: _AliasBook, + shadowed: list[tuple[str, set[str], list[str]]] | None, + unreadable: list[str], +) -> None: + """Register the aliases emulator YAMLs give (aliases field on file entries).""" + emulators_dir = Path("emulators") + if not emulators_dir.is_dir(): + return + for emu_file in source_yaml_paths(emulators_dir): + try: + with open(emu_file) as f: + emu_config = yaml_load(f) or {} + except (yaml.YAMLError, OSError) as e: + unreadable.append(f"{emu_file}: {e}") + continue + # A profile whose entries name each other (dosbox-x opens + # MT32_CONTROL.ROM and CM32L_CONTROL.ROM alike, so each entry + # aliases the other) states that ITS slot takes either name. + # Indexed globally that became evidence for every emulator: + # ScummVM's MT-32 slot received the CM-32L ROMs. + primary_names = _primary_names(emu_config.get("files", [])) + for file_entry in emu_config.get("files", []): + _profile_entry_aliases(book, file_entry, primary_names, shadowed) + + +# Identical content named differently across platforms/cores +KNOWN_ALIAS_GROUPS = [ + # ColecoVision - all these are the same 8KB BIOS + ["colecovision.rom", "coleco.rom", "BIOS.col", "bioscv.rom"], + # Game Boy - DMG boot ROM + ["gb_bios.bin", "dmg_boot.bin", "dmg_rom.bin", "dmg0_rom.bin"], + # Game Boy Color - CGB boot ROM + ["gbc_bios.bin", "cgb_boot.bin", "cgb0_boot.bin", "cgb_agb_boot.bin"], + # Super Game Boy + ["sgb_bios.bin", "sgb_boot.bin", "sgb.boot.rom"], + ["sgb2_bios.bin", "sgb2_boot.bin", "sgb2.boot.rom"], + ["sgb1.program.rom", "SGB1.sfc/program.rom"], + ["sgb2.program.rom", "SGB2.sfc/program.rom"], + # Nintendo DS. DraStic opens nds_bios_arm9.bin, nds_bios_arm7.bin + # and nds_firmware.bin and checks their size only: the collection + # answers those names with its DS dumps. + ["NDS_Bios7.bin", "bios7.bin", "nds7.bin", "nds_bios_arm7.bin"], + ["NDS_Bios9.bin", "bios9.bin", "nds9.bin", "nds_bios_arm9.bin"], + ["NDS_Lite_Firmware.bin", "nds_firmware.bin"], + ["dsi_sd_card.bin", "nds_sd_card.bin"], + # MSX + ["MSX.ROM", "MSX.rom", "Machines/Shared Roms/MSX.rom"], + # NEC PC-98 + ["N88KNJ1.ROM", "n88knj1.rom", "quasi88/n88knj1.rom"], + # Enterprise + ["zt19uk.rom", "zt19hfnt.rom", "ep128emu/roms/zt19hfnt.rom"], + # ZX Spectrum + ["48.rom", "zx48.rom"], + # SquirrelJME - all JARs are the same + [ + "squirreljme.sqc", + "squirreljme.jar", + "squirreljme-fast.jar", + "squirreljme-slow.jar", + "squirreljme-slow-test.jar", + "squirreljme-0.3.0.jar", + "squirreljme-0.3.0-fast.jar", + "squirreljme-0.3.0-slow.jar", + "squirreljme-0.3.0-slow-test.jar", + ], + # Arcade - FBNeo spectrum + ["spectrum.zip", "fbneo/spectrum.zip", "spec48k.zip"], +] + + +def _collect_all_aliases( + files: dict, + copies: dict | None = None, + shadowed: list[tuple[str, set[str], list[str]]] | None = None, +) -> dict: + """Collect alternate filenames from platform YAMLs, core-info, and known aliases. + + Registers alternate names so generate_pack can resolve files stored under different names. + ``copies`` maps a sha1 to the other files the scan found with that content. + ``shadowed`` receives, per profile entry, its name, the contents its hashes + designate and the aliases a primary's name already carries. + """ + book = _alias_book(files, copies) # A source that does not parse is reported and the run refused: written # without it, the database lost every alias the file proves and the # command exited 0 (dosbox-x's wqy fonts answered not_found). unreadable: list[str] = [] - platforms_dir = Path("platforms") - if platforms_dir.is_dir(): - for platform_name in list_registered_platforms( - str(platforms_dir) - ): - config_file = platforms_dir / f"{platform_name}.yml" - try: - with open(config_file) as f: - config = yaml_load(f) or {} - except (yaml.YAMLError, OSError) as e: - unreadable.append(f"{config_file}: {e}") - continue - - for sys_id, system in config.get("systems", {}).items(): - for file_entry in system.get("files", []): - name = file_entry.get("name", "") - sha1 = file_entry.get("sha1", "") - md5 = file_entry.get("md5", "") - - # A zipped_file entry verifies a ROM INSIDE the - # archive, so its hash describes the member and not - # the file the name designates. Registering the name - # against that hash made d2fdc.zip an alias of a - # loose 256-byte state-machine-16.rom, which three - # platforms were then served in place of the archive. - if file_entry.get("zipped_file"): - continue - - matched = None - if sha1 and sha1 in files: - matched = sha1 - elif md5 and md5 in md5_to_sha1: - matched = md5_to_sha1[md5] - - if matched: - _add_alias(name, matched) + _platform_aliases(book, unreadable) # core-info is not read here: it was the only network call of a build # that must give the same database offline, and the one name it added # (gearcoleco's writer.rom) is a profile entry proven by its sha1, which # the profile pass below now registers. - # Collect aliases from emulator YAMLs (aliases field on file entries) - emulators_dir = Path("emulators") - if emulators_dir.is_dir(): - for emu_file in source_yaml_paths(emulators_dir): - try: - with open(emu_file) as f: - emu_config = yaml_load(f) or {} - except (yaml.YAMLError, OSError) as e: - unreadable.append(f"{emu_file}: {e}") - continue - # A profile whose entries name each other (dosbox-x opens - # MT32_CONTROL.ROM and CM32L_CONTROL.ROM alike, so each entry - # aliases the other) states that ITS slot takes either name. - # Indexed globally that became evidence for every emulator: - # ScummVM's MT-32 slot received the CM-32L ROMs. - primary_names = _primary_names(emu_config.get("files", [])) - for file_entry in emu_config.get("files", []): - entry_name = file_entry.get("name", "") - entry_aliases = _own_aliases(file_entry, primary_names) - # A profile may accept several revisions: each held one - # is designated by the entry, none of them by guess. - matched: set[str] = { - value for value in _as_list(file_entry.get("sha1")) - if value in files - } - matched |= { - md5_to_sha1[value] - for value in _as_list(file_entry.get("md5")) - if value in md5_to_sha1 - } - if matched: - # Proven by content, the profile's own name designates - # the file whatever the collection calls it. - entry_aliases.insert(0, entry_name) - if not entry_aliases: - continue - if shadowed is not None: - taken = [ - alias for alias in entry_aliases - if alias != entry_name and alias in named_primaries - ] - if taken: - shadowed.append((entry_name, set(matched), taken)) - held = holders.get(entry_name, set()) - if ( - not matched - and len(held) == 1 - and len(families[entry_name.casefold()]) == 1 - ): - # A name carried by several contents names none of them: - # quasi88's disk.rom aliases went to whichever - # disk.rom the scan met last, a Tandy CoCo ROM. - matched = set(held) - for sha in sorted(matched): - for alias_name in entry_aliases: - _add_alias(alias_name, sha) - - # Identical content named differently across platforms/cores - KNOWN_ALIAS_GROUPS = [ - # ColecoVision - all these are the same 8KB BIOS - ["colecovision.rom", "coleco.rom", "BIOS.col", "bioscv.rom"], - # Game Boy - DMG boot ROM - ["gb_bios.bin", "dmg_boot.bin", "dmg_rom.bin", "dmg0_rom.bin"], - # Game Boy Color - CGB boot ROM - ["gbc_bios.bin", "cgb_boot.bin", "cgb0_boot.bin", "cgb_agb_boot.bin"], - # Super Game Boy - ["sgb_bios.bin", "sgb_boot.bin", "sgb.boot.rom"], - ["sgb2_bios.bin", "sgb2_boot.bin", "sgb2.boot.rom"], - ["sgb1.program.rom", "SGB1.sfc/program.rom"], - ["sgb2.program.rom", "SGB2.sfc/program.rom"], - # Nintendo DS. DraStic opens nds_bios_arm9.bin, nds_bios_arm7.bin - # and nds_firmware.bin and checks their size only: the collection - # answers those names with its DS dumps. - ["NDS_Bios7.bin", "bios7.bin", "nds7.bin", "nds_bios_arm7.bin"], - ["NDS_Bios9.bin", "bios9.bin", "nds9.bin", "nds_bios_arm9.bin"], - ["NDS_Lite_Firmware.bin", "nds_firmware.bin"], - ["dsi_sd_card.bin", "nds_sd_card.bin"], - # MSX - ["MSX.ROM", "MSX.rom", "Machines/Shared Roms/MSX.rom"], - # NEC PC-98 - ["N88KNJ1.ROM", "n88knj1.rom", "quasi88/n88knj1.rom"], - # Enterprise - ["zt19uk.rom", "zt19hfnt.rom", "ep128emu/roms/zt19hfnt.rom"], - # ZX Spectrum - ["48.rom", "zx48.rom"], - # SquirrelJME - all JARs are the same - [ - "squirreljme.sqc", - "squirreljme.jar", - "squirreljme-fast.jar", - "squirreljme-slow.jar", - "squirreljme-slow-test.jar", - "squirreljme-0.3.0.jar", - "squirreljme-0.3.0-fast.jar", - "squirreljme-0.3.0-slow.jar", - "squirreljme-0.3.0-slow-test.jar", - ], - # Arcade - FBNeo spectrum - ["spectrum.zip", "fbneo/spectrum.zip", "spec48k.zip"], - ] + _profile_aliases(book, shadowed, unreadable) for group in KNOWN_ALIAS_GROUPS: matched_sha1 = None for name in group: - if name in name_to_sha1: - matched_sha1 = name_to_sha1[name] + if name in book.name_to_sha1: + matched_sha1 = book.name_to_sha1[name] break if not matched_sha1: continue for name in group: - _add_alias(name, matched_sha1) + book.add(name, matched_sha1) if unreadable: raise UnreadableSource(unreadable) - return aliases + return book.aliases if __name__ == "__main__": 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/generate_pack.py b/scripts/generate_pack.py index be2a224f4..ea76c0038 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -19,7 +19,7 @@ import sys if sys.version_info < (3, 9): sys.exit(f"generate_pack.py needs Python 3.9 or newer, this is {sys.version.split()[0]}") -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator, Mapping from artifacts import _build_timestamp, set_plain_mode import argparse @@ -34,7 +34,8 @@ import shutil import tempfile import zipfile from pathlib import Path, PurePosixPath -from typing import Any +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict sys.path.insert(0, os.path.dirname(__file__)) from alternatives import core_file_spares, settle_sets, slot_set_keys @@ -133,9 +134,84 @@ from validation import ( extra_alternatives, ) +from packpaths import ( + MEDIA_MARKER, + lands_on_android, + _archive_destination, + _has_path_conflict, + _register_path, + _flat, + _resolve_destination, + placement_block, + save_layout, +) +from packextras import ( + ExtraResolver, + extra_full_destination, + extra_region_key, + prefixed_destination, + save_entry_fields, + save_manifest_dest, + _detect_extras_prefix, + _collect_emulator_extras, + _extra_system_ids, + extras_for_systems as _extras_for_systems, + platform_region_groups, + emulator_region_drops, + emulator_required_spares, + _emulator_region_group as _emulator_region_group, + expand_agnostic_entries, + undeclared_report, +) +from packreadme import ( + _build_readme, + _build_agnostic_rename_readme, + save_place, +) +from packverify import ( + _check_member_hash as _check_member_hash, + _hash_matches as _hash_matches, + _intentional_hash_exclusion as _intentional_hash_exclusion, + verify_pack_against_platform, + verify_pack, + generate_sha256sums, +) +# _OFFLINE is deliberately not re-exported: importing a value copies it, so a +# facade name would keep saying False after set_offline() changed the flag. +from packresolve import ( + ACCEPTED_HASHES, + sha1_for_hash, + preferred_entries as _preferred_entries, + parse_hash_input, + parse_hash_file, + lookup_hashes, + resolve_declaration, + resolve_file, + download_external, +) + +if TYPE_CHECKING: + from typing_extensions import Unpack + + # How a manifest settles a platform declaration: the copy served, or None + # and why not. + _Settle = Callable[[dict, str, str, "str | None"], "tuple[str | None, str]"] + # What a destination came to: its entries, whether it was filled, and the + # report to make if no other member of its set fills it. + _Outcome = tuple[list[dict], bool, "Callable[[], None] | None"] + yaml = require_yaml() DEFAULT_PLATFORMS_DIR = "platforms" + + +def _reject_unknown(function: str, options: Mapping[str, object], known: frozenset[str]) -> None: + """Refuse a keyword the options do not declare, as a named parameter would.""" + for key in options: + if key not in known: + raise TypeError(f"{function}() got an unexpected keyword argument '{key}'") + + DEFAULT_DB_FILE = "database.json" DEFAULT_OUTPUT_DIR = "dist" DEFAULT_BIOS_DIR = "bios" @@ -536,6 +612,45 @@ def _tree_references( yield tuple(tree["source_systems"]), tree +class _TreeWalkOptions(TypedDict, total=False): + """The keyword options of _data_directory_members.""" + + refs_out: dict | None + required_only: bool + core_trees: Iterable[dict] + reclaim: dict[str, str] | None + + +def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> str | None: + """The cache folder of a tree reference the pack carries, or None.""" + ref_key = dd.get("ref", "") + if not ref_key or not data_registry or ref_key not in data_registry: + return None + if ref_key in installed_data_refs(platform_name): + return None + entry = data_registry[ref_key] + allowed = entry.get("for_platforms") + if allowed and platform_name not in allowed: + return None + local_path = entry.get("local_cache", "") + if not local_path or not os.path.isdir(local_path): + print( + f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)" + ) + _MISSING_DATA_DIRS.add(ref_key) + return None + return local_path + + +def _tree_files(local_path: str, dd_prefix: str) -> Iterator[tuple[str, str]]: + """(source, destination) of every file of a cached tree.""" + for root, _dirs, filenames in os.walk(local_path): + for fname in filenames: + src = os.path.join(root, fname) + rel = os.path.relpath(src, local_path) + yield src, f"{dd_prefix}/{rel}" if dd_prefix else rel + + def _data_directory_members( pack_systems: dict, data_registry: dict | None, @@ -545,10 +660,7 @@ def _data_directory_members( seen_destinations: set, seen_lower: set, seen_parents: set, - refs_out: dict | None = None, - required_only: bool = False, - core_trees: Iterable[dict] = (), - reclaim: dict[str, str] | None = None, + **options: Unpack[_TreeWalkOptions], ) -> Iterator[tuple[str, str]]: """Yield (source, destination) for the cached data directories a platform's systems declare, then those its cores read (``core_trees``, @@ -570,91 +682,42 @@ def _data_directory_members( ``required_only`` leaves out a tree declared ``required: false``, one the core runs without, as it leaves out such a file. """ + _reject_unknown("_data_directory_members", options, _TreeWalkOptions.__optional_keys__) + refs_out = options.get("refs_out") + reclaim = options.get("reclaim") + required_only = options.get("required_only", False) + core_trees = options.get("core_trees", ()) # Data directories from _data_dirs.yml for systems, dd in _tree_references(pack_systems, core_trees): - ref_key = dd.get("ref", "") - if not ref_key or not data_registry or ref_key not in data_registry: - continue needed = dd.get("required") is not False if required_only and not needed: continue - if ref_key in installed_data_refs(platform_name): - continue - entry = data_registry[ref_key] - allowed = entry.get("for_platforms") - if allowed and platform_name not in allowed: - continue - local_path = entry.get("local_cache", "") - if not local_path or not os.path.isdir(local_path): - print( - f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)" - ) - _MISSING_DATA_DIRS.add(ref_key) + local_path = _carried_tree(dd, data_registry, platform_name) + if local_path is None: continue + ref_key = dd.get("ref", "") dd_dest = dd.get("destination", "") - if base_dest and dd_dest: - dd_prefix = f"{base_dest}/{dd_dest}" - elif base_dest: - dd_prefix = base_dest - else: - dd_prefix = dd_dest + dd_prefix = f"{base_dest}/{dd_dest}" if base_dest and dd_dest else base_dest or dd_dest # Held while the caller writes what is yielded: a refresh swapping # the tree waits until the walk is done. with cache_lock(local_path, shared=True): - for root, _dirs, filenames in os.walk(local_path): - for fname in filenames: - src = os.path.join(root, fname) - rel = os.path.relpath(src, local_path) - full = f"{dd_prefix}/{rel}" if dd_prefix else rel - if reclaim and full in reclaim and ( - os.path.normpath(reclaim[full]) == os.path.normpath(src) - ): - del reclaim[full] - if refs_out is not None: - refs_out[full] = (ref_key, systems, dd_prefix, needed) - yield src, full - continue - if full in seen_destinations or ( - full.lower() in seen_lower and case_insensitive - ): - continue - if _has_path_conflict(full, seen_destinations, seen_parents): - continue + for src, full in _tree_files(local_path, dd_prefix): + if reclaim and full in reclaim and ( + os.path.normpath(reclaim[full]) == os.path.normpath(src) + ): + del reclaim[full] + elif full in seen_destinations or ( + full.lower() in seen_lower and case_insensitive + ) or _has_path_conflict(full, seen_destinations, seen_parents): + continue + else: seen_destinations.add(full) _register_path(full, seen_destinations, seen_parents) if case_insensitive: seen_lower.add(full.lower()) - if refs_out is not None: - refs_out[full] = (ref_key, systems, dd_prefix, needed) - yield src, full - - -def _pack_data_directories( - zf: zipfile.ZipFile | PackRecord, - pack_systems: dict, - data_registry: dict | None, - platform_name: str, - base_dest: str, - flatten: bool, - case_insensitive: bool, - seen_destinations: set, - seen_lower: set, - seen_parents: set, - required_only: bool = False, - core_trees: Iterable[dict] = (), -) -> int: - """Add the data directories to the pack. Returns how many files went in.""" - added = 0 - for src, full in _data_directory_members( - pack_systems, data_registry, platform_name, base_dest, - case_insensitive, seen_destinations, seen_lower, seen_parents, - required_only=required_only, core_trees=core_trees, - ): - _add_pack_member(zf, src, _flat(full, base_dest, flatten)) - if isinstance(zf, PackRecord): - zf.trees.append(_flat(full, base_dest, flatten)) - added += 1 - return added + if refs_out is not None: + refs_out[full] = (ref_key, systems, dd_prefix, needed) + yield src, full def _case_twin_pairs( @@ -714,6 +777,18 @@ def _report_pack_counts( f"{trees}{core_count} from cores), {', '.join(parts)} [{verification_mode}]" ) +class _VariantOptions(TypedDict, total=False): + """The keyword options of _select_variants.""" + + regions: list[str] | None + one_per_slot: bool + required_only: bool + undeclared: list[dict] | None + zip_contents: dict | None + data_registry: dict | None + slot_overrides: dict[str, str] | None + + def _select_variants( config: dict, pack_systems: dict, @@ -723,13 +798,7 @@ def _select_variants( emu_profiles: dict | None, target_cores: set[str] | None, source: str, - regions: list[str] | None, - one_per_slot: bool, - required_only: bool = False, - undeclared: list[dict] | None = None, - zip_contents: dict | None = None, - data_registry: dict | None = None, - slot_overrides: dict[str, str] | None = None, + **options: Unpack[_VariantOptions], ) -> tuple[set, list, list]: """Which regional and slot alternatives this pack leaves out. @@ -739,6 +808,9 @@ def _select_variants( Returns the destinations to drop, the groups kept only as a fallback, and the slots no profile puts in order. """ + _reject_unknown("_select_variants", options, _VariantOptions.__optional_keys__) + regions = options.get("regions") + one_per_slot = options.get("one_per_slot", False) region_drops: set[str] = set() region_fallbacks: list[str] = [] # One grouping for both passes: a file judged in its own system by one @@ -756,12 +828,12 @@ def _select_variants( target_cores=target_cores, include_extras=(source != "platform"), include_all=(source == "truth"), - required_only=required_only, + required_only=options.get("required_only", False), held_out=held, - undeclared=undeclared, - zip_contents=zip_contents, - data_registry=data_registry, - slot_overrides=slot_overrides, + undeclared=options.get("undeclared"), + zip_contents=options.get("zip_contents"), + data_registry=options.get("data_registry"), + slot_overrides=options.get("slot_overrides"), ) if regions: region_index = region_mod.platform_region_index( @@ -868,31 +940,835 @@ def _report_left_out(cut: GameDataCut, systems: set[str], cores: bool) -> None: print(f" {line}") +class PackNarrowing(TypedDict, total=False): + """How a platform pack is narrowed, shared by a pack and its split parts.""" + + emulators_dir: str + zip_contents: dict | None + data_registry: dict | None + emu_profiles: dict | None + target_cores: set[str] | None + required_only: bool + source: str + regions: list[str] | None + target_name: str | None + one_per_slot: bool + offline: bool | None + no_game_data: bool + + +class _PartScope(TypedDict, total=False): + """What one split part keeps of the platform.""" + + system_filter: list[str] | None + precomputed_extras: list[dict] | None + extras_only: bool + + +class PackOptions(PackNarrowing, _PartScope, total=False): + """The keyword options of generate_pack.""" + + flatten: bool + pack_name: str | None + record: PackRecord | None + within: dict[str, str] | None + + +@dataclass(frozen=True) +class _PackSettings: + """PackOptions with their defaults.""" + + emulators_dir: str = "emulators" + zip_contents: dict | None = None + data_registry: dict | None = None + emu_profiles: dict | None = None + target_cores: set[str] | None = None + required_only: bool = False + system_filter: list[str] | None = None + precomputed_extras: list[dict] | None = None + extras_only: bool = False + source: str = "full" + flatten: bool = True + regions: list[str] | None = None + target_name: str | None = None + one_per_slot: bool = False + offline: bool | None = None + pack_name: str | None = None + no_game_data: bool = False + record: PackRecord | None = None + within: dict[str, str] | None = None + + +@dataclass +class _Placed: + """The destinations a build has taken, and the folders they open. + + ``fold`` is whether a case twin of a taken path counts as taken. + """ + + fold: bool + destinations: set[str] = field(default_factory=set) + lower: set[str] = field(default_factory=set) # only used when fold=True + parents: set[str] = field(default_factory=set) # parent dirs of added files (path conflict detection) + + def take(self, dest: str) -> None: + self.destinations.add(dest) + _register_path(dest, self.destinations, self.parents) + if self.fold: + self.lower.add(dest.lower()) + + def holds(self, dest: str) -> bool: + return dest in self.destinations or (self.fold and dest.lower() in self.lower) + + def conflicts(self, dest: str) -> bool: + return _has_path_conflict(dest, self.destinations, self.parents) + + def block(self, dest: str) -> str | None: + return placement_block(dest, self.destinations, self.lower, self.parents, self.fold) + + +@dataclass +class _PlatformPlan: + """What a platform pack is built from, settled before its first member.""" + + platform_name: str + platforms_dir: str + db: dict + bios_dir: str + opts: _PackSettings + config: dict + emu_profiles: dict + zip_contents: dict + cut: GameDataCut | None + narrowings: list[tuple[str, str]] + zip_path: str + validation_index: dict + platform_profiles: dict[str, dict] + validation_owners: dict + slot_overrides: dict[str, str] + pack_systems: dict + preferred_entries: dict[str, int] = field(default_factory=dict) + undeclared: list[dict] | None = None + region_drops: set[str] = field(default_factory=set) + region_fallbacks: list = field(default_factory=list) + slot_undecidable: list[str] = field(default_factory=list) + + @property + def verification_mode(self) -> str: + return self.config.get("verification_mode", "existence") + + @property + def platform_display(self) -> str: + return self.config.get("platform", self.platform_name) + + @property + def base_dest(self) -> str: + return self.config.get("base_destination", "") + + @property + def case_insensitive(self) -> bool: + # Case-insensitive dedup only for platforms targeting Windows/macOS. + # Linux-only platforms (Batocera, Recalbox, RetroDECK, Lakka, RomM) + # are case-sensitive and may have distinct files like DISK.ROM vs disk.rom. + return self.config.get("case_insensitive_fs", False) + + +def _plan_platform_pack( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + output_dir: str, + opts: _PackSettings, +) -> _PlatformPlan | None: + """The configuration, scope and checks a platform pack reads, or None + when the systems asked for leave nothing to build.""" + config = load_platform_config(platform_name, platforms_dir) + if opts.target_name: + config = {**config, TARGET_KEY: opts.target_name} + zip_contents = {} if opts.zip_contents is None else opts.zip_contents + emu_profiles = opts.emu_profiles + if emu_profiles is None: + # The pipeline always passes them, but a caller that does not must get the + # same pack, not one built without validation, slots or agnostic cores. + emu_profiles = load_emulator_profiles(opts.emulators_dir) + # Cut from the full config and profiles: the category of a platform + # entry is read from the profiles' game data entries. + cut = ( + without_game_data(config, emu_profiles, opts.data_registry, opts.target_cores) + if opts.no_game_data else None + ) + if cut is not None: + config, emu_profiles = cut.config, cut.profiles + + narrowings = _narrowings( + opts.source, opts.regions, opts.target_name, opts.one_per_slot, opts.required_only, + no_game_data=opts.no_game_data, + ) + zip_path = os.path.join( + output_dir, + _platform_pack_name( + platform_name, platforms_dir, narrowings, opts.system_filter, opts.pack_name + ), + ) + if opts.record is None: + os.makedirs(output_dir, exist_ok=True) + + # Build emulator-level validation index from the platform's own + # emulators (same scope as verify.py) + from common import resolve_platform_cores + + validation_index = {} + platform_profiles: dict[str, dict] = {} + if emu_profiles: + platform_profiles = { + name: emu_profiles[name] + for name in resolve_platform_cores(config, emu_profiles) + } + validation_index = _build_validation_index(platform_profiles) + validation_owners = destination_owners(platform_profiles) + slot_overrides = slots.pack_overrides( + config, emu_profiles or {}, db, zip_contents, opts.data_registry, + target_cores=opts.target_cores, source=opts.source, + ) + + pack_systems = platform_scope_systems( + config, emu_profiles or {}, opts.target_cores, opts.system_filter + ) + if opts.system_filter and not pack_systems: + reason = system_scope_error(config, platform_name, opts.system_filter, opts.target_name) + print(f" WARNING: {reason}") + return None + if opts.extras_only: + # The part of a split that carries the core extras no platform system + # owns: the platform's own files and trees went to the other parts. + pack_systems = {} + + plan = _PlatformPlan( + platform_name, platforms_dir, db, bios_dir, opts, config, emu_profiles, + zip_contents, cut, narrowings, zip_path, validation_index, platform_profiles, + validation_owners, slot_overrides, pack_systems, + ) + _settle_pack_choices(plan) + return plan + + +def _settle_pack_choices(plan: _PlatformPlan) -> None: + """The declaration each destination takes and the variants left out.""" + opts = plan.opts + if opts.source != "truth": + # Decided among the declarations this pack keeps: a preferred entry + # that --required-only drops must not silence its required twin, or + # the destination leaves the pack without a trace (RetroDECK's four + # Atari 5200 ROMs, optional under atari-400-800 and required under + # atari-5200). No data directories: the choice is about the baseline. + plan.preferred_entries = _preferred_entries( + plan.pack_systems, plan.db, plan.bios_dir, plan.base_dest, opts.required_only, + plan.zip_contents, opts.offline, + ) + + # Region selection is decided once, over both the platform baseline and the + # core extras, so the two phases below consult a single set. Grouping uses a + # dedicated extras pass with an empty seen set: it only needs group + # membership, never destinations, and a superset of members is the safe + # direction. Runs only when --region is given. + # The gap report both extras passes read, computed once: the region + # grouping and the core complement below ask it the same question. + plan.undeclared = ( + undeclared_report( + plan.config, opts.emulators_dir, plan.db, plan.emu_profiles, opts.target_cores, + include_all=(opts.source == "truth"), + ) + if opts.source != "platform" and opts.precomputed_extras is None + else None + ) + plan.region_drops, plan.region_fallbacks, plan.slot_undecidable = _select_variants( + plan.config, plan.pack_systems, opts.emulators_dir, plan.db, plan.base_dest, + plan.emu_profiles, opts.target_cores, opts.source, regions=opts.regions, + one_per_slot=opts.one_per_slot, required_only=opts.required_only, + undeclared=plan.undeclared, zip_contents=plan.zip_contents, + data_registry=opts.data_registry, slot_overrides=plan.slot_overrides, + ) + + +_STATUS_LABELS = {"untested": "UNTESTED", "excluded": "EXCLUDED", "missing": "MISSING"} + + +@dataclass +class _PlatformPackBuild: + """One platform pack being written: its members and what each slot came to. + + The four lookups are bound by generate_pack, the one place that says how + a platform file and a core extra are found and judged. + """ + + plan: _PlatformPlan + zf: zipfile.ZipFile | PackRecord + resolve: Callable[[dict, str], tuple[str | None, str]] + verdict: Callable[[dict, str | None, str], tuple[str, str | None]] + judge: Callable[[dict, str | None, str], tuple[str | None, str | None]] + resolve_extra: Callable[[dict, str], tuple[str | None, str, str]] + placed: _Placed = field(init=False) + total_files: int = 0 + core_count: int = 0 + save_count: int = 0 + tree_count: int = 0 + # Per-destination status. ``excluded`` means a same-named local payload + # exists but contradicts the declaration and is intentionally not shipped. + # It is distinct from a genuine coverage gap (``missing``). + file_status: dict[str, str] = field(default_factory=dict) + file_reasons: dict[str, str] = field(default_factory=dict) + # Core extras whose local copy contradicts the profile hash: packed, + # reported, and never counted against the platform's own file total. + core_discrepancies: list[str] = field(default_factory=list) + # Spellings left out as case twins of a packed file, for the README. + case_twins: list[str] = field(default_factory=list) + + def __post_init__(self) -> None: + self.placed = _Placed(self.plan.case_insensitive) + + def _flat(self, path: str) -> str: + return _flat(path, self.plan.base_dest, self.plan.opts.flatten) + + def run(self) -> None: + if self.plan.opts.source != "truth": + for sys_id, system in sorted(self.plan.pack_systems.items()): + for file_entry in system.get("files", []): + self._pack_declared(sys_id, file_entry) + # Core requirements: files platform's cores need but YAML doesn't declare + self._pack_core_files() + self._pack_trees() + self._write_readme() + + def _judge_conflict(self, file_entry: dict, full_dest: str) -> None: + # Content ships under the conflicting shape (file vs dir, + # e.g. SGB1.sfc). verify.py resolves each declaration on + # its own, so this one is counted by what it resolves to: + # an unresolved one counted OK had the pack claim a file + # verify reports missing. + plan = self.plan + conflict_path, conflict_status = resolve_file( + file_entry, plan.db, plan.bios_dir, plan.zip_contents, + data_dir_registry=plan.opts.data_registry, offline=plan.opts.offline, + ) + # The verdict of the main path: a zipped_file archive is + # judged by the member inside, and a frontend that hashes + # one digest accepts a file another declared hash + # contradicts, as verify judges it. + conflict_status, refusal = baseline_verdict( + file_entry, conflict_path, conflict_status, plan.verification_mode, + plan.config.get("hash_rule", ""), + ) + if conflict_status == "not_found": + self.file_status[full_dest] = "missing" + self.file_reasons[full_dest] = "not found" + elif refusal: + self.file_status[full_dest] = "excluded" + self.file_reasons[full_dest] = refusal + else: + self.file_status.setdefault(full_dest, "ok") + + def _pack_declared(self, sys_id: str, file_entry: dict) -> None: + plan, opts = self.plan, self.plan.opts + if opts.required_only and file_entry.get("required") is False: + return + dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) + if plan.region_drops and dest in plan.region_drops: + return + if not dest: + self._judge_unnamed(sys_id, file_entry) + return + full_dest = f"{plan.base_dest}/{dest}" if plan.base_dest else dest + already_packed = self.placed.holds(full_dest) + + preferred = plan.preferred_entries.get(full_dest) + if preferred is not None and id(file_entry) != preferred: + return + if self.placed.conflicts(full_dest): + self._judge_conflict(file_entry, full_dest) + return + storage = file_entry.get("storage", "embedded") + if storage == "user_provided": + if not already_packed: + self._write_instructions(file_entry, full_dest) + return + + local_path, status = self.resolve(file_entry, full_dest) + if status == "external": + self._pack_external(file_entry, full_dest) + return + if status == "not_found": + local_path = self._agnostic_fallback(sys_id, file_entry, full_dest, already_packed) + if local_path is None: + return + status = "agnostic_fallback" + # Fall through to normal packing below + chosen = self._settle_declared(file_entry, full_dest, dest, local_path, status, already_packed) + if chosen is not None: + self._ship_declared(file_entry, full_dest, chosen, already_packed) + + def _judge_unnamed(self, sys_id: str, file_entry: dict) -> None: + # EmuDeck-style entries (system:md5 whitelist, no filename). + # Judged as verify judges it: resolved on disk, the md5 + # list parsed once (case, comma lists). + plan = self.plan + fkey = f"{sys_id}/{file_entry.get('name', '')}" + held, held_status = resolve_file( + file_entry, plan.db, plan.bios_dir, plan.zip_contents, + data_dir_registry=plan.opts.data_registry, offline=plan.opts.offline, + ) + if held_status == "not_found" or not held: + self.file_status[fkey] = "missing" + elif self.verdict(file_entry, held, held_status)[1]: + self.file_status[fkey] = "excluded" + else: + self.file_status.setdefault(fkey, "ok") + + def _write_instructions(self, file_entry: dict, full_dest: str) -> None: + base_dest = self.plan.base_dest + self.placed.take(full_dest) + self.file_status.setdefault(full_dest, "ok") + instructions = file_entry.get( + "instructions", "Please provide this file manually." + ) + instr_name = f"INSTRUCTIONS_{file_entry['name']}.txt" + instr_path = ( + f"{base_dest}/{instr_name}" if base_dest else instr_name + ) + _write_generated_member( + self.zf, + self._flat(instr_path), + f"File needed: {file_entry['name']}\n\n{instructions}\n", + ) + self.total_files += 1 + + def _pack_external(self, file_entry: dict, full_dest: str) -> None: + file_ext = os.path.splitext(file_entry["name"])[1] or "" + with tempfile.NamedTemporaryFile( + delete=False, suffix=file_ext, dir=packresolve.scratch_dir() + ) as tmp: + tmp_path = tmp.name + + # The slot is the platform's file whether the download + # arrives or not: verify cannot fetch, and a core file + # filling it on a failed download made the two differ. + self.placed.take(full_dest) + try: + if self.plan.opts.record is None and download_external(file_entry, tmp_path): + extract = file_entry.get("extract", False) + if extract and tmp_path.endswith(".zip"): + _extract_zip_to_archive(tmp_path, self._flat(full_dest), self.zf) + else: + _add_pack_member(self.zf, tmp_path, self._flat(full_dest)) + self.file_status.setdefault(full_dest, "ok") + self.total_files += 1 + else: + self.file_status[full_dest] = "missing" + self.file_reasons[full_dest] = "external download failed" + finally: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + + def _agnostic_fallback( + self, sys_id: str, file_entry: dict, full_dest: str, already_packed: bool, + ) -> str | None: + # A filename-agnostic core takes any image of its system, + # renamed. Only an existence frontend accepts that. + plan = self.plan + found = None + if not reads_file_contents(plan.verification_mode): + found = agnostic_substitute(file_entry, sys_id, plan.db, plan.platform_profiles) + if not found or not found[0]: + if not already_packed: + self.file_status[full_dest] = "missing" + self.file_reasons[full_dest] = "not found" + return None + local_path, agnostic_path = found + original_name = os.path.basename(local_path) + dest_name = file_entry.get("name", "") + if original_name != dest_name and agnostic_path: + alt_names = [ + entry.get("name", "") + for entry in plan.db.get("files", {}).values() + if entry.get("path", "").startswith(agnostic_path) + and entry.get("name", "") and entry.get("name", "") != original_name + ] + readme_text = _build_agnostic_rename_readme(dest_name, original_name, alt_names) + readme_name = f"RENAMED_{dest_name}.txt" + readme_full = f"{plan.base_dest}/{readme_name}" if plan.base_dest else readme_name + if readme_full not in self.placed.destinations: + _write_generated_member(self.zf, self._flat(readme_full), readme_text) + self.placed.destinations.add(readme_full) + return local_path + + def _settle_declared( + self, + file_entry: dict, + full_dest: str, + dest: str, + local_path: str | None, + status: str, + already_packed: bool, + ) -> str | None: + """The copy a declaration ships once judged, or None when refused.""" + plan = self.plan + # The verdict the install manifest reads too: a member missing + # from a zipped_file archive, or a hash the frontend rejects. + status, refusal = self.verdict(file_entry, local_path, status) + if refusal: + # An earlier declaration of this path shipped a file this + # one refuses: it is in the pack, untested as verify + # counts it, not excluded. + self.file_status[full_dest] = "untested" if already_packed else "excluded" + self.file_reasons[full_dest] = refusal + return None + if not hash_mismatch_excludes_file(plan.verification_mode) and ( + status == "hash_mismatch" and local_path + ): + # Existence platforms accept any file at the declared path: + # their code never reads the bytes. An upstream hash that + # contradicts a local dump is reported, not acted on. + self.file_reasons.setdefault( + full_dest, + existence_discrepancy(file_entry, local_path, plan.platform_display), + ) + if self.file_status.get(full_dest) == "missing": + # An earlier declaration of this path found nothing, and this + # one fills it, as verify counts it. + del self.file_status[full_dest] + self.file_reasons.pop(full_dest, None) + self.file_status.setdefault(full_dest, "ok") + + # Emulator-level validation: informational only for platform packs. + # Platform verification (existence/md5) is the authority for pack status. + # Emulator checks are supplementary: logged but don't downgrade. + # When a discrepancy is found, try to find a file satisfying both. + if self.file_status.get(full_dest) == "ok": + local_path, disagreement = self.judge(file_entry, local_path, dest) + if disagreement: + self.file_reasons.setdefault( + full_dest, f"{plan.platform_display} says OK but {disagreement}" + ) + return local_path + + def _ship_declared( + self, file_entry: dict, full_dest: str, local_path: str, already_packed: bool, + ) -> None: + within = self.plan.opts.within + if already_packed: + if full_dest not in self.placed.destinations: + self.case_twins.append(self._flat(full_dest)) + return + if within is not None and not _same_bytes(local_path, within.get(self._flat(full_dest))): + # The full pack holds another system's file here. + return + if self.file_status.get(full_dest) == "excluded": + # An earlier declaration refused the file this one ships. + self.file_status[full_dest] = "untested" + self.placed.take(full_dest) + + extract = file_entry.get("extract", False) + flat_dest = self._flat(full_dest) + if extract and local_path.endswith(".zip"): + _extract_zip_to_archive(local_path, flat_dest, self.zf) + elif local_path.endswith(".zip"): + _add_zip_to_pack(local_path, flat_dest, self.zf, file_entry) + else: + _add_pack_member(self.zf, local_path, flat_dest) + self.total_files += 1 + + def _region_dropped(self, fe: dict) -> bool: + drops = self.plan.region_drops + return bool(drops) and extra_region_key(fe, declared_root(self.plan.config)) in drops + + def _spares(self, files: list[dict]) -> set[int]: + if not self.plan.opts.required_only: + return set() + return core_file_spares(files, self._region_dropped) + + def _core_files(self) -> list[dict]: + plan, opts = self.plan, self.plan.opts + if opts.source == "platform": + return [] + if opts.precomputed_extras is not None: + return opts.precomputed_extras + if opts.system_filter: + # The systems asked for, with what their cores need: the split + # packs get exactly this, and a full pack of one system had none. + return _extras_for_systems( + _collect_emulator_extras( + plan.config, opts.emulators_dir, plan.db, set(), plan.base_dest, + plan.emu_profiles, target_cores=opts.target_cores, + include_all=(opts.source == "truth"), undeclared=plan.undeclared, + ), + opts.system_filter, + ) + return _collect_emulator_extras( + plan.config, + opts.emulators_dir, + plan.db, + self.placed.destinations, + plan.base_dest, + plan.emu_profiles, + target_cores=opts.target_cores, + include_all=(opts.source == "truth"), + undeclared=plan.undeclared, + ) + + def _pack_core_files(self) -> None: + core_files = self._core_files() + spares = self._spares(core_files) + for fe in core_files: + if self.plan.opts.required_only and (fe.get("required") is False or id(fe) in spares): + continue + self._pack_core_file(fe) + + def _pack_core_file(self, fe: dict) -> None: + plan = self.plan + dest = sanitize_pack_path(fe.get("destination", fe["name"])) + if self._region_dropped(fe): + return + if not dest: + return + if fe.get("root") in OUTER_ROOTS: + # Read below the roms directory or in an emulator folder: the + # pack is extracted into the BIOS folder and cannot reach + # them, the installer places these files. + return + # Core extras: _collect_emulator_extras already adjusted + # destinations for slug-based platforms. Apply the effective + # prefix (base_dest, or inferred from YAML when base_dest is + # empty, as RetroDECK infers "bios"). A file read below the save + # directory goes to the pack's save folder instead. + full_dest = extra_full_destination( + fe, _detect_extras_prefix(plan.config, plan.base_dest) + ) + if not full_dest: + return + # Taken, a case twin on a case-insensitive filesystem, or a + # file/directory conflict (SGB1.sfc vs SGB1.sfc/): verify replays + # the same rule (packextras.hidden_extras). + block = self.placed.block(full_dest) + if block: + if block == "case_twin" and self.resolve_extra(fe, dest)[0]: + self.case_twins.append(self._flat(full_dest)) + return + + # The emulator's own check picks the copy, as for a declared file + # and in the emulator pack: the name led RetroArch's GC/dsp_rom.bin + # to Dolphin's obsolete v0.3.1 free ROM, beside Nintendo's coef + # ROM, a pair Dolphin warns about at every start. + local_path, status, disagreement = self.resolve_extra(fe, dest) + if not local_path: + return + self._note_core_discrepancy(fe, full_dest, local_path, status, disagreement) + + flat_dest = self._flat(full_dest) + within = plan.opts.within + if within is not None and not _same_bytes(local_path, within.get(flat_dest)): + return + if local_path.endswith(".zip"): + _add_zip_to_pack(local_path, flat_dest, self.zf, fe) + else: + _add_pack_member(self.zf, local_path, flat_dest) + if self.file_status.get(full_dest) in ("missing", "excluded"): + self._core_fills_declaration(fe, full_dest) + self.placed.take(full_dest) + self.core_count += 1 + if fe.get("root") == "save": + self.save_count += 1 + self.total_files += 1 + + def _note_core_discrepancy( + self, fe: dict, full_dest: str, local_path: str, status: str, disagreement: str, + ) -> None: + if disagreement: + self.core_discrepancies.append(f"{full_dest}: {disagreement}") + if status == "hash_mismatch" and not _matches_an_alternative( + fe, local_path, self.plan.emu_profiles or {} + ): + # The core's declared hash comes from its source, the local dump + # is what the collection holds. Shipping it keeps the emulator + # working when the code never reads the hash, and the divergence is + # reported so it can be resolved at the profile or the dump. + # file_status tracks platform declarations only, so the report + # goes to its own list and never moves the pack's own count. + self.core_discrepancies.append( + f"{full_dest}: declared hash of " + f"{fe.get('source_profile') or fe.get('source_emulator', 'core profile')}" + " does not match the packed copy" + ) + + def _core_fills_declaration(self, fe: dict, full_dest: str) -> None: + source_name = fe.get("source_profile") or fe.get( + "source_emulator", "core profile" + ) + if reads_file_contents(self.plan.verification_mode): + # The frontend hashes what sits at the path, and the core's + # copy is not the hash it declares: the file ships for the + # core, the platform's own check still fails, as verify says. + self.file_reasons[full_dest] = ( + "platform-declared hash unavailable; " + f"packed the validated {source_name} requirement, " + "which the platform check does not accept" + ) + else: + # An existence frontend is satisfied by any file at the path. + self.file_status[full_dest] = "ok" + self.file_reasons.pop(full_dest, None) + + def _pack_trees(self) -> None: + plan, opts = self.plan, self.plan.opts + # The trees the cores read follow them as their extras do: by the + # systems asked for, and those of no system in the part of their own. + core_trees = ( + [] if opts.source == "platform" + else core_data_trees( + plan.config, plan.emu_profiles, plan.platform_name, opts.data_registry, + opts.target_cores, + ) + ) + if opts.extras_only: + owned = list(platform_scope_systems(plan.config, plan.emu_profiles, opts.target_cores)) + core_trees = [t for t in core_trees if not _extras_for_systems([t], owned)] + elif opts.system_filter: + core_trees = _extras_for_systems(core_trees, opts.system_filter) + # Counted apart: the trees a core reads are not on the platform's + # list. MyMinUI declares nothing and its line read "6944 baseline". + self.total_files += self._pack_data_directories(plan.pack_systems, ()) + self.tree_count = self._pack_data_directories({}, core_trees) + self.total_files += self.tree_count + + def _pack_data_directories(self, pack_systems: dict, core_trees: Iterable[dict]) -> int: + """Add the data directories to the pack. Returns how many files went in.""" + plan = self.plan + required_only = plan.opts.required_only + seen_parents = self.placed.parents + added = 0 + for src, full in _data_directory_members( + pack_systems, plan.opts.data_registry, plan.platform_name, plan.base_dest, + self.placed.fold, self.placed.destinations, self.placed.lower, + seen_parents, required_only=required_only, + core_trees=core_trees, + ): + _add_pack_member(self.zf, src, self._flat(full)) + if isinstance(self.zf, PackRecord): + self.zf.trees.append(self._flat(full)) + added += 1 + return added + + def _unfolded_twins(self) -> None: + # The spellings a folded platform counts as declared never reach + # the extras: collected as the filesystem that keeps case sees + # them, as the manifest's case_variants are (Mesen-CE's bios.col + # beside the declared BIOS.col). + plan, opts = self.plan, self.plan.opts + unfolded = _collect_emulator_extras( + {**plan.config, "case_insensitive_fs": False}, opts.emulators_dir, plan.db, set(), + plan.base_dest, plan.emu_profiles, target_cores=opts.target_cores, + include_all=(opts.source == "truth"), + ) + if opts.system_filter: + unfolded = _extras_for_systems(unfolded, opts.system_filter) + prefix = _detect_extras_prefix(plan.config, plan.base_dest) + unfolded_spares = self._spares(unfolded) + for fe in unfolded: + if opts.required_only and (fe.get("required") is False or id(fe) in unfolded_spares): + continue + if self._region_dropped(fe): + continue + full = extra_full_destination(fe, prefix) + if ( + full and full not in self.placed.destinations and full.lower() in self.placed.lower + and self.resolve_extra( + fe, sanitize_pack_path(fe.get("destination", fe["name"])) + )[0] + ): + self.case_twins.append(self._flat(full)) + + def _write_readme(self) -> None: + # README.txt for users: personalized step-by-step per platform + plan, opts = self.plan, self.plan.opts + registry = _platform_registry(plan.platforms_dir).get(plan.platform_name, {}) + install = registry.get("install", {}) or {} + keeps_case = plan.case_insensitive and any( + d.get("os") not in CASE_FOLDING_OS for d in install.get("detect", []) + ) + if keeps_case and opts.source != "platform" and opts.precomputed_extras is None: + self._unfolded_twins() + save_count = self.save_count + readme_text = _build_readme( + plan.platform_name, plan.platform_display, plan.base_dest, self.total_files, + len(plan.pack_systems), + source=opts.source, + contributors=registry.get("contributed_by", []), + regions=opts.regions, + fallback_systems=plan.region_fallbacks, + one_per_slot=opts.one_per_slot, + undecidable_slots=plan.slot_undecidable, + narrowings=plan.narrowings, + system_filter=opts.system_filter, + detect=install.get("detect", []), + standalone_copies=install.get("standalone_copies", []), + launch_folders=len(plan.config.get("core_system_dirs") or {}), + save_folder=(save_layout(plan.config).in_pack if save_count else ""), + save_where=( + save_place( + str(registry.get("extract_to") or ""), + save_layout(plan.config).folder, plan.base_dest, + ) if save_count else "" + ), + save_by_system=bool(save_count and save_layout(plan.config).by_system), + case_twins=( + _case_twin_pairs( + self.case_twins, self.placed.destinations, plan.base_dest, opts.flatten + ) + if keeps_case else [] + ), + ) + _write_generated_member(self.zf, "README.txt", readme_text) + for marker in pack_markers(plan.platform_name, opts.target_name, plan.platforms_dir): + _write_generated_member( + self.zf, + self._flat(f"{plan.base_dest}/{marker}" if plan.base_dest else marker), + "", + ) + + def report(self) -> None: + plan, opts = self.plan, self.plan.opts + _report_pack_counts( + plan.zip_path, self.file_status, self.total_files, self.core_count, opts.source, + plan.verification_mode, tree_count=self.tree_count, + ) + if plan.cut is not None: + _report_left_out( + plan.cut, + systems=set(plan.pack_systems) if opts.source != "truth" else set(), + cores=opts.source != "platform" and opts.precomputed_extras is None, + ) + for key, reason in sorted(self.file_reasons.items()): + label = _STATUS_LABELS.get(self.file_status.get(key, ""), "DISCREPANCY") + print(f" {label}: {key}: {reason}") + for note in sorted(self.core_discrepancies): + print(f" DISCREPANCY: {note}") + + +def _platform_registry(platforms_dir: str) -> dict: + """The platforms of _registry.yml, or nothing when the file is absent.""" + registry_path = Path(platforms_dir) / "_registry.yml" + if not registry_path.exists(): + return {} + with open(registry_path) as f: + return (yaml_load(f) or {}).get("platforms", {}) + + def generate_pack( platform_name: str, platforms_dir: str, db: dict, bios_dir: str, output_dir: str, - emulators_dir: str = "emulators", - zip_contents: dict | None = None, - data_registry: dict | None = None, - emu_profiles: dict | None = None, - target_cores: set[str] | None = None, - required_only: bool = False, - system_filter: list[str] | None = None, - precomputed_extras: list[dict] | None = None, - extras_only: bool = False, - source: str = "full", - flatten: bool = True, - regions: list[str] | None = None, - target_name: str | None = None, - one_per_slot: bool = False, - offline: bool | None = None, - pack_name: str | None = None, - no_game_data: bool = False, - record: PackRecord | None = None, - within: dict[str, str] | None = None, + **options: Unpack[PackOptions], ) -> str | None: """Generate a ZIP pack for a platform. @@ -914,657 +1790,51 @@ def generate_pack( Returns the path to the generated ZIP, or None on failure. """ - config = load_platform_config(platform_name, platforms_dir) - if target_name: - config = {**config, TARGET_KEY: target_name} - if zip_contents is None: - zip_contents = {} - if emu_profiles is None: - # The pipeline always passes them, but a caller that does not must get the - # same pack, not one built without validation, slots or agnostic cores. - emu_profiles = load_emulator_profiles(emulators_dir) - # Cut from the full config and profiles: the category of a platform - # entry is read from the profiles' game data entries. - cut = ( - without_game_data(config, emu_profiles, data_registry, target_cores) - if no_game_data else None - ) - if cut is not None: - config, emu_profiles = cut.config, cut.profiles - - verification_mode = config.get("verification_mode", "existence") - platform_display = config.get("platform", platform_name) - base_dest = config.get("base_destination", "") - - narrowings = _narrowings( - source, regions, target_name, one_per_slot, required_only, - no_game_data=no_game_data, - ) - zip_path = os.path.join( - output_dir, - _platform_pack_name( - platform_name, platforms_dir, narrowings, system_filter, pack_name - ), - ) - if record is None: - os.makedirs(output_dir, exist_ok=True) - - # Case-insensitive dedup only for platforms targeting Windows/macOS. - # Linux-only platforms (Batocera, Recalbox, RetroDECK, Lakka, RomM) - # are case-sensitive and may have distinct files like DISK.ROM vs disk.rom. - case_insensitive = config.get("case_insensitive_fs", False) - - total_files = 0 - missing_files = [] - # Core extras whose local copy contradicts the profile hash: packed, - # reported, and never counted against the platform's own file total. - core_discrepancies: list[str] = [] - user_provided = [] - seen_destinations: set[str] = set() - seen_lower: set[str] = set() # only used when case_insensitive=True - # Spellings left out as case twins of a packed file, for the README. - case_twins: list[str] = [] - seen_parents: set[str] = ( - set() - ) # parent dirs of added files (path conflict detection) - # Per-destination status. ``excluded`` means a same-named local payload - # exists but contradicts the declaration and is intentionally not shipped. - # It is distinct from a genuine coverage gap (``missing``). - file_status: dict[str, str] = {} - file_reasons: dict[str, str] = {} - - # Build emulator-level validation index from the platform's own - # emulators (same scope as verify.py) - from common import resolve_platform_cores - - validation_index = {} - platform_profiles: dict[str, dict] = {} - if emu_profiles: - platform_profiles = { - name: emu_profiles[name] - for name in resolve_platform_cores(config, emu_profiles) - } - validation_index = _build_validation_index(platform_profiles) - validation_owners = destination_owners(platform_profiles) - slot_overrides = slots.pack_overrides( - config, emu_profiles or {}, db, zip_contents, data_registry, - target_cores=target_cores, source=source, - ) - - pack_systems = platform_scope_systems( - config, emu_profiles or {}, target_cores, system_filter - ) - if system_filter and not pack_systems: - reason = system_scope_error(config, platform_name, system_filter, target_name) - print(f" WARNING: {reason}") + _reject_unknown("generate_pack", options, PackOptions.__optional_keys__) + opts = _PackSettings(**options) + plan = _plan_platform_pack(platform_name, platforms_dir, db, bios_dir, output_dir, opts) + if plan is None: return None - if extras_only: - # The part of a split that carries the core extras no platform system - # owns: the platform's own files and trees went to the other parts. - pack_systems = {} - preferred_entries: dict[str, int] = {} - if source != "truth": - # Decided among the declarations this pack keeps: a preferred entry - # that --required-only drops must not silence its required twin, or - # the destination leaves the pack without a trace (RetroDECK's four - # Atari 5200 ROMs, optional under atari-400-800 and required under - # atari-5200). No data directories: the choice is about the baseline. - preferred_entries = _preferred_entries( - pack_systems, db, bios_dir, base_dest, required_only, - zip_contents, offline, + def resolve(file_entry: dict, full_dest: str) -> tuple[str | None, str]: + return resolve_declaration( + file_entry, + db, + bios_dir, + plan.zip_contents, + opts.data_registry, + plan.slot_overrides.get(full_dest), + offline=opts.offline, ) - # Region selection is decided once, over both the platform baseline and the - # core extras, so the two phases below consult a single set. Grouping uses a - # dedicated extras pass with an empty seen set: it only needs group - # membership, never destinations, and a superset of members is the safe - # direction. Runs only when --region is given. - # The gap report both extras passes read, computed once: the region - # grouping and the core complement below ask it the same question. - undeclared = ( - undeclared_report( - config, emulators_dir, db, emu_profiles, target_cores, - include_all=(source == "truth"), + def verdict(file_entry: dict, local_path: str | None, status: str) -> tuple[str, str | None]: + return baseline_verdict( + file_entry, local_path, status, plan.verification_mode, + plan.config.get("hash_rule", ""), ) - if source != "platform" and precomputed_extras is None - else None - ) - region_drops, region_fallbacks, slot_undecidable = _select_variants( - config, pack_systems, emulators_dir, db, base_dest, emu_profiles, - target_cores, source, regions, one_per_slot, required_only, - undeclared=undeclared, zip_contents=zip_contents, - data_registry=data_registry, slot_overrides=slot_overrides, + + def judge(file_entry: dict, local_path: str | None, dest: str) -> tuple[str | None, str | None]: + return validated_choice( + file_entry, local_path, db, plan.validation_index, bios_dir, + digest_algorithm(plan.verification_mode), dest, plan.validation_owners, + ) + + extra_resolver = ExtraResolver( + db, bios_dir, plan.zip_contents, opts.data_registry, plan.validation_index, + plan.validation_owners, opts.offline, profiles=plan.emu_profiles, ) + def resolve_extra(fe: dict, dest: str) -> tuple[str | None, str, str]: + return extra_resolver.resolve(fe, dest) + with ( - contextlib.nullcontext(record) if record is not None - else _writing_pack(zip_path) + contextlib.nullcontext(opts.record) if opts.record is not None + else _writing_pack(plan.zip_path) ) as zf: - if source != "truth": - for sys_id, system in sorted(pack_systems.items()): - for file_entry in system.get("files", []): - if required_only and file_entry.get("required") is False: - continue - dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) - if region_drops and dest in region_drops: - continue - if not dest: - # EmuDeck-style entries (system:md5 whitelist, no filename). - # Judged as verify judges it: resolved on disk, the md5 - # list parsed once (case, comma lists). - fkey = f"{sys_id}/{file_entry.get('name', '')}" - held, held_status = resolve_file( - file_entry, db, bios_dir, zip_contents, - data_dir_registry=data_registry, offline=offline, - ) - if held_status == "not_found" or not held: - file_status[fkey] = "missing" - elif baseline_verdict( - file_entry, held, held_status, verification_mode, - config.get("hash_rule", ""), - )[1]: - file_status[fkey] = "excluded" - else: - file_status.setdefault(fkey, "ok") - continue - if base_dest: - full_dest = f"{base_dest}/{dest}" - else: - full_dest = dest - - dedup_key = full_dest - already_packed = dedup_key in seen_destinations or ( - case_insensitive and dedup_key.lower() in seen_lower - ) - - preferred = preferred_entries.get(dedup_key) - if preferred is not None and id(file_entry) != preferred: - continue - - if _has_path_conflict(full_dest, seen_destinations, seen_parents): - # Content ships under the conflicting shape (file vs dir, - # e.g. SGB1.sfc). verify.py resolves each declaration on - # its own, so this one is counted by what it resolves to: - # an unresolved one counted OK had the pack claim a file - # verify reports missing. - conflict_path, conflict_status = resolve_file( - file_entry, db, bios_dir, zip_contents, - data_dir_registry=data_registry, offline=offline, - ) - # The verdict of the main path: a zipped_file archive is - # judged by the member inside, and a frontend that hashes - # one digest accepts a file another declared hash - # contradicts, as verify judges it. - conflict_status, refusal = baseline_verdict( - file_entry, conflict_path, conflict_status, verification_mode, - config.get("hash_rule", ""), - ) - if conflict_status == "not_found": - file_status[dedup_key] = "missing" - file_reasons[dedup_key] = "not found" - elif refusal: - file_status[dedup_key] = "excluded" - file_reasons[dedup_key] = refusal - else: - file_status.setdefault(dedup_key, "ok") - continue - - storage = file_entry.get("storage", "embedded") - - if storage == "user_provided": - if already_packed: - continue - seen_destinations.add(dedup_key) - _register_path(dedup_key, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(dedup_key.lower()) - file_status.setdefault(dedup_key, "ok") - instructions = file_entry.get( - "instructions", "Please provide this file manually." - ) - instr_name = f"INSTRUCTIONS_{file_entry['name']}.txt" - instr_path = ( - f"{base_dest}/{instr_name}" if base_dest else instr_name - ) - _write_generated_member( - zf, - _flat(instr_path, base_dest, flatten), - f"File needed: {file_entry['name']}\n\n{instructions}\n", - ) - user_provided.append(file_entry["name"]) - total_files += 1 - continue - - local_path, status = resolve_declaration( - file_entry, - db, - bios_dir, - zip_contents, - data_registry, - slot_overrides.get(full_dest), - offline=offline, - ) - - if status == "external": - file_ext = os.path.splitext(file_entry["name"])[1] or "" - with tempfile.NamedTemporaryFile( - delete=False, suffix=file_ext, dir=packresolve.scratch_dir() - ) as tmp: - tmp_path = tmp.name - - # The slot is the platform's file whether the download - # arrives or not: verify cannot fetch, and a core file - # filling it on a failed download made the two differ. - seen_destinations.add(dedup_key) - _register_path(dedup_key, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(dedup_key.lower()) - try: - if record is None and download_external(file_entry, tmp_path): - extract = file_entry.get("extract", False) - if extract and tmp_path.endswith(".zip"): - _extract_zip_to_archive(tmp_path, _flat(full_dest, base_dest, flatten), zf) - else: - _add_pack_member(zf, tmp_path, _flat(full_dest, base_dest, flatten)) - file_status.setdefault(dedup_key, "ok") - total_files += 1 - else: - file_status[dedup_key] = "missing" - file_reasons[dedup_key] = "external download failed" - finally: - if os.path.exists(tmp_path): - os.unlink(tmp_path) - continue - - if status == "not_found": - # A filename-agnostic core takes any image of its system, - # renamed. Only an existence frontend accepts that. - files_db = db.get("files", {}) - agnostic_path = None - agnostic_resolved = False - if not reads_file_contents(verification_mode): - found = agnostic_substitute(file_entry, sys_id, db, platform_profiles) - if found: - local_path, agnostic_path = found - agnostic_resolved = True - - if agnostic_resolved and local_path: - original_name = os.path.basename(local_path) - dest_name = file_entry.get("name", "") - if original_name != dest_name and agnostic_path: - alt_names = [] - for _s, _e in files_db.items(): - _p = _e.get("path", "") - if _p.startswith(agnostic_path): - _n = _e.get("name", "") - if _n and _n != original_name: - alt_names.append(_n) - readme_text = _build_agnostic_rename_readme( - dest_name, - original_name, - alt_names, - ) - readme_name = f"RENAMED_{dest_name}.txt" - readme_full = ( - f"{base_dest}/{readme_name}" - if base_dest - else readme_name - ) - if readme_full not in seen_destinations: - _write_generated_member( - zf, - _flat(readme_full, base_dest, flatten), - readme_text, - ) - seen_destinations.add(readme_full) - status = "agnostic_fallback" - # Fall through to normal packing below - else: - if not already_packed: - file_status[dedup_key] = "missing" - file_reasons[dedup_key] = "not found" - continue - - # The verdict the install manifest reads too: a member missing - # from a zipped_file archive, or a hash the frontend rejects. - status, refusal = baseline_verdict( - file_entry, local_path, status, verification_mode, - config.get("hash_rule", ""), - ) - if refusal: - # An earlier declaration of this path shipped a file this - # one refuses: it is in the pack, untested as verify - # counts it, not excluded. - file_status[dedup_key] = "untested" if already_packed else "excluded" - file_reasons[dedup_key] = refusal - continue - if not hash_mismatch_excludes_file(verification_mode) and ( - status == "hash_mismatch" and local_path - ): - # Existence platforms accept any file at the declared path: - # their code never reads the bytes. An upstream hash that - # contradicts a local dump is reported, not acted on. - file_reasons.setdefault( - dedup_key, - existence_discrepancy(file_entry, local_path, platform_display), - ) - if file_status.get(dedup_key) == "missing": - # An earlier declaration of this path found nothing, and this - # one fills it, as verify counts it. - del file_status[dedup_key] - file_reasons.pop(dedup_key, None) - file_status.setdefault(dedup_key, "ok") - - # Emulator-level validation: informational only for platform packs. - # Platform verification (existence/md5) is the authority for pack status. - # Emulator checks are supplementary: logged but don't downgrade. - # When a discrepancy is found, try to find a file satisfying both. - if file_status.get(dedup_key) == "ok": - local_path, disagreement = validated_choice( - file_entry, local_path, db, validation_index, bios_dir, - digest_algorithm(verification_mode), dest, validation_owners, - ) - if disagreement: - file_reasons.setdefault( - dedup_key, f"{platform_display} says OK but {disagreement}" - ) - - if already_packed: - if dedup_key not in seen_destinations: - case_twins.append(_flat(full_dest, base_dest, flatten)) - continue - if within is not None and not _same_bytes( - local_path, within.get(_flat(full_dest, base_dest, flatten)) - ): - # The full pack holds another system's file here. - continue - if file_status.get(dedup_key) == "excluded": - # An earlier declaration refused the file this one ships. - file_status[dedup_key] = "untested" - seen_destinations.add(dedup_key) - _register_path(dedup_key, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(dedup_key.lower()) - - extract = file_entry.get("extract", False) - flat_dest = _flat(full_dest, base_dest, flatten) - if extract and local_path.endswith(".zip"): - _extract_zip_to_archive(local_path, flat_dest, zf) - elif local_path.endswith(".zip"): - _add_zip_to_pack(local_path, flat_dest, zf, file_entry) - else: - _add_pack_member(zf, local_path, flat_dest) - total_files += 1 - - # Core requirements: files platform's cores need but YAML doesn't declare - if emu_profiles is None: - emu_profiles = load_emulator_profiles(emulators_dir) - if source == "platform": - core_files = [] - elif precomputed_extras is not None: - core_files = precomputed_extras - elif system_filter: - # The systems asked for, with what their cores need: the split - # packs get exactly this, and a full pack of one system had none. - core_files = _extras_for_systems( - _collect_emulator_extras( - config, emulators_dir, db, set(), base_dest, emu_profiles, - target_cores=target_cores, include_all=(source == "truth"), - undeclared=undeclared, - ), - system_filter, - ) - else: - core_files = _collect_emulator_extras( - config, - emulators_dir, - db, - seen_destinations, - base_dest, - emu_profiles, - target_cores=target_cores, - include_all=(source == "truth"), - undeclared=undeclared, - ) - - core_count = 0 - save_count = 0 - extra_resolver = ExtraResolver( - db, bios_dir, zip_contents, data_registry, validation_index, - validation_owners, offline, profiles=emu_profiles, - ) - spares = core_file_spares( - core_files, - lambda fe: bool(region_drops) - and extra_region_key(fe, declared_root(config)) in region_drops, - ) if required_only else set() - for fe in core_files: - if required_only and (fe.get("required") is False or id(fe) in spares): - continue - dest = sanitize_pack_path(fe.get("destination", fe["name"])) - if region_drops and extra_region_key(fe, declared_root(config)) in region_drops: - continue - if not dest: - continue - if fe.get("root") in OUTER_ROOTS: - # Read below the roms directory or in an emulator folder: the - # pack is extracted into the BIOS folder and cannot reach - # them, the installer places these files. - continue - # Core extras: _collect_emulator_extras already adjusted - # destinations for slug-based platforms. Apply the effective - # prefix (base_dest, or inferred from YAML when base_dest is - # empty, as RetroDECK infers "bios"). A file read below the save - # directory goes to the pack's save folder instead. - full_dest = extra_full_destination( - fe, _detect_extras_prefix(config, base_dest) - ) - if not full_dest: - continue - # Taken, a case twin on a case-insensitive filesystem, or a - # file/directory conflict (SGB1.sfc vs SGB1.sfc/): verify replays - # the same rule (packextras.hidden_extras). - block = placement_block( - full_dest, seen_destinations, seen_lower, seen_parents, - case_insensitive, - ) - if block: - if block == "case_twin" and extra_resolver.resolve(fe, dest)[0]: - case_twins.append(_flat(full_dest, base_dest, flatten)) - continue - - # The emulator's own check picks the copy, as for a declared file - # and in the emulator pack: the name led RetroArch's GC/dsp_rom.bin - # to Dolphin's obsolete v0.3.1 free ROM, beside Nintendo's coef - # ROM, a pair Dolphin warns about at every start. - local_path, status, disagreement = extra_resolver.resolve(fe, dest) - if not local_path: - continue - if disagreement: - core_discrepancies.append(f"{full_dest}: {disagreement}") - if status == "hash_mismatch" and not _matches_an_alternative( - fe, local_path, emu_profiles or {} - ): - # The core's declared hash comes from its source, the local dump - # is what the collection holds. Shipping it keeps the emulator - # working when the code never reads the hash, and the divergence is - # reported so it can be resolved at the profile or the dump. - # file_status tracks platform declarations only, so the report - # goes to its own list and never moves the pack's own count. - core_discrepancies.append( - f"{full_dest}: declared hash of " - f"{fe.get('source_profile') or fe.get('source_emulator', 'core profile')}" - " does not match the packed copy" - ) - - flat_dest = _flat(full_dest, base_dest, flatten) - if within is not None and not _same_bytes(local_path, within.get(flat_dest)): - continue - if local_path.endswith(".zip"): - _add_zip_to_pack(local_path, flat_dest, zf, fe) - else: - _add_pack_member(zf, local_path, flat_dest) - if file_status.get(full_dest) in ("missing", "excluded"): - source_name = fe.get("source_profile") or fe.get( - "source_emulator", "core profile" - ) - if reads_file_contents(verification_mode): - # The frontend hashes what sits at the path, and the core's - # copy is not the hash it declares: the file ships for the - # core, the platform's own check still fails, as verify says. - file_reasons[full_dest] = ( - "platform-declared hash unavailable; " - f"packed the validated {source_name} requirement, " - "which the platform check does not accept" - ) - else: - # An existence frontend is satisfied by any file at the path. - file_status[full_dest] = "ok" - file_reasons.pop(full_dest, None) - seen_destinations.add(full_dest) - _register_path(full_dest, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(full_dest.lower()) - core_count += 1 - if fe.get("root") == "save": - save_count += 1 - total_files += 1 - - # The trees the cores read follow them as their extras do: by the - # systems asked for, and those of no system in the part of their own. - core_trees = ( - [] if source == "platform" - else core_data_trees( - config, emu_profiles, platform_name, data_registry, target_cores - ) - ) - if extras_only: - owned = list(platform_scope_systems(config, emu_profiles, target_cores)) - core_trees = [t for t in core_trees if not _extras_for_systems([t], owned)] - elif system_filter: - core_trees = _extras_for_systems(core_trees, system_filter) - # Counted apart: the trees a core reads are not on the platform's - # list. MyMinUI declares nothing and its line read "6944 baseline". - total_files += _pack_data_directories( - zf, pack_systems, data_registry, platform_name, base_dest, - flatten, case_insensitive, seen_destinations, seen_lower, - seen_parents, required_only=required_only, - ) - tree_count = _pack_data_directories( - zf, {}, data_registry, platform_name, base_dest, - flatten, case_insensitive, seen_destinations, seen_lower, - seen_parents, required_only=required_only, core_trees=core_trees, - ) - total_files += tree_count - - # README.txt for users: personalized step-by-step per platform - num_systems = len(pack_systems) - _registry_path = Path(platforms_dir) / "_registry.yml" - _pack_registry: dict = {} - if _registry_path.exists(): - with open(_registry_path) as _rf: - _pack_registry = (yaml_load(_rf) or {}).get("platforms", {}) - keeps_case = case_insensitive and any( - d.get("os") not in CASE_FOLDING_OS - for d in (_pack_registry.get(platform_name, {}).get("install", {}) or {}) - .get("detect", []) - ) - if keeps_case and source != "platform" and precomputed_extras is None: - # The spellings a folded platform counts as declared never reach - # the extras: collected as the filesystem that keeps case sees - # them, as the manifest's case_variants are (Mesen-CE's bios.col - # beside the declared BIOS.col). - unfolded = _collect_emulator_extras( - {**config, "case_insensitive_fs": False}, emulators_dir, db, set(), - base_dest, emu_profiles, target_cores=target_cores, - include_all=(source == "truth"), - ) - if system_filter: - unfolded = _extras_for_systems(unfolded, system_filter) - prefix = _detect_extras_prefix(config, base_dest) - unfolded_spares = core_file_spares( - unfolded, - lambda fe: bool(region_drops) - and extra_region_key(fe, declared_root(config)) in region_drops, - ) if required_only else set() - for fe in unfolded: - if required_only and (fe.get("required") is False or id(fe) in unfolded_spares): - continue - if region_drops and extra_region_key(fe, declared_root(config)) in region_drops: - continue - full = extra_full_destination(fe, prefix) - if ( - full and full not in seen_destinations and full.lower() in seen_lower - and extra_resolver.resolve( - fe, sanitize_pack_path(fe.get("destination", fe["name"])) - )[0] - ): - case_twins.append(_flat(full, base_dest, flatten)) - readme_text = _build_readme( - platform_name, platform_display, base_dest, total_files, num_systems, - source=source, - contributors=_pack_registry.get(platform_name, {}).get("contributed_by", []), - regions=regions, - fallback_systems=region_fallbacks, - one_per_slot=one_per_slot, - undecidable_slots=slot_undecidable, - narrowings=narrowings, - system_filter=system_filter, - detect=( - _pack_registry.get(platform_name, {}).get("install", {}) or {} - ).get("detect", []), - standalone_copies=( - _pack_registry.get(platform_name, {}).get("install", {}) or {} - ).get("standalone_copies", []), - launch_folders=len(config.get("core_system_dirs") or {}), - save_folder=(save_layout(config).in_pack if save_count else ""), - save_where=( - save_place( - str(_pack_registry.get(platform_name, {}).get("extract_to") or ""), - save_layout(config).folder, base_dest, - ) if save_count else "" - ), - save_by_system=bool(save_count and save_layout(config).by_system), - case_twins=( - _case_twin_pairs(case_twins, seen_destinations, base_dest, flatten) - if keeps_case else [] - ), - ) - _write_generated_member(zf, "README.txt", readme_text) - for marker in pack_markers(platform_name, target_name, platforms_dir): - _write_generated_member( - zf, _flat(f"{base_dest}/{marker}" if base_dest else marker, base_dest, flatten), "" - ) - - _report_pack_counts( - zip_path, file_status, total_files, core_count, source, - verification_mode, tree_count=tree_count, - ) - if cut is not None: - _report_left_out( - cut, - systems=set(pack_systems) if source != "truth" else set(), - cores=source != "platform" and precomputed_extras is None, - ) - - - for key, reason in sorted(file_reasons.items()): - status = file_status.get(key, "") - if status == "untested": - label = "UNTESTED" - elif status == "excluded": - label = "EXCLUDED" - elif status == "missing": - label = "MISSING" - else: - label = "DISCREPANCY" - print(f" {label}: {key}: {reason}") - for name in missing_files: - print(f" MISSING: {name}") - for note in sorted(core_discrepancies): - print(f" DISCREPANCY: {note}") - return zip_path + build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra) + build.run() + build.report() + return plan.zip_path def _extract_zip_to_archive( @@ -1712,6 +1982,386 @@ def _bounded_pack_name(display_names: list[str], keys: list[str], suffix: str) - return f"{display_names[0]}_and_{len(display_names) - 1}_more_{digest}{suffix}" +class EmulatorPackOptions(TypedDict, total=False): + """The keyword options of generate_emulator_pack.""" + + zip_contents: dict | None + offline: bool | None + platforms_dir: str | None + pack_name: str | None + system_ids: list[str] | None + final_dir: str | None + record: PackRecord | None + + +@dataclass +class _EmulatorPackBuild: + """One emulator pack being written, and what each destination came to.""" + + db: dict + bios_dir: str + standalone: bool + required_only: bool + zip_contents: dict + data_registry: dict + validation_index: dict + region_drops: set[str] + all_profiles: dict + zf: zipfile.ZipFile | PackRecord + offline: bool | None = None + system_ids: list[str] | None = None + record: PackRecord | None = None + total_files: int = 0 + data_files: int = 0 + missing_files: list[str] = field(default_factory=list) + rejected_files: list[str] = field(default_factory=list) + discrepancies: list[str] = field(default_factory=list) + unsourceable_files: list[str] = field(default_factory=list) + instruction_files: list[str] = field(default_factory=list) + placed: _Placed = field(default_factory=lambda: _Placed(True)) + seen_hashes: set[str] = field(default_factory=set) # SHA1 dedup for same file, different path + # Loose file packed at each folded destination, to tell a profile asking + # for the same file there from one asking for other bytes. + packed_at: dict[str, str] = field(default_factory=dict) + # A destination is missing once, however many profiles ask for it: + # verify --emulator counts by destination. + missing_at: set[str] = field(default_factory=set) + data_dir_notices: list[str] = field(default_factory=list) + + def report_missing(self, name: str, destination: str) -> None: + if destination not in self.missing_at: + self.missing_at.add(destination) + self.missing_files.append(name) + + def _add(self, local_path: str, dest: str, fe: dict | None) -> None: + """Write a loose file or an archive at dest and count it.""" + if fe is not None and local_path.endswith(".zip"): + _add_zip_to_pack(local_path, dest, self.zf, fe) + else: + _add_pack_member(self.zf, local_path, dest) + self.placed.take(dest) + self.total_files += 1 + if self.record is not None: + self.record.files.append(dest) + + def pack_profile(self, emu_name: str, profile: dict) -> None: + pack_structure = profile.get("pack_structure") + files = expand_agnostic_entries( + expand_directory_entries( + deliverable(profile.get("files", []), self.standalone), + self.db, + self.standalone, + ), + emu_name, profile, self.db, self.standalone, self.all_profiles, + ) + if self.system_ids: + files = [ + fe for fe in files if entry_serves_systems(fe, profile, self.system_ids) + ] + if not files and not profile.get("data_directories"): + print(f" No files needed for {profile.get('emulator', emu_name)}") + + # What each destination came to, settled by set once the + # profile is read: a member another member fills is not missing, + # and a set nobody holds is reported once (alternatives.py). An + # archive unit is a member like a loose file. + outcomes: list[_Outcome] = [] + spares = emulator_required_spares( + emu_name, profile, files, self.standalone, self.region_drops, self.db, + self.validation_index, self.zip_contents, data_registry=self.data_registry, + ) if self.required_only else set() + + # Pack archives as units + archive_prefix = profile.get("archive_prefix", "") + for archive_name in sorted({fe["archive"] for fe in files if fe.get("archive")}): + archive_dest = _archive_destination( + archive_name, archive_prefix, pack_structure, self.standalone + ) + own_entry = archive_entry(archive_name, files) + if self.required_only and archive_is_optional(own_entry, archive_name, files): + continue + if archive_dest in spares: + continue + outcomes.append(self._pack_archive(own_entry, archive_name, archive_dest)) + + for dest, alternatives in self._slots(files, spares).items(): + outcome = self._pack_slot(emu_name, files, dest, alternatives) + if outcome is not None: + outcomes.append(outcome) + + excused, _standing = settle_sets([ + (slot_set_keys(emu_name, entries), entries[0], fills) + for entries, fills, _report in outcomes + ]) + for position, (_entries, _fills, report) in enumerate(outcomes): + if report is not None and position not in excused: + report() + self._pack_trees(profile, pack_structure) + + def _pack_archive(self, own_entry: dict, archive_name: str, archive_dest: str) -> _Outcome: + local_path, status = resolve_file( + own_entry, + self.db, + self.bios_dir, + self.zip_contents, + data_dir_registry=self.data_registry, + offline=self.offline, + ) + taken = archive_dest.lower() in self.placed.lower + if taken or self.placed.conflicts(archive_dest): + # Another profile's file holds this path. The same archive + # asked for twice is served. Anything else leaves this + # profile without its archive, which used to pass in + # silence: a neocdz.zip lacking 000-lo.lo shipped as the + # one the second core needs. + if not (taken and local_path and _same_bytes( + local_path, self.packed_at.get(archive_dest.lower()) + )): + return ([own_entry], False, functools.partial( + self.report_missing, archive_name, archive_dest + )) + return ([own_entry], True, None) + if local_path and status not in ("not_found",): + self._add(local_path, archive_dest, own_entry) + self.packed_at[archive_dest.lower()] = local_path + return ([own_entry], True, None) + return ([own_entry], False, functools.partial( + self.report_missing, archive_name, archive_dest + )) + + def _slots(self, files: list[dict], spares: set) -> dict[str, list[dict]]: + # Pack individual files (skip archive members). The entries of one + # profile on one destination are the releases the code accepts + # there (raze's seven SW.GRP): the first one the core accepts + # fills the slot, as verify --emulator credits it, and the slot + # has one outcome however many alternatives it lists. + slots: dict[str, list[dict]] = {} + for fe in files: + if self.required_only and fe.get("required") is False: + continue + if fe.get("archive"): + continue + dest = _resolve_destination(fe, self.standalone) + if not dest or dest in spares: + continue + if self.region_drops and dest in self.region_drops: + continue + slots.setdefault(dest, []).append(fe) + return slots + + def _write_instructions(self, provided: dict, dest: str) -> None: + # Instructions, not a file: written beside the slot the + # user fills, and counted apart from what the pack holds. + self.placed.take(dest) + instr = provided.get("instructions", "Please provide this file manually.") + folder = dest.rsplit("/", 1)[0] + "/" if "/" in dest else "" + _write_generated_member( + self.zf, + f"{folder}INSTRUCTIONS_{provided['name']}.txt", + f"File needed: {provided['name']}\n\n{instr}\n", + ) + # verify --emulator counts an unsourceable one as such. + (self.unsourceable_files if provided.get("unsourceable") else self.instruction_files).append( + provided["name"] + ) + + def _choose( + self, emu_name: str, files: list[dict], alternatives: list[dict], + ) -> tuple[tuple[dict, str, str | None] | None, str | None, str | None]: + """The alternative the core accepts, with the refusal of the first + one it turned away and that copy.""" + fallback: tuple[dict, str, str | None] | None = None + refusal: str | None = None + refused_path: str | None = None + for fe in alternatives: + local_path, status = resolve_file( + {**with_archive_members(fe, files), "source_profile": emu_name}, + self.db, + self.bios_dir, + self.zip_contents, + dest_hint=fe.get("path", ""), + data_dir_registry=self.data_registry, + offline=self.offline, + ) + if status == "external": + return (fe, "", "external"), refusal, refused_path + if status in ("not_found", "user_provided") or not local_path: + continue + # The file verify --emulator credits is the one shipped: + # a dump the core's own check rejects gives way to a held + # one it accepts (azahar's otp.bin, dolphin's dsp_rom.bin). + better, disagreement = validated_choice( + fe, local_path, self.db, self.validation_index, self.bios_dir, None, + emulators={emu_name}, + ) + if disagreement: + reason = disagreement.split(" says ", 1)[-1] + refusal = refusal or f"{fe['name']}: {reason}" + refused_path = refused_path or local_path + continue + if better != local_path: + return (fe, better, None), refusal, refused_path + if status == "hash_mismatch": + # Not a check the core runs, so the file still serves, + # but it is not the dump the profile documents. + fallback = fallback or (fe, local_path, "mismatch") + continue + return (fe, local_path, None), refusal, refused_path + return fallback, refusal, refused_path + + def _pack_slot( + self, emu_name: str, files: list[dict], dest: str, alternatives: list[dict], + ) -> _Outcome | None: + # Name order, first file wins, case folded: verify replays + # the rule and reports a later profile's file as missing. + block = self.placed.block(dest) + + provided = next( + (fe for fe in alternatives if fe.get("storage") == "user_provided"), + None, + ) + if provided is not None: + if not block: + self._write_instructions(provided, dest) + return None + + chosen, refusal, refused_path = self._choose(emu_name, files, alternatives) + if block: + held = ( + chosen[1] if chosen is not None and chosen[2] != "external" + else None if chosen is not None else refused_path + ) + if chosen is not None or held is not None: + if block == "taken" and held and _same_bytes( + held, self.packed_at.get(dest.lower()) + ): + # The file already at this path, asked for twice. + return (alternatives, True, None) + return (alternatives, False, functools.partial( + self.report_missing, alternatives[0]["name"], dest + )) + + if chosen is None: + return self._unfilled(alternatives, dest, refusal) + fe, local_path, how = chosen + if how == "external": + return self._pack_external(fe, dest, alternatives) + if how == "mismatch": + self.discrepancies.append( + f"{fe['name']}: not the dump the {emu_name} profile declares" + ) + + # SHA1 dedup: skip if same physical file AND same destination + # (but allow same file to be packed under different destinations, + # e.g., IPL.bin in GC/USA/ and GC/EUR/ from same source) + dedup_key_hash = f"{os.path.realpath(local_path)}:{dest}" + if dedup_key_hash not in self.seen_hashes: + self.seen_hashes.add(dedup_key_hash) + self._add(local_path, dest, fe) + self.packed_at[dest.lower()] = local_path + return (alternatives, True, None) + + def _unfilled(self, alternatives: list[dict], dest: str, refusal: str | None) -> _Outcome: + if refusal: + self.rejected_files.append(refusal) + return (alternatives, False, None) + if all(fe.get("unsourceable") for fe in alternatives): + return (alternatives, False, functools.partial( + self.unsourceable_files.append, alternatives[0]["name"] + )) + return (alternatives, False, functools.partial( + self.report_missing, alternatives[0]["name"], dest + )) + + def _pack_external(self, fe: dict, dest: str, alternatives: list[dict]) -> _Outcome: + file_ext = os.path.splitext(fe["name"])[1] or "" + with tempfile.NamedTemporaryFile( + delete=False, suffix=file_ext, dir=packresolve.scratch_dir() + ) as tmp: + tmp_path = tmp.name + try: + # Built in memory, nothing is fetched: verify --emulator + # cannot fetch either and reports the file missing. + if self.record is None and download_external(fe, tmp_path): + self._add(tmp_path, dest, None) + return (alternatives, True, None) + return (alternatives, False, functools.partial( + self.missing_files.append, fe["name"] + )) + finally: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + + def _pack_trees(self, profile: dict, pack_structure: dict | None) -> None: + # The trees after the files, as in a platform pack: a dump the + # profile declares wins over the copy a tree bundles at the same + # path (Dolphin's real dsp_rom.bin over Sys/GC's free one). + # A tree only one build reads follows that build, like a file. + required_only = self.required_only + for dd in deliverable( + profile.get("data_directories", []), self.standalone + ): + if required_only and dd.get("required") is False: + continue + ref_key = dd.get("ref", "") + if not ref_key or not self.data_registry or ref_key not in self.data_registry: + if ref_key: + self.data_dir_notices.append(ref_key) + continue + local_cache = self.data_registry[ref_key].get("local_cache", "") + if not local_cache or not os.path.isdir(local_cache): + self.data_dir_notices.append(ref_key) + continue + dd_dest = dd.get("destination", "") + if pack_structure: + mode_key = "standalone" if self.standalone else "libretro" + prefix = pack_structure.get(mode_key, "") + if prefix: + dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix + self.data_files += _pack_data_tree( + self.zf, local_cache, dd_dest, self.placed.destinations, + self.placed.parents, self.placed.lower, self.packed_at, + ) + + def nothing_needed(self) -> bool: + return self.total_files + self.data_files == 0 and not ( + self.missing_files or self.rejected_files or self.instruction_files + or self.unsourceable_files + ) + + def report(self, shown: str) -> None: + # Report. The members of data trees are counted apart: verify --emulator + # counts the profile's files, and folding 3500 tree members into the + # same number made the two impossible to compare. + parts = [f"{self.total_files} files packed"] + if self.data_files: + parts.append(f"{self.data_files} from data directories") + if self.missing_files: + parts.append(f"{len(self.missing_files)} missing") + if self.rejected_files: + parts.append(f"{len(self.rejected_files)} refused by the core") + if self.unsourceable_files: + parts.append(f"{len(self.unsourceable_files)} unsourceable") + if self.instruction_files: + parts.append(f"{len(self.instruction_files)} to provide") + print(f" {shown}: {', '.join(parts)}") + for name in self.missing_files: + print(f" MISSING: {name}") + for name in self.unsourceable_files: + print(f" UNSOURCEABLE: {name}") + for name in self.instruction_files: + print(f" TO PROVIDE: {name} (instructions in the pack)") + for line in self.rejected_files: + print(f" REFUSED: {line}") + for line in self.discrepancies: + print(f" DISCREPANCY: {line}") + for ref in sorted(set(self.data_dir_notices)): + print( + f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)" + ) + _MISSING_DATA_DIRS.update(self.data_dir_notices) + + def generate_emulator_pack( profile_names: list[str], emulators_dir: str, @@ -1719,15 +2369,10 @@ def generate_emulator_pack( bios_dir: str, output_dir: str, standalone: bool = False, - zip_contents: dict | None = None, + *, required_only: bool = False, regions: list[str] | None = None, - offline: bool | None = None, - platforms_dir: str | None = None, - pack_name: str | None = None, - system_ids: list[str] | None = None, - final_dir: str | None = None, - record: PackRecord | None = None, + **options: Unpack[EmulatorPackOptions], ) -> str | None: """Generate a ZIP pack for specific emulator profiles. @@ -1742,7 +2387,9 @@ def generate_emulator_pack( `record` builds the pack in memory instead (PackRecord): nothing is written or read, and the paths are kept on it. """ + _reject_unknown("generate_emulator_pack", options, EmulatorPackOptions.__optional_keys__) all_profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) + zip_contents = options.get("zip_contents") if zip_contents is None: zip_contents = build_zip_contents_index(db) @@ -1752,6 +2399,7 @@ def generate_emulator_pack( print(f"Error: {exc}", file=sys.stderr) return None + record = options.get("record") # ZIP naming display_names = [_name_part(p.get("emulator", n)) for n, p in selected] validation_index = _build_validation_index(dict(selected)) @@ -1761,7 +2409,7 @@ def generate_emulator_pack( "full", regions, None, False, required_only, standalone ) ) - zip_name = pack_name or _bounded_pack_name( + zip_name = options.get("pack_name") or _bounded_pack_name( display_names, [n for n, _p in selected], f"{narrow_tags}_BIOS_Pack.zip" ) zip_path = os.path.join(output_dir, zip_name) @@ -1769,7 +2417,7 @@ def generate_emulator_pack( os.makedirs(output_dir, exist_ok=True) data_registry = load_data_dir_registry( - platforms_dir or os.path.join(os.path.dirname(__file__), "..", "platforms") + options.get("platforms_dir") or os.path.join(os.path.dirname(__file__), "..", "platforms") ) region_drops: set[str] = ( emulator_region_drops( @@ -1779,345 +2427,20 @@ def generate_emulator_pack( if regions else set() ) - - total_files = 0 - data_files = 0 - missing_files = [] - rejected_files: list[str] = [] - discrepancies: list[str] = [] - unsourceable_files: list[str] = [] - instruction_files: list[str] = [] - seen_destinations: set[str] = set() - seen_lower: set[str] = set() - seen_parents: set[str] = ( - set() - ) # parent dirs of added files (path conflict detection) - seen_hashes: set[str] = set() # SHA1 dedup for same file, different path - # Loose file packed at each folded destination, to tell a profile asking - # for the same file there from one asking for other bytes. - packed_at: dict[str, str] = {} - # A destination is missing once, however many profiles ask for it: - # verify --emulator counts by destination. - missing_at: set[str] = set() - - def report_missing(name: str, destination: str) -> None: - if destination not in missing_at: - missing_at.add(destination) - missing_files.append(name) - - data_dir_notices: list[str] = [] - with ( contextlib.nullcontext(record) if record is not None else _writing_pack(zip_path) ) as zf: + build = _EmulatorPackBuild( + db, bios_dir, standalone, required_only, zip_contents, data_registry, + validation_index, region_drops, all_profiles, zf, + offline=options.get("offline"), system_ids=options.get("system_ids"), record=record, + ) for emu_name, profile in sorted(selected): - pack_structure = profile.get("pack_structure") - files = expand_agnostic_entries( - expand_directory_entries( - deliverable(profile.get("files", []), standalone), - db, - standalone, - ), - emu_name, profile, db, standalone, all_profiles, - ) - if system_ids: - files = [ - fe for fe in files if entry_serves_systems(fe, profile, system_ids) - ] - if not files and not profile.get("data_directories"): - print(f" No files needed for {profile.get('emulator', emu_name)}") - - archives: set[str] = set() - for fe in files: - archive = fe.get("archive") - if archive: - archives.add(archive) - - # What each destination came to, settled by set once the - # profile is read: a member another member fills is not missing, - # and a set nobody holds is reported once (alternatives.py). An - # archive unit is a member like a loose file. - outcomes: list[tuple[list[dict], bool, Callable[[], None] | None]] = [] - spares = emulator_required_spares( - emu_name, profile, files, standalone, region_drops, db, - validation_index, zip_contents, data_registry, - ) if required_only else set() - - # Pack archives as units - archive_prefix = profile.get("archive_prefix", "") - for archive_name in sorted(archives): - archive_dest = _archive_destination( - archive_name, archive_prefix, pack_structure, standalone - ) - - own_entry = archive_entry(archive_name, files) - if required_only and archive_is_optional(own_entry, archive_name, files): - continue - if archive_dest in spares: - continue - local_path, status = resolve_file( - own_entry, - db, - bios_dir, - zip_contents, - data_dir_registry=data_registry, - offline=offline, - ) - taken = archive_dest.lower() in seen_lower - if taken or _has_path_conflict(archive_dest, seen_destinations, seen_parents): - # Another profile's file holds this path. The same archive - # asked for twice is served. Anything else leaves this - # profile without its archive, which used to pass in - # silence: a neocdz.zip lacking 000-lo.lo shipped as the - # one the second core needs. - if not (taken and local_path and _same_bytes( - local_path, packed_at.get(archive_dest.lower()) - )): - outcomes.append(([own_entry], False, functools.partial( - report_missing, archive_name, archive_dest - ))) - else: - outcomes.append(([own_entry], True, None)) - continue - if local_path and status not in ("not_found",): - if local_path.endswith(".zip"): - _add_zip_to_pack(local_path, archive_dest, zf, own_entry) - else: - _add_pack_member(zf, local_path, archive_dest) - seen_destinations.add(archive_dest) - _register_path(archive_dest, seen_destinations, seen_parents) - seen_lower.add(archive_dest.lower()) - packed_at[archive_dest.lower()] = local_path - total_files += 1 - if record is not None: - record.files.append(archive_dest) - outcomes.append(([own_entry], True, None)) - else: - outcomes.append(([own_entry], False, functools.partial( - report_missing, archive_name, archive_dest - ))) - - # Pack individual files (skip archive members). The entries of one - # profile on one destination are the releases the code accepts - # there (raze's seven SW.GRP): the first one the core accepts - # fills the slot, as verify --emulator credits it, and the slot - # has one outcome however many alternatives it lists. - slots: dict[str, list[dict]] = {} - for fe in files: - if required_only and fe.get("required") is False: - continue - if fe.get("archive"): - continue - dest = _resolve_destination(fe, standalone) - if not dest or dest in spares: - continue - if region_drops and dest in region_drops: - continue - slots.setdefault(dest, []).append(fe) - - for dest, alternatives in slots.items(): - # Name order, first file wins, case folded: verify replays - # the rule and reports a later profile's file as missing. - block = placement_block( - dest, seen_destinations, seen_lower, seen_parents, True - ) - - provided = next( - (fe for fe in alternatives if fe.get("storage") == "user_provided"), - None, - ) - if provided is not None and block: - continue - if provided is not None: - # Instructions, not a file: written beside the slot the - # user fills, and counted apart from what the pack holds. - seen_destinations.add(dest) - _register_path(dest, seen_destinations, seen_parents) - seen_lower.add(dest.lower()) - instr = provided.get("instructions", "Please provide this file manually.") - folder = dest.rsplit("/", 1)[0] + "/" if "/" in dest else "" - _write_generated_member( - zf, - f"{folder}INSTRUCTIONS_{provided['name']}.txt", - f"File needed: {provided['name']}\n\n{instr}\n", - ) - # verify --emulator counts an unsourceable one as such. - (unsourceable_files if provided.get("unsourceable") else instruction_files).append( - provided["name"] - ) - continue - - chosen: tuple[dict, str, str | None] | None = None - fallback: tuple[dict, str, str | None] | None = None - refusal: str | None = None - refused_path: str | None = None - for fe in alternatives: - local_path, status = resolve_file( - {**with_archive_members(fe, files), "source_profile": emu_name}, - db, - bios_dir, - zip_contents, - dest_hint=fe.get("path", ""), - data_dir_registry=data_registry, - offline=offline, - ) - if status == "external": - chosen = (fe, "", "external") - break - if status in ("not_found", "user_provided") or not local_path: - continue - # The file verify --emulator credits is the one shipped: - # a dump the core's own check rejects gives way to a held - # one it accepts (azahar's otp.bin, dolphin's dsp_rom.bin). - better, disagreement = validated_choice( - fe, local_path, db, validation_index, bios_dir, None, - emulators={emu_name}, - ) - if disagreement: - reason = disagreement.split(" says ", 1)[-1] - refusal = refusal or f"{fe['name']}: {reason}" - refused_path = refused_path or local_path - continue - if better != local_path: - chosen = (fe, better, None) - break - if status == "hash_mismatch": - # Not a check the core runs, so the file still serves, - # but it is not the dump the profile documents. - fallback = fallback or (fe, local_path, "mismatch") - continue - chosen = (fe, local_path, None) - break - chosen = chosen or fallback - - if block: - held = ( - chosen[1] if chosen is not None and chosen[2] != "external" - else None if chosen is not None else refused_path - ) - if chosen is not None or held is not None: - if block == "taken" and held and _same_bytes( - held, packed_at.get(dest.lower()) - ): - # The file already at this path, asked for twice. - outcomes.append((alternatives, True, None)) - continue - outcomes.append((alternatives, False, functools.partial( - report_missing, alternatives[0]["name"], dest - ))) - continue - - if chosen is None: - if refusal: - rejected_files.append(refusal) - outcomes.append((alternatives, False, None)) - elif all(fe.get("unsourceable") for fe in alternatives): - outcomes.append((alternatives, False, functools.partial( - unsourceable_files.append, alternatives[0]["name"] - ))) - else: - outcomes.append((alternatives, False, functools.partial( - report_missing, alternatives[0]["name"], dest - ))) - continue - - fe, local_path, how = chosen - if how == "external": - file_ext = os.path.splitext(fe["name"])[1] or "" - with tempfile.NamedTemporaryFile( - delete=False, suffix=file_ext, dir=packresolve.scratch_dir() - ) as tmp: - tmp_path = tmp.name - try: - # Built in memory, nothing is fetched: verify --emulator - # cannot fetch either and reports the file missing. - if record is None and download_external(fe, tmp_path): - _add_pack_member(zf, tmp_path, dest) - seen_destinations.add(dest) - _register_path(dest, seen_destinations, seen_parents) - seen_lower.add(dest.lower()) - total_files += 1 - if record is not None: - record.files.append(dest) - outcomes.append((alternatives, True, None)) - else: - outcomes.append((alternatives, False, functools.partial( - missing_files.append, fe["name"] - ))) - finally: - if os.path.exists(tmp_path): - os.unlink(tmp_path) - continue - if how == "mismatch": - discrepancies.append( - f"{fe['name']}: not the dump the {emu_name} profile declares" - ) - - # SHA1 dedup: skip if same physical file AND same destination - # (but allow same file to be packed under different destinations, - # e.g., IPL.bin in GC/USA/ and GC/EUR/ from same source) - dedup_key_hash = f"{os.path.realpath(local_path)}:{dest}" - outcomes.append((alternatives, True, None)) - if dedup_key_hash in seen_hashes: - continue - seen_hashes.add(dedup_key_hash) - - if local_path.endswith(".zip"): - _add_zip_to_pack(local_path, dest, zf, fe) - else: - _add_pack_member(zf, local_path, dest) - seen_destinations.add(dest) - _register_path(dest, seen_destinations, seen_parents) - seen_lower.add(dest.lower()) - packed_at[dest.lower()] = local_path - total_files += 1 - if record is not None: - record.files.append(dest) - - excused, _standing = settle_sets([ - (slot_set_keys(emu_name, entries), entries[0], fills) - for entries, fills, _report in outcomes - ]) - for position, (_entries, _fills, report) in enumerate(outcomes): - if report is not None and position not in excused: - report() - - # The trees after the files, as in a platform pack: a dump the - # profile declares wins over the copy a tree bundles at the same - # path (Dolphin's real dsp_rom.bin over Sys/GC's free one). - # A tree only one build reads follows that build, like a file. - for dd in deliverable( - profile.get("data_directories", []), standalone - ): - if required_only and dd.get("required") is False: - continue - ref_key = dd.get("ref", "") - if not ref_key or not data_registry or ref_key not in data_registry: - if ref_key: - data_dir_notices.append(ref_key) - continue - entry = data_registry[ref_key] - local_cache = entry.get("local_cache", "") - if not local_cache or not os.path.isdir(local_cache): - data_dir_notices.append(ref_key) - continue - dd_dest = dd.get("destination", "") - if pack_structure: - mode_key = "standalone" if standalone else "libretro" - prefix = pack_structure.get(mode_key, "") - if prefix: - dd_dest = f"{prefix}/{dd_dest}" if dd_dest else prefix - data_files += _pack_data_tree( - zf, local_cache, dd_dest, seen_destinations, seen_parents, seen_lower, - packed_at, - ) + build.pack_profile(emu_name, profile) # Remove empty ZIP (no files packed and no missing = nothing to ship) - nothing_needed = total_files + data_files == 0 and not ( - missing_files or rejected_files or instruction_files or unsourceable_files - ) - if record is None and nothing_needed: + if record is None and build.nothing_needed(): os.unlink(zip_path) # What verify --emulator reports as 0/0 OK: no file is needed, so # no pack is written and the run succeeds. Printed with the path, @@ -2125,46 +2448,18 @@ def generate_emulator_pack( print(f" {', '.join(display_names)}: no file needed, no pack written") return "" - # Report. The members of data trees are counted apart: verify --emulator - # counts the profile's files, and folding 3500 tree members into the - # same number made the two impossible to compare. - missing_count = len(missing_files) - ok_count = total_files - parts = [f"{ok_count} files packed"] - if data_files: - parts.append(f"{data_files} from data directories") - if missing_count: - parts.append(f"{missing_count} missing") - if rejected_files: - parts.append(f"{len(rejected_files)} refused by the core") - if unsourceable_files: - parts.append(f"{len(unsourceable_files)} unsourceable") - if instruction_files: - parts.append(f"{len(instruction_files)} to provide") - shown = os.path.join(final_dir, zip_name) if final_dir else zip_path - print(f" {shown}: {', '.join(parts)}") - for name in missing_files: - print(f" MISSING: {name}") - for name in unsourceable_files: - print(f" UNSOURCEABLE: {name}") - for name in instruction_files: - print(f" TO PROVIDE: {name} (instructions in the pack)") - for line in rejected_files: - print(f" REFUSED: {line}") - for line in discrepancies: - print(f" DISCREPANCY: {line}") - for ref in sorted(set(data_dir_notices)): - print( - f" Note: data directory '{ref}' required but not included (use refresh_data_dirs.py)" - ) - _MISSING_DATA_DIRS.update(data_dir_notices) + final_dir = options.get("final_dir") + build.report(os.path.join(final_dir, zip_name) if final_dir else zip_path) + return None if build.nothing_needed() else zip_path - return ( - zip_path - if total_files + data_files > 0 or missing_files or rejected_files or instruction_files - or unsourceable_files - else None - ) + +class SystemPackOptions(TypedDict, total=False): + """The keyword options of generate_system_pack.""" + + required_only: bool + regions: list[str] | None + offline: bool | None + platforms_dir: str | None def generate_system_pack( @@ -2175,15 +2470,17 @@ def generate_system_pack( output_dir: str, standalone: bool = False, zip_contents: dict | None = None, - required_only: bool = False, - regions: list[str] | None = None, - offline: bool | None = None, - platforms_dir: str | None = None, + **options: Unpack[SystemPackOptions], ) -> str | None: """Generate a ZIP pack for all emulators supporting given system IDs. Returns the path, "" when no file is needed, None on failure. """ + _reject_unknown("generate_system_pack", options, SystemPackOptions.__optional_keys__) + required_only = options.get("required_only", False) + regions = options.get("regions") + offline = options.get("offline") + platforms_dir = options.get("platforms_dir") profiles = load_emulator_profiles(emulators_dir) matching = profiles_for_systems(profiles, system_ids, standalone) @@ -2237,7 +2534,7 @@ def generate_system_pack( bios_dir, scratch, standalone, - zip_contents, + zip_contents=zip_contents, required_only=required_only, regions=regions, offline=offline, @@ -2281,6 +2578,40 @@ def _group_systems_by_manufacturer( return groups +class SplitOptions(PackNarrowing, total=False): + """The keyword options of generate_split_packs.""" + + records: dict[str, PackRecord] | None + + +def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict]: + """The core extras of every part, collected once (expensive: scans 260+ + emulator profiles), then distributed per group by system overlap.""" + emu_profiles = narrowing["emu_profiles"] or {} + source = narrowing["source"] + target_cores = narrowing["target_cores"] + base_dest = config.get("base_destination", "") + # Each part cuts the platform's own entries from the full profiles. The + # extras are collected once here, already without the cores' game data. + cut = ( + without_game_data(config, emu_profiles, narrowing["data_registry"], target_cores) + if narrowing["no_game_data"] else None + ) + if source == "platform": + all_extras = [] + elif emu_profiles: + all_extras = _collect_emulator_extras( + cut.config if cut else config, narrowing["emulators_dir"], db, + set(), base_dest, cut.profiles if cut else emu_profiles, + target_cores=target_cores, include_all=(source == "truth"), + ) + else: + all_extras = [] + if cut is not None and source != "platform": + _report_left_out(cut, systems=set(), cores=True) + return all_extras + + def generate_split_packs( platform_name: str, platforms_dir: str, @@ -2288,19 +2619,7 @@ def generate_split_packs( bios_dir: str, output_dir: str, group_by: str = "system", - emulators_dir: str = "emulators", - zip_contents: dict | None = None, - data_registry: dict | None = None, - emu_profiles: dict | None = None, - target_cores: set[str] | None = None, - required_only: bool = False, - source: str = "full", - regions: list[str] | None = None, - target_name: str | None = None, - one_per_slot: bool = False, - offline: bool | None = None, - no_game_data: bool = False, - records: dict[str, PackRecord] | None = None, + **options: Unpack[SplitOptions], ) -> list[str]: """Generate split packs (one ZIP per system or manufacturer). @@ -2308,14 +2627,31 @@ def generate_split_packs( own placement (``within``). ``records`` builds the parts in memory, keyed by part name, with no archive written. """ + _reject_unknown("generate_split_packs", options, SplitOptions.__optional_keys__) config = load_platform_config(platform_name, platforms_dir) + records = options.get("records") + narrowing: PackNarrowing = { + "emulators_dir": options.get("emulators_dir", "emulators"), + "zip_contents": options.get("zip_contents"), + "data_registry": options.get("data_registry"), + "emu_profiles": options.get("emu_profiles"), + "target_cores": options.get("target_cores"), + "required_only": options.get("required_only", False), + "source": options.get("source", "full"), + "regions": options.get("regions"), + "target_name": options.get("target_name"), + "one_per_slot": options.get("one_per_slot", False), + "offline": options.get("offline"), + "no_game_data": options.get("no_game_data", False), + } # The split directory carries the same tags as the packs inside it, or two # differently narrowed runs write into one another. split_tags = "".join( tag for tag, _label in _narrowings( - source, regions, target_name, one_per_slot, required_only, - no_game_data=no_game_data, + narrowing["source"], narrowing["regions"], narrowing["target_name"], + narrowing["one_per_slot"], narrowing["required_only"], + no_game_data=narrowing["no_game_data"], ) ) # Two groupings write different files. Without the tag they accumulate in @@ -2333,16 +2669,10 @@ def generate_split_packs( if records is None: os.makedirs(split_dir, exist_ok=True) + emu_profiles = narrowing["emu_profiles"] if emu_profiles is None: - emu_profiles = load_emulator_profiles(emulators_dir) - narrowing = { - "emulators_dir": emulators_dir, "zip_contents": zip_contents, - "data_registry": data_registry, "emu_profiles": emu_profiles, - "target_cores": target_cores, "required_only": required_only, - "source": source, "regions": regions, "target_name": target_name, - "one_per_slot": one_per_slot, "offline": offline, - "no_game_data": no_game_data, - } + emu_profiles = load_emulator_profiles(narrowing["emulators_dir"]) + narrowing["emu_profiles"] = emu_profiles full = PackRecord() with contextlib.redirect_stdout(io.StringIO()): generate_pack( @@ -2350,52 +2680,32 @@ def generate_split_packs( record=full, **narrowing, ) - def part(pack_name: str, **scope: object) -> str | None: + def part(pack_name: str, scope: _PartScope) -> str | None: record = PackRecord() if records is not None else None zip_path = generate_pack( platform_name, platforms_dir, db, bios_dir, split_dir, pack_name=pack_name, record=record, within=full.sources, **scope, **narrowing, ) - if record is not None and zip_path: + if records is not None and record is not None and zip_path: records[pack_name] = record return zip_path # The systems a core of the target runs: a part per declared system sent # each one the target drops to a refusal naming it as unknown. - systems = platform_scope_systems(config, emu_profiles, target_cores) + systems = platform_scope_systems(config, emu_profiles, narrowing["target_cores"]) if group_by == "manufacturer": groups = _group_systems_by_manufacturer(systems, db, bios_dir) else: groups = {_system_display_name(sid): [sid] for sid in systems} - # Pre-compute core extras once (expensive: scans 260+ emulator profiles) - # then distribute per group based on emulator system overlap - base_dest = config.get("base_destination", "") - # Each part cuts the platform's own entries from the full profiles. The - # extras are collected once here, already without the cores' game data. - cut = ( - without_game_data(config, emu_profiles, data_registry, target_cores) - if no_game_data else None - ) - if source == "platform": - all_extras = [] - elif emu_profiles: - all_extras = _collect_emulator_extras( - cut.config if cut else config, emulators_dir, db, set(), base_dest, - cut.profiles if cut else emu_profiles, - target_cores=target_cores, include_all=(source == "truth"), - ) - else: - all_extras = [] - if cut is not None and source != "platform": - _report_left_out(cut, systems=set(), cores=True) + all_extras = _split_extras(config, db, narrowing) results = [] for group_name, group_system_ids in sorted(groups.items()): group_extras = _extras_for_systems(all_extras, group_system_ids) zip_path = part( f"{part_prefix}_{_name_part(group_name, '_')}_BIOS_Pack.zip", - system_filter=group_system_ids, precomputed_extras=group_extras, + {"system_filter": group_system_ids, "precomputed_extras": group_extras}, ) if zip_path: results.append(zip_path) @@ -2413,7 +2723,7 @@ def generate_split_packs( if undistributed: zip_path = part( f"{part_prefix}_Other_Cores_BIOS_Pack.zip", - precomputed_extras=undistributed, extras_only=True, + {"precomputed_extras": undistributed, "extras_only": True}, ) if zip_path: results.append(zip_path) @@ -2448,23 +2758,44 @@ def _entry_for_file(candidates: list[dict], held: dict) -> dict: return candidates[-1] -def generate_md5_pack( - hashes: list[tuple[str, str]], - db: dict, - bios_dir: str, - output_dir: str, - zip_contents: dict | None = None, - platform_name: str | None = None, - platforms_dir: str | None = None, - emulator_name: str | None = None, - emulators_dir: str | None = None, - standalone: bool = False, -) -> str | None: - """Build a pack from an explicit list of hashes with layout context.""" - files_db = db.get("files", {}) - if zip_contents is None: - zip_contents = {} +class Md5PackOptions(TypedDict, total=False): + """The keyword options of generate_md5_pack: the layout to follow.""" + platform_name: str | None + platforms_dir: str | None + emulator_name: str | None + emulators_dir: str | None + standalone: bool + + +@dataclass(frozen=True) +class _Md5Settings: + """Md5PackOptions with their defaults.""" + + platform_name: str | None = None + platforms_dir: str | None = None + emulator_name: str | None = None + emulators_dir: str | None = None + standalone: bool = False + + +@dataclass(frozen=True) +class _Md5Layout: + """Where a hash-selected pack puts each file: the declarations by + lowercased name, the platform's base destination, and the pack's name.""" + + index: dict[str, list[dict]] + base_dest: str + context_name: str + + +def _md5_layout(opts: _Md5Settings) -> _Md5Layout | None: + """The platform or emulator layout a hash list is packed in, or None + when the emulator named is refused.""" + platform_name = opts.platform_name + platforms_dir = opts.platforms_dir + emulator_name = opts.emulator_name + emulators_dir = opts.emulators_dir plat_file_index: dict[str, list[dict]] = {} base_dest = "" plat_display = "Custom" @@ -2472,7 +2803,7 @@ def generate_md5_pack( config = load_platform_config(platform_name, platforms_dir) base_dest = config.get("base_destination", "") plat_display = config.get("platform", platform_name) - for _sys_id, system in config.get("systems", {}).items(): + for system in config.get("systems", {}).values(): for fe in system.get("files", []): plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe) @@ -2484,7 +2815,7 @@ def generate_md5_pack( # core with no standalone build has no standalone layout either. try: (_name, profile), = select_emulator_profiles( - [emulator_name], profiles, standalone + [emulator_name], profiles, opts.standalone ) except ProfileSelectionError as exc: print(f"Error: {exc}", file=sys.stderr) @@ -2496,17 +2827,26 @@ def generate_md5_pack( plat_file_index.setdefault(alias.lower(), []).append(fe) context_name = plat_display if platform_name else (emu_display or "Custom") + return _Md5Layout(plat_file_index, base_dest, context_name) + + +def _md5_pack_name( + context_name: str, hashes: list[tuple[str, str]], opts: _Md5Settings, +) -> str: + """The file name of a hash-selected pack.""" # The selection mode is part of the name, as for --system: BizHawk is # both a platform and a profile display name, and the two layouts # (Firmware/ under the platform, the profile's paths under the core) # wrote one file, the second run replacing the first without a word. - mode_part = "_Emulator" if emulator_name and not platform_name else "" + mode_part = ( + "_Emulator" if opts.emulator_name and not opts.platform_name else "" + ) # --standalone changes the destination layout, so a run with it must not # take the name of a run without it. custom_tags = "".join( tag for tag, _label in _narrowings( - "full", None, None, False, False, standalone=standalone + "full", None, None, False, False, standalone=opts.standalone ) ) # The hash list is what chooses the content: two lists under one name @@ -2514,11 +2854,58 @@ def generate_md5_pack( selection = hashlib.sha1( "\n".join(sorted(f"{kind}:{value.lower()}" for kind, value in hashes)).encode() ).hexdigest()[:8] - zip_name = ( + return ( f"{_name_part(context_name, '_')}{mode_part}_Custom_{selection}{custom_tags}" "_BIOS_Pack.zip" ) - zip_path = os.path.join(output_dir, zip_name) + + +def _md5_destination(entry: dict, layout: _Md5Layout, opts: _Md5Settings) -> str: + """Where a held file goes in a hash-selected pack.""" + name = entry.get("name", "") + aliases = entry.get("aliases") or [] + paths = entry.get("paths") or [] + + dest = name + matched_fe = None + for lookup_name in [name] + aliases: + if lookup_name.lower() in layout.index: + matched_fe = _entry_for_file(layout.index[lookup_name.lower()], entry) + break + + if matched_fe: + if opts.emulator_name: + # Laid out as the emulator pack lays it out: its path and + # its standalone_path, which --standalone has to reach. + dest = _resolve_destination(matched_fe, opts.standalone) + else: + dest = matched_fe.get("destination", matched_fe.get("name", name)) + elif paths: + dest = paths[0] + + if layout.base_dest and not dest.startswith(layout.base_dest): + return f"{layout.base_dest}/{dest}" + return dest + + +def generate_md5_pack( + hashes: list[tuple[str, str]], + db: dict, + bios_dir: str, + output_dir: str, + zip_contents: dict | None = None, + **options: Unpack[Md5PackOptions], +) -> str | None: + """Build a pack from an explicit list of hashes with layout context.""" + files_db = db.get("files", {}) + if zip_contents is None: + zip_contents = {} + _reject_unknown("generate_md5_pack", options, Md5PackOptions.__optional_keys__) + opts = _Md5Settings(**options) + layout = _md5_layout(opts) + if layout is None: + return None + zip_path = os.path.join(output_dir, _md5_pack_name(layout.context_name, hashes, opts)) os.makedirs(output_dir, exist_ok=True) packed: list[tuple[str, str]] = [] @@ -2535,33 +2922,7 @@ def generate_md5_pack( entry = files_db[sha1] name = entry.get("name", "") - aliases = entry.get("aliases") or [] - paths = entry.get("paths") or [] - - dest = name - matched_fe = None - for lookup_name in [name] + aliases: - if lookup_name.lower() in plat_file_index: - matched_fe = _entry_for_file( - plat_file_index[lookup_name.lower()], entry - ) - break - - if matched_fe: - if emulator_name: - # Laid out as the emulator pack lays it out: its path and - # its standalone_path, which --standalone has to reach. - dest = _resolve_destination(matched_fe, standalone) - else: - dest = matched_fe.get("destination", matched_fe.get("name", name)) - elif paths: - dest = paths[0] - - if base_dest and not dest.startswith(base_dest): - full_dest = f"{base_dest}/{dest}" - else: - full_dest = dest - + full_dest = _md5_destination(entry, layout, opts) if full_dest in seen: continue seen.add(full_dest) @@ -2829,96 +3190,76 @@ def _refuse_for_verify_packs(args: argparse.Namespace, parser: argparse.Argument parser.error(f"{flag} is incompatible with --verify-packs") -def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: - """Validate argument combinations and mutual exclusion rules.""" - _refuse_for_verify_packs(args, parser) +def _argument_conflicts(args: argparse.Namespace) -> list[tuple[bool, str]]: + """Each refused combination of arguments with its message, in the order + they are checked: the first one that applies is the error reported.""" has_platform = bool(args.platform) has_all = args.all has_emulator = bool(args.emulator) has_system = bool(args.system) - has_from_md5 = bool(args.from_md5 or getattr(args, "from_md5_file", None)) - - if args.from_md5 and getattr(args, "from_md5_file", None): - parser.error("--from-md5 and --from-md5-file are mutually exclusive") - if has_from_md5 and has_all: - parser.error("--from-md5 requires --platform or --emulator, not --all") - if has_from_md5 and has_system: - parser.error("--from-md5 and --system are mutually exclusive") - if has_from_md5 and args.split: - parser.error("--split and --from-md5 are mutually exclusive") - - # --platform/--all and --system can combine (system filters within platform) - # --emulator is exclusive with everything else - if has_emulator and (has_platform or has_all or has_system): - parser.error( - "--emulator is mutually exclusive with --platform, --all, and --system" - ) - if has_platform and has_all: - parser.error("--platform and --all are mutually exclusive") - if not (has_platform or has_all or has_emulator or has_system or has_from_md5): - parser.error("Specify --platform, --all, --emulator, --system, or --from-md5") - if args.standalone and not ( - has_emulator or (has_system and not has_platform and not has_all) - ): - parser.error( - "--standalone requires --emulator or --system (without --platform)" - ) - if args.split and not (has_platform or has_all): - parser.error("--split requires --platform or --all") - if args.split and has_emulator: - parser.error("--split is incompatible with --emulator") - if args.group_by is not None and not args.split: - parser.error("--group-by requires --split") - if args.target and not (has_platform or has_all): - parser.error("--target requires --platform or --all") - if args.target and has_emulator: - parser.error("--target is incompatible with --emulator") - if args.manifest and not (has_platform or has_all): - parser.error("--manifest requires --platform or --all") - if args.manifest and has_emulator: - parser.error("--manifest is incompatible with --emulator") - if args.manifest and args.split: - parser.error("--manifest is incompatible with --split") - if getattr(args, "region", None) and has_from_md5: - parser.error("--region and --from-md5 are mutually exclusive") + md5_file = getattr(args, "from_md5_file", None) + has_from_md5 = bool(args.from_md5 or md5_file) # A mode either applies a narrowing flag or refuses it. Swallowing one # answers about an artifact the caller did not ask for, and the name on # disk then asserts a narrowing the contents do not carry. # --source and --group-by default to None so a typed default value is # seen: compared with "full", `--emulator X --source full` went through. source_given = getattr(args, "source", None) is not None - if source_given and (has_emulator or (has_system and not has_platform)): - parser.error("--source requires --platform or --all") - if has_from_md5: - for flag, given in ( - ("--manifest", args.manifest), - ("--target", args.target), - ("--required-only", args.required_only), - ("--source", source_given), - ): - if given: - parser.error(f"{flag} is incompatible with --from-md5") - if has_system and (has_platform or has_all): - if args.manifest: - parser.error("--system is incompatible with --manifest") - if args.split: - parser.error("--system is incompatible with --split") - + with_platform = has_system and (has_platform or has_all) # Game data is categorized against a platform's list and the cores it # runs: a pack of one emulator or of a system's emulators has neither. - if getattr(args, "no_game_data", False) and not (has_platform or has_all): - parser.error("--no-game-data requires --platform or --all") - if getattr(args, "no_game_data", False) and has_from_md5: - parser.error("--no-game-data is incompatible with --from-md5") - if getattr(args, "one_per_slot", False): - if has_from_md5: - parser.error("--one-per-slot and --from-md5 are mutually exclusive") - if args.manifest: - parser.error("--one-per-slot is incompatible with --manifest") - if has_emulator: - parser.error("--one-per-slot is incompatible with --emulator") - if has_system: - parser.error("--one-per-slot is incompatible with --system") + no_game_data = getattr(args, "no_game_data", False) + one_per_slot = getattr(args, "one_per_slot", False) + return [ + (bool(args.from_md5 and md5_file), "--from-md5 and --from-md5-file are mutually exclusive"), + (has_from_md5 and has_all, "--from-md5 requires --platform or --emulator, not --all"), + (has_from_md5 and has_system, "--from-md5 and --system are mutually exclusive"), + (has_from_md5 and args.split, "--split and --from-md5 are mutually exclusive"), + # --platform/--all and --system can combine (system filters within platform) + # --emulator is exclusive with everything else + (has_emulator and (has_platform or has_all or has_system), + "--emulator is mutually exclusive with --platform, --all, and --system"), + (has_platform and has_all, "--platform and --all are mutually exclusive"), + (not (has_platform or has_all or has_emulator or has_system or has_from_md5), + "Specify --platform, --all, --emulator, --system, or --from-md5"), + (args.standalone and not ( + has_emulator or (has_system and not has_platform and not has_all) + ), "--standalone requires --emulator or --system (without --platform)"), + (args.split and not (has_platform or has_all), "--split requires --platform or --all"), + (args.split and has_emulator, "--split is incompatible with --emulator"), + (args.group_by is not None and not args.split, "--group-by requires --split"), + (args.target and not (has_platform or has_all), "--target requires --platform or --all"), + (args.target and has_emulator, "--target is incompatible with --emulator"), + (args.manifest and not (has_platform or has_all), + "--manifest requires --platform or --all"), + (args.manifest and has_emulator, "--manifest is incompatible with --emulator"), + (args.manifest and args.split, "--manifest is incompatible with --split"), + (getattr(args, "region", None) and has_from_md5, + "--region and --from-md5 are mutually exclusive"), + (source_given and (has_emulator or (has_system and not has_platform)), + "--source requires --platform or --all"), + (has_from_md5 and args.manifest, "--manifest is incompatible with --from-md5"), + (has_from_md5 and args.target, "--target is incompatible with --from-md5"), + (has_from_md5 and args.required_only, "--required-only is incompatible with --from-md5"), + (has_from_md5 and source_given, "--source is incompatible with --from-md5"), + (with_platform and args.manifest, "--system is incompatible with --manifest"), + (with_platform and args.split, "--system is incompatible with --split"), + (no_game_data and not (has_platform or has_all), + "--no-game-data requires --platform or --all"), + (no_game_data and has_from_md5, "--no-game-data is incompatible with --from-md5"), + (one_per_slot and has_from_md5, "--one-per-slot and --from-md5 are mutually exclusive"), + (one_per_slot and args.manifest, "--one-per-slot is incompatible with --manifest"), + (one_per_slot and has_emulator, "--one-per-slot is incompatible with --emulator"), + (one_per_slot and has_system, "--one-per-slot is incompatible with --system"), + ] + + +def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + """Validate argument combinations and mutual exclusion rules.""" + _refuse_for_verify_packs(args, parser) + for refused, message in _argument_conflicts(args): + if refused: + parser.error(message) def _write_manifest_if_changed(path: str, manifest: dict) -> None: @@ -3076,16 +3417,21 @@ def _baseline_shortfall(excluded: int, absent: int) -> list[str]: return parts -def _run_verify_packs(args: argparse.Namespace) -> None: - """Verify each pack in the output directory against its platform. +@dataclass(frozen=True) +class _PackCheck: + """What --verify-packs checks every pack against.""" - Delegates to verify_pack_against_platform so the command answers the same - question the pipeline asks: baseline files, core extras and structure. A - second implementation here answered a narrower one and reported OK while - the core extras went unchecked. - """ - verify_db = load_database(args.db) + db: dict + platforms_dir: str + emulators_dir: str + profiles: dict + regions: list[str] | None + data_registry: dict + no_game_data: bool + +def _verify_packs_scope(args: argparse.Namespace) -> tuple[list[str], dict[str, set[str] | None]]: + """The platforms --verify-packs checks, and the cores of the target.""" if args.platform: platforms = [args.platform] elif args.all: @@ -3107,20 +3453,35 @@ def _run_verify_packs(args: argparse.Namespace) -> None: except (FileNotFoundError, ValueError) as e: print(f"ERROR: {e}", file=sys.stderr) sys.exit(1) + return platforms, target_cores_cache + + +def _run_verify_packs(args: argparse.Namespace) -> None: + """Verify each pack in the output directory against its platform. + + Delegates to verify_pack_against_platform so the command answers the same + question the pipeline asks: baseline files, core extras and structure. A + second implementation here answered a narrower one and reported OK while + the core extras went unchecked. + """ + verify_db = load_database(args.db) + platforms, target_cores_cache = _verify_packs_scope(args) all_ok = True - verify_regions = getattr(args, "regions", None) - verify_profiles = load_emulator_profiles(args.emulators_dir) - verify_data_registry = load_data_dir_registry(args.platforms_dir) + check = _PackCheck( + verify_db, args.platforms_dir, args.emulators_dir, + load_emulator_profiles(args.emulators_dir), getattr(args, "regions", None), + load_data_dir_registry(args.platforms_dir), getattr(args, "no_game_data", False), + ) # After an --all-variants build every variant is named, so none of the # six packs the run wrote passes unmentioned. expected = _expected_pack_names( platforms, args.platforms_dir, - verify_regions, + check.regions, args.target, ALL_VARIANTS if args.all_variants else (("full", False),), - no_game_data=getattr(args, "no_game_data", False), + no_game_data=check.no_game_data, ) on_disk = ( set(os.listdir(args.output_dir)) if os.path.isdir(args.output_dir) else set() @@ -3163,16 +3524,16 @@ def _run_verify_packs(args: argparse.Namespace) -> None: result = verify_pack_against_platform( zip_path, platform_name, - args.platforms_dir, - db=verify_db, - emulators_dir=args.emulators_dir, - emu_profiles=verify_profiles, - regions=verify_regions, - data_registry=verify_data_registry, + check.platforms_dir, + db=check.db, + emulators_dir=check.emulators_dir, + emu_profiles=check.profiles, + regions=check.regions, + data_registry=check.data_registry, target_cores=tc, source=source, required_only=required_only, - no_game_data=getattr(args, "no_game_data", False), + no_game_data=check.no_game_data, ) (ok, _checked, _present, errors, bl_checked, bl_present, core_checked, core_present, bl_excluded, bl_absent) = result @@ -3194,6 +3555,12 @@ def _run_verify_packs(args: argparse.Namespace) -> None: all_ok = False failing.append(f"{platform_name} ({pack_name})") + if not _verification_summary(failing, verified, args.output_dir) or not all_ok: + sys.exit(1) + + +def _verification_summary(failing: list[str], verified: int, output_dir: str) -> bool: + """Print how --verify-packs ended. False when nothing was verified.""" if failing: # Named at the end, where the log is read, and on stderr, as the # build path does: a failing pack sat among its own error lines. @@ -3206,10 +3573,9 @@ def _run_verify_packs(args: argparse.Namespace) -> None: if not verified: # Every platform skipped is no check at all: a mistyped or purged # output directory read as a passed integrity check. - print(f"ERROR: no pack to verify in {args.output_dir}", file=sys.stderr) - all_ok = False - if not all_ok: - sys.exit(1) + print(f"ERROR: no pack to verify in {output_dir}", file=sys.stderr) + return False + return True # The source x required combinations --all-variants builds, in build order. @@ -3335,26 +3701,13 @@ def _run_platform_packs( # renamed, it overwrote and carried away a # `--platform retroarch` pack already in the directory, # and os.rename refused an existing target on Windows. - group_name = None - if aliases: - narrow_tags = "".join( - tag - for tag, _label in _narrowings( - source, - getattr(args, "regions", None), - named_target, - args.one_per_slot, - required_only, - no_game_data=getattr(args, "no_game_data", False), - ) - ) - stem = _platform_pack_stem( - group_platforms, representative, args.platforms_dir - ) - group_name = ( - f"{stem}{narrow_tags}_BIOS_Pack" - f"{_system_tag(system_filter)}.zip" + group_name = ( + _group_pack_name( + args, group_platforms, representative, (source, required_only), + named_target, system_filter, ) + if aliases else None + ) zip_path = generate_pack( representative, args.platforms_dir, @@ -3406,6 +3759,55 @@ def _run_platform_packs( no_game_data=getattr(args, "no_game_data", False), ), target_list(board_list) if board_list.is_file() else None) + all_ok = _finalize_platform_packs(args, db, data_registry, built, systems_for, system_filter) + if failed: + # Verification only sees the ZIPs that exist, so a pack that was never + # written does not fail it. + print(f"ERROR: no pack for {', '.join(sorted(set(failed)))}", file=sys.stderr) + sys.exit(1) + if not all_ok: + sys.exit(1) + + +def _group_pack_name( + args: argparse.Namespace, + group_platforms: list[str], + representative: str, + variant: tuple[str, bool], + named_target: str | None, + system_filter: list[str] | None, +) -> str: + """The file name of a pack shared by a group of identical platforms.""" + source, required_only = variant + narrow_tags = "".join( + tag + for tag, _label in _narrowings( + source, + getattr(args, "regions", None), + named_target, + args.one_per_slot, + required_only, + no_game_data=getattr(args, "no_game_data", False), + ) + ) + stem = _platform_pack_stem( + group_platforms, representative, args.platforms_dir + ) + return ( + f"{stem}{narrow_tags}_BIOS_Pack" + f"{_system_tag(system_filter)}.zip" + ) + + +def _finalize_platform_packs( + args: argparse.Namespace, + db: dict, + data_registry: dict | None, + built: set[str], + systems_for: dict[str, dict], + system_filter: list[str] | None, +) -> bool: + """Verify the packs this run wrote and write their manifests.""" print("\nVerifying packs and generating manifests...") skip_conf = bool(system_filter or args.split) all_ok = verify_and_finalize_packs( @@ -3439,13 +3841,7 @@ def _run_platform_packs( regions=getattr(args, "regions", None), ) all_ok = all_ok and ok - if failed: - # Verification only sees the ZIPs that exist, so a pack that was never - # written does not fail it. - print(f"ERROR: no pack for {', '.join(sorted(set(failed)))}", file=sys.stderr) - sys.exit(1) - if not all_ok: - sys.exit(1) + return all_ok def _refuse_for_all_variants(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: @@ -3608,7 +4004,8 @@ def main() -> None: sys.exit(1) -def _main(held: contextlib.ExitStack) -> None: +def _build_parser() -> argparse.ArgumentParser: + """The command line of generate_pack.py.""" parser = argparse.ArgumentParser(allow_abbrev=False, description="Generate platform BIOS ZIP packs") parser.add_argument( "--platform", "-p", type=platform_arg, @@ -3739,20 +4136,14 @@ def _main(held: contextlib.ExitStack) -> None: action="store_true", help="Extract and verify pack integrity (path + hash)", ) - args = parser.parse_args() - from verify import work_from_repo_root + return parser - work_from_repo_root( - args, parser, - ["db", "platforms_dir", "bios_dir", "output_dir", "emulators_dir", "from_md5_file"], - ) - packresolve.set_offline(bool(args.offline)) - if args.platform: - require_platform(args.platform, args.platforms_dir) - require_directory(args.bios_dir) - _refuse_unapplied_flags(args, parser) - _refuse_for_verify_packs(args, parser) +def _run_quick_mode( + args: argparse.Namespace, parser: argparse.ArgumentParser, held: contextlib.ExitStack, +) -> bool: + """Run a mode that builds nothing (a check of existing packs, the target + lists, a listing). True when one ran.""" # Quick-exit modes: --verify-packs alone = verify existing packs only # Combined with --all-variants, generation runs first then verify if args.verify_packs and not args.all_variants: @@ -3761,26 +4152,26 @@ def _main(held: contextlib.ExitStack) -> None: hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) with _pack_output_lock(args.output_dir, exclusive=False): _run_verify_packs(args) - return + return True if args.manifest_targets: _refuse_mixed_output(args.output_dir, "targets") with _pack_output_lock(args.output_dir): generate_target_manifests( os.path.join(args.platforms_dir, "targets"), args.output_dir ) - return + return True if args.list: print_platform_listing(args.platforms_dir) - return + return True if args.list_emulators: list_emulator_profiles(args.emulators_dir) - return + return True if args.list_systems: if args.platform: list_platform_system_ids(args.platform, args.platforms_dir) else: list_system_ids(args.emulators_dir) - return + return True if args.list_targets: if not args.platform: parser.error("--list-targets requires --platform") @@ -3789,71 +4180,61 @@ def _main(held: contextlib.ExitStack) -> None: targets = list_available_targets(args.platform, args.platforms_dir) if not targets: print(f"No targets configured for platform '{args.platform}'") - return + return True for t in targets: print(target_listing_line(t)) - return + return True + return False - _validate_args(args, parser) - _resolve_systems(args, parser) - # Unset until every refusal has run, so a typed default value is seen. - args.source = args.source or "full" - args.group_by = args.group_by or "system" - - # Hash lookup / pack mode - # A platform run may refresh the trees below, under the exclusive lock: - # it takes the shared ones after that. Every other mode reads them now. - if not (args.platform or args.all) or args.offline or args.no_refresh_data: - hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) - has_from_md5 = bool(args.from_md5 or getattr(args, "from_md5_file", None)) - if has_from_md5: - try: - hashes = ( - parse_hash_input(args.from_md5) - if args.from_md5 - else parse_hash_file(args.from_md5_file) - ) - except ValueError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) - except OSError as exc: - print(f"ERROR: --from-md5-file {args.from_md5_file}: {exc.strerror}", file=sys.stderr) - sys.exit(1) - if not hashes: - print( - f"ERROR: no hash in the input. Accepted: {ACCEPTED_HASHES}", - file=sys.stderr, - ) - sys.exit(1) - db = load_database(args.db) - if not args.platform and not args.emulator: - # A lookup that found nothing is an answer a script must see. - if lookup_hashes( - hashes, db, args.bios_dir, args.emulators_dir, args.platforms_dir - ): - sys.exit(1) - return - zip_contents = build_zip_contents_index(db) - with _pack_output_lock(args.output_dir): - result = generate_md5_pack( - hashes=hashes, - db=db, - bios_dir=args.bios_dir, - output_dir=args.output_dir, - zip_contents=zip_contents, - platform_name=args.platform, - platforms_dir=args.platforms_dir, - emulator_name=args.emulator, - emulators_dir=args.emulators_dir, - standalone=getattr(args, "standalone", False), - ) - if not result: - sys.exit(1) - return +def _run_hash_mode(args: argparse.Namespace) -> None: + """--from-md5 and --from-md5-file: look the hashes up, or pack them.""" + try: + hashes = ( + parse_hash_input(args.from_md5) + if args.from_md5 + else parse_hash_file(args.from_md5_file) + ) + except ValueError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + except OSError as exc: + print(f"ERROR: --from-md5-file {args.from_md5_file}: {exc.strerror}", file=sys.stderr) + sys.exit(1) + if not hashes: + print( + f"ERROR: no hash in the input. Accepted: {ACCEPTED_HASHES}", + file=sys.stderr, + ) + sys.exit(1) db = load_database(args.db) + if not args.platform and not args.emulator: + # A lookup that found nothing is an answer a script must see. + if lookup_hashes( + hashes, db, args.bios_dir, args.emulators_dir, args.platforms_dir + ): + sys.exit(1) + return zip_contents = build_zip_contents_index(db) + with _pack_output_lock(args.output_dir): + result = generate_md5_pack( + hashes=hashes, + db=db, + bios_dir=args.bios_dir, + output_dir=args.output_dir, + zip_contents=zip_contents, + platform_name=args.platform, + platforms_dir=args.platforms_dir, + emulator_name=args.emulator, + emulators_dir=args.emulators_dir, + standalone=getattr(args, "standalone", False), + ) + if not result: + sys.exit(1) + +def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> None: + """--emulator, or --system without a platform: the emulators' own layout.""" # Emulator mode if args.emulator: names = [n.strip() for n in args.emulator.split(",") if n.strip()] @@ -3865,7 +4246,7 @@ def _main(held: contextlib.ExitStack) -> None: args.bios_dir, args.output_dir, args.standalone, - zip_contents, + zip_contents=zip_contents, required_only=args.required_only, regions=getattr(args, "regions", None), offline=args.offline, @@ -3876,44 +4257,69 @@ def _main(held: contextlib.ExitStack) -> None: return # System mode (standalone, without platform context) - if args.system and not args.platform and not args.all: - system_ids = [s.strip() for s in args.system.split(",") if s.strip()] - with _pack_output_lock(args.output_dir): - built = generate_system_pack( - system_ids, - args.emulators_dir, - db, - args.bios_dir, - args.output_dir, - args.standalone, - zip_contents, - required_only=args.required_only, - regions=getattr(args, "regions", None), - offline=args.offline, - platforms_dir=args.platforms_dir, - ) - if built is None: - sys.exit(1) - return + system_ids = [s.strip() for s in args.system.split(",") if s.strip()] + with _pack_output_lock(args.output_dir): + built = generate_system_pack( + system_ids, + args.emulators_dir, + db, + args.bios_dir, + args.output_dir, + args.standalone, + zip_contents=zip_contents, + required_only=args.required_only, + regions=getattr(args, "regions", None), + offline=args.offline, + platforms_dir=args.platforms_dir, + ) + if built is None: + sys.exit(1) - system_filter = getattr(args, "system_ids", None) - # Platform mode +def _requested_platforms(args: argparse.Namespace, parser: argparse.ArgumentParser) -> list[str]: + """The platforms a platform run builds for.""" if args.all and args.manifest: # Install manifests cover every registered platform: the installer # serves each one, with or without a release pack. - platforms = list_registered_platforms(args.platforms_dir) - elif args.all: + return list_registered_platforms(args.platforms_dir) + if args.all: # A release publishes the packs the registry marks release_pack and # nothing else: a pack built for another platform is one nobody uploads. platforms = list_release_pack_platforms(args.platforms_dir) if not platforms: parser.error("no registered platform has release_pack: true") - elif args.platform: - platforms = [args.platform] - else: + return platforms + if not args.platform: parser.error("Specify --platform or --all") - return + return [args.platform] + + +def _refresh_data_directories(args: argparse.Namespace, data_registry: dict) -> None: + """Bring the data directory caches up to date before a build reads them.""" + from refresh_data_dirs import load_registry, refresh_all + + registry = load_registry(os.path.join(args.platforms_dir, "_data_dirs.yml")) + results = refresh_all(registry, force=args.refresh_data) + updated = sum(1 for v in results.values() if v) + if updated: + print(f"Refreshed {updated} data director{'ies' if updated > 1 else 'y'}") + failed = sorted(k for k, v in results.items() if v is None) + if failed: + print(f"WARNING: data directory refresh failed: {', '.join(failed)}") + + +def _run_platform_mode( + args: argparse.Namespace, + parser: argparse.ArgumentParser, + held: contextlib.ExitStack, + db: dict, + zip_contents: dict, +) -> None: + """--platform or --all: packs or manifests in each platform's layout.""" + system_filter = getattr(args, "system_ids", None) + + # Platform mode + platforms = _requested_platforms(args, parser) # A mistyped target is refused before the output lock and the data # directory refresh: checked after them, `--target swich` waited on a @@ -3957,16 +4363,7 @@ def _main(held: contextlib.ExitStack) -> None: # during a pipeline sat silent for hours instead of being refused. with _pack_output_lock(args.output_dir): if data_registry and not args.offline and not args.no_refresh_data: - from refresh_data_dirs import load_registry, refresh_all - - registry = load_registry(os.path.join(args.platforms_dir, "_data_dirs.yml")) - results = refresh_all(registry, force=args.refresh_data) - updated = sum(1 for v in results.values() if v) - if updated: - print(f"Refreshed {updated} data director{'ies' if updated > 1 else 'y'}") - failed = sorted(k for k, v in results.items() if v is None) - if failed: - print(f"WARNING: data directory refresh failed: {', '.join(failed)}") + _refresh_data_directories(args, data_registry) if data_registry: hold_data_dirs(held, data_registry) @@ -3995,6 +4392,48 @@ def _main(held: contextlib.ExitStack) -> None: _run_verify_packs(args) +def _main(held: contextlib.ExitStack) -> None: + parser = _build_parser() + args = parser.parse_args() + from verify import work_from_repo_root + + work_from_repo_root( + args, parser, + ["db", "platforms_dir", "bios_dir", "output_dir", "emulators_dir", "from_md5_file"], + ) + packresolve.set_offline(bool(args.offline)) + if args.platform: + require_platform(args.platform, args.platforms_dir) + require_directory(args.bios_dir) + + _refuse_unapplied_flags(args, parser) + _refuse_for_verify_packs(args, parser) + if _run_quick_mode(args, parser, held): + return + + _validate_args(args, parser) + _resolve_systems(args, parser) + # Unset until every refusal has run, so a typed default value is seen. + args.source = args.source or "full" + args.group_by = args.group_by or "system" + + # Hash lookup / pack mode + # A platform run may refresh the trees below, under the exclusive lock: + # it takes the shared ones after that. Every other mode reads them now. + if not (args.platform or args.all) or args.offline or args.no_refresh_data: + hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) + if args.from_md5 or getattr(args, "from_md5_file", None): + _run_hash_mode(args) + return + + db = load_database(args.db) + zip_contents = build_zip_contents_index(db) + if args.emulator or (args.system and not args.platform and not args.all): + _run_profile_mode(args, db, zip_contents) + return + _run_platform_mode(args, parser, held, db, zip_contents) + + # Manifest generation (JSON inventory for install.py) @functools.cache @@ -4129,6 +4568,35 @@ def _one_content(held: list[str], entries: dict[str, dict], emulator: str) -> li return [min(own or held, key=lambda dest: (dest.count("/"), len(dest), dest))] +def _profile_roots(profile: dict) -> dict[str, str]: + """The data_root of each system the profile names a findable place for.""" + return { + _DATA_ROOT_SYSTEMS[key]: target + for key, value in (profile.get("data_root") or {}).items() + if key in _DATA_ROOT_SYSTEMS and isinstance(value, dict) + and (target := _data_root_target(_DATA_ROOT_SYSTEMS[key], value.get("path", ""))) + } + + +def _copy_source( + entry: dict, + by_tail: dict[str, list[str]], + entries: dict[str, dict] | None, + profile_name: str, +) -> str | None: + """The manifest dest a profile entry's standalone copy is taken from.""" + standalone = entry.get("standalone_path") + if (not standalone or standalone.endswith("/") or entry.get("mode") == "libretro" + or entry.get("type") == "directory" or entry.get("found_by") == "content"): + return None + held = by_tail.get(entry.get("path") or entry["name"], []) + if len(held) > 1 and entries is not None: + held = _one_content(held, entries, profile_name) + if len(held) != 1: + return None + return held[0] + + def _profile_copies( profiles: dict[str, dict], dests: list[str], declared: list[dict], entries: dict[str, dict] | None = None, @@ -4172,26 +4640,14 @@ def _profile_copies( copies: list[dict] = [] for profile_name in sorted(profiles): profile = profiles[profile_name] - roots = { - _DATA_ROOT_SYSTEMS[key]: target - for key, value in (profile.get("data_root") or {}).items() - if key in _DATA_ROOT_SYSTEMS and isinstance(value, dict) - and (target := _data_root_target(_DATA_ROOT_SYSTEMS[key], value.get("path", ""))) - } + roots = _profile_roots(profile) if not roots: continue for entry in profile.get("files", []): - standalone = entry.get("standalone_path") - if (not standalone or standalone.endswith("/") or entry.get("mode") == "libretro" - or entry.get("type") == "directory" or entry.get("found_by") == "content"): + source = _copy_source(entry, by_tail, entries, profile_name) + if source is None: continue - held = by_tail.get(entry.get("path") or entry["name"], []) - if len(held) > 1 and entries is not None: - held = _one_content(held, entries, profile_name) - if len(held) != 1: - continue - source = held[0] - where = PurePosixPath(standalone) + where = PurePosixPath(entry["standalone_path"]) placed: dict[str, list[str]] = {} for system, root in roots.items(): sep = "\\" if system == "windows" else "/" @@ -4296,7 +4752,7 @@ def _manifest_entry( "cores": cores, **selection_fields, } - if is_release_asset: + if local_path and is_release_asset: entry["storage"] = "release" entry["release_asset"] = _release_asset_name(local_path, repo_root) # The installer writes what it downloads with the umask's mode, but a program @@ -4323,20 +4779,27 @@ def _is_program(path: str) -> bool: return any(head.startswith(magic) for magic in _PROGRAM_MAGIC) +@dataclass(frozen=True) +class _ClaimContext: + """How a manifest resolves and judges the copy a core claim names.""" + + db: dict + bios_dir: str + zip_contents: dict | None + offline: bool | None + required_only: bool + validation_index: dict | None + owners: dict | None + repo_root: str + data_registry: dict | None = None + + def _attach_claims( entry: dict, claims: list[dict], - db: dict, - bios_dir: str, - zip_contents: dict | None, - offline: bool | None, - required_only: bool, - validation_index: dict | None, - owners: dict | None, + ctx: _ClaimContext, dest: str, manifest_dest: str, - repo_root: str, - data_registry: dict | None = None, ) -> None: """Every other core that reads this destination, in the order the builder meets them: a pack built without the earlier cores, or without the @@ -4355,35 +4818,26 @@ def _attach_claims( if not claim_emu or claim_emu in claimed: continue claimed.add(claim_emu) - if required_only and claim.get("required") is False: + if ctx.required_only and claim.get("required") is False: continue claim_path, claim_status = resolve_file( - claim, db, bios_dir, zip_contents, + claim, ctx.db, ctx.bios_dir, ctx.zip_contents, dest_hint=claim.get("destination", ""), - data_dir_registry=data_registry, offline=offline, + data_dir_registry=ctx.data_registry, offline=ctx.offline, ) if claim_status in ("not_found", "external", "user_provided") or not claim_path: # Nothing held for this core: narrowed to it without the cores # served above, the slot is a file left out (installer replays it). - systems = _extra_system_ids(claim) - entry.setdefault("absent_claims", []).append({ - "name": str(claim.get("name") or ""), - "system": systems[0] if systems else "", - "required": bool(claim.get("required", True)), - "reason": ( - claim_status - if claim_status in ("not_found", "external", "user_provided") - else "not_found" - ), - "cores": [claim_emu], - }) + entry.setdefault("absent_claims", []).append( + _absent_claim(claim, claim_emu, claim_status) + ) continue claim_path, _ = validated_choice( - claim, claim_path, db, validation_index or {}, bios_dir, None, - claim.get("layout_path") or dest, owners, + claim, claim_path, ctx.db, ctx.validation_index or {}, ctx.bios_dir, None, + claim.get("layout_path") or dest, ctx.owners, ) copy, _size = _manifest_entry( - claim_path, manifest_dest, [claim_emu], db, repo_root, {} + claim_path, manifest_dest, [claim_emu], ctx.db, ctx.repo_root, {} ) if copy is None: continue @@ -4399,6 +4853,22 @@ def _attach_claims( entry.pop("alternatives", None) +def _absent_claim(claim: dict, claim_emu: str, claim_status: str) -> dict: + """The omission a claim with nothing held stands for.""" + systems = _extra_system_ids(claim) + return { + "name": str(claim.get("name") or ""), + "system": systems[0] if systems else "", + "required": bool(claim.get("required", True)), + "reason": ( + claim_status + if claim_status in ("not_found", "external", "user_provided") + else "not_found" + ), + "cores": [claim_emu], + } + + def _record_slot_choices( entry: dict, choices: list[tuple[str, str | None]], @@ -4459,114 +4929,125 @@ def _record_slot_choices( entry["declared_choices"] = declared -def _manifest_core_entries( - core_files: list, - config: dict, - db: dict, - bios_dir: str, - base_dest: str, - repo_root: str, - zip_contents: dict | None, - offline: bool | None, - region_drops: set, - case_insensitive: bool, - seen_destinations: set, - seen_lower: set, - seen_parents: set, - manifest_files: list, - omitted_by_destination: dict, - record_omission: Callable[..., None], - pack_only_sizes: list[int], - selection: SelectionIndex, - required_only: bool = False, - validation_index: dict | None = None, - owners: dict | None = None, - data_registry: dict | None = None, - profiles: dict | None = None, -) -> int: - """Add the files a platform's cores need but its list does not name. +class _CoreEntryState(TypedDict): + """What _manifest_core_entries reads and fills of the manifest being listed.""" - The installer fetches by hash, so an entry records the copy this - repository holds rather than the value the profile declares: an - upstream hash carried by no local file leaves the entry with no URL. - Returns the bytes added. - """ - total_size = 0 - extras_pfx = _detect_extras_prefix(config, base_dest) - resolver = ExtraResolver( - db, bios_dir, zip_contents, data_registry, validation_index or {}, - owners, offline, profiles=profiles, - ) - spares = core_file_spares( - core_files, - lambda fe: bool(region_drops) - and extra_region_key(fe, declared_root(config)) in region_drops, - ) if required_only else set() - for fe in core_files: - if required_only and (fe.get("required") is False or id(fe) in spares): - continue + region_drops: set + case_insensitive: bool + seen_destinations: set + seen_lower: set + seen_parents: set + manifest_files: list + omitted_by_destination: dict + record_omission: Callable[..., None] + pack_only_sizes: list[int] + selection: SelectionIndex + + +class _CoreEntryParts(_CoreEntryState, total=False): + """_CoreEntryState and the optional keywords of _manifest_core_entries.""" + + required_only: bool + validation_index: dict | None + owners: dict | None + data_registry: dict | None + profiles: dict | None + + +@dataclass +class _CoreEntryLister: + """Lists a platform's core extras into the manifest, one at a time.""" + + config: dict + base_dest: str + ctx: _ClaimContext + state: _CoreEntryParts + resolver: ExtraResolver + total_size: int = 0 + extras_pfx: str = field(init=False) + + def __post_init__(self) -> None: + self.extras_pfx = _detect_extras_prefix(self.config, self.base_dest) + + def region_key(self, fe: dict) -> str: + return extra_region_key(fe, declared_root(self.config)) + + def region_dropped(self, fe: dict) -> bool: + drops = self.state["region_drops"] + return bool(drops) and self.region_key(fe) in drops + + def list_extra(self, fe: dict) -> None: + state = self.state dest = sanitize_pack_path(fe.get("destination", fe["name"])) if not dest: - continue - region_key = extra_region_key(fe, declared_root(config)) - if region_drops and region_key in region_drops: - continue - full_dest = extra_full_destination(fe, extras_pfx) + return + region_key = self.region_key(fe) + if state["region_drops"] and region_key in state["region_drops"]: + return + full_dest = extra_full_destination(fe, self.extras_pfx) if not full_dest: - continue - save_root = fe.get("root") == "save" + return if ( - case_insensitive - and full_dest not in seen_destinations - and full_dest.lower() in seen_lower + state["case_insensitive"] + and full_dest not in state["seen_destinations"] + and full_dest.lower() in state["seen_lower"] ): - # One file under two spellings: BlastEm opens 32X_M_BIOS.bin and - # PicoDrive 32X_M_BIOS.BIN. The second core's claim joins the - # entry kept, or a pack built without the first core loses the - # file the installer would still have to place. Collisions are - # rare, so the entry is looked up only when one happens. - folded = ( - save_manifest_dest(fe) if save_root - else _manifest_dest_of(full_dest, base_dest) - ).lower() - held = next( - (e for e in manifest_files - if e["dest"].lower() == folded - and (e.get("root") == "save") == save_root), - None, - ) - if held is not None and held.get("cores") is not None: - _attach_claims( - held, [fe], db, bios_dir, zip_contents, offline, required_only, - validation_index, owners, dest, held["dest"], repo_root, - data_registry, - ) - continue + self._join_spelling(fe, full_dest, dest) + return if placement_block( - full_dest, seen_destinations, seen_lower, seen_parents, - case_insensitive, + full_dest, state["seen_destinations"], state["seen_lower"], state["seen_parents"], + state["case_insensitive"], ): - continue + return # The builder's own lookup (ExtraResolver): the data directories, the # copy the emulator accepts, and the size its code checks. Without # the data directories blueMSX's MSX2P.rom named a different dump # than the one its pack carried. - local_path, status, _disagreement = resolver.resolve(fe, dest) + local_path, status, _disagreement = self.resolver.resolve(fe, dest) if not local_path: - source_emu = fe.get("source_profile") or fe.get("source_emulator", "") - if not _claim_platform_omission( - omitted_by_destination.get(full_dest), source_emu - ): - systems = _extra_system_ids(fe) - record_omission( - full_dest, fe, systems[0] if systems else "", status, _claim_cores(fe), - ) - continue + self._omit(fe, full_dest, status) + return + self._list_held(fe, dest, full_dest, region_key, local_path) + def _join_spelling(self, fe: dict, full_dest: str, dest: str) -> None: + # One file under two spellings: BlastEm opens 32X_M_BIOS.bin and + # PicoDrive 32X_M_BIOS.BIN. The second core's claim joins the + # entry kept, or a pack built without the first core loses the + # file the installer would still have to place. Collisions are + # rare, so the entry is looked up only when one happens. + save_root = fe.get("root") == "save" + folded = ( + save_manifest_dest(fe) if save_root + else _manifest_dest_of(full_dest, self.base_dest) + ).lower() + held = next( + (e for e in self.state["manifest_files"] + if e["dest"].lower() == folded + and (e.get("root") == "save") == save_root), + None, + ) + if held is not None and held.get("cores") is not None: + _attach_claims(held, [fe], self.ctx, dest, held["dest"]) + + def _omit(self, fe: dict, full_dest: str, reason: str) -> None: source_emu = fe.get("source_profile") or fe.get("source_emulator", "") + if not _claim_platform_omission( + self.state["omitted_by_destination"].get(full_dest), source_emu + ): + systems = _extra_system_ids(fe) + self.state["record_omission"]( + full_dest, fe, systems[0] if systems else "", reason, _claim_cores(fe), + ) + + def _list_held( + self, fe: dict, dest: str, full_dest: str, region_key: str, local_path: str, + ) -> None: + state = self.state + source_emu = fe.get("source_profile") or fe.get("source_emulator", "") + save_root = fe.get("root") == "save" # Manifest dests are relative to base_destination. Keep the inferred # extras prefix when it is an internal layout dir (RetroDECK bios/). @@ -4579,42 +5060,31 @@ def _manifest_core_entries( # Relative to the roms or emulators folder the entry names. manifest_dest = dest else: - manifest_dest = _manifest_dest_of(full_dest, base_dest) + manifest_dest = _manifest_dest_of(full_dest, self.base_dest) entry, file_size = _manifest_entry( local_path, manifest_dest, [source_emu] if source_emu else [], - db, repo_root, - selection.fields(region_key, fe.get("name", "")), + self.ctx.db, self.ctx.repo_root, + state["selection"].fields(region_key, fe.get("name", "")), ) if entry is not None and save_root: entry.update(save_entry_fields(fe)) elif entry is not None and outer_root: entry["root"] = outer_root if entry is None: - if not _claim_platform_omission( - omitted_by_destination.get(full_dest), source_emu - ): - systems = _extra_system_ids(fe) - record_omission( - full_dest, fe, systems[0] if systems else "", "not_found", - _claim_cores(fe), - ) + self._omit(fe, full_dest, "not_found") if file_size: - pack_only_sizes.append(file_size) - continue + state["pack_only_sizes"].append(file_size) + return if is_game_data(fe) and all( is_game_data(claim) for claim in fe.get("other_claims", []) ): entry["category"] = GAME_DATA - _attach_claims( - entry, fe.get("other_claims", []), db, bios_dir, zip_contents, - offline, required_only, validation_index, owners, dest, - manifest_dest, repo_root, data_registry, - ) + _attach_claims(entry, fe.get("other_claims", []), self.ctx, dest, manifest_dest) - manifest_files.append(entry) - displaced = omitted_by_destination.pop(full_dest, None) + state["manifest_files"].append(entry) + displaced = state["omitted_by_destination"].pop(full_dest, None) if displaced and displaced.get("cores"): # A core that wants this slot and has nothing held: a pack built # without the cores served here leaves the slot to it, missing, @@ -4622,13 +5092,54 @@ def _manifest_core_entries( entry.setdefault("absent_claims", []).append( {k: v for k, v in displaced.items() if k not in ("dest", "held")} ) - total_size += file_size - seen_destinations.add(full_dest) - _register_path(full_dest, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(full_dest.lower()) + self.total_size += file_size + state["seen_destinations"].add(full_dest) + _register_path(full_dest, state["seen_destinations"], state["seen_parents"]) + if state["case_insensitive"]: + state["seen_lower"].add(full_dest.lower()) - return total_size + +def _manifest_core_entries( + core_files: list, + config: dict, + db: dict, + bios_dir: str, + base_dest: str, + repo_root: str, + zip_contents: dict | None, + offline: bool | None, + **state: Unpack[_CoreEntryParts], +) -> int: + """Add the files a platform's cores need but its list does not name. + + The installer fetches by hash, so an entry records the copy this + repository holds rather than the value the profile declares: an + upstream hash carried by no local file leaves the entry with no URL. + Returns the bytes added. + """ + _reject_unknown( + "_manifest_core_entries", state, + _CoreEntryParts.__required_keys__ | _CoreEntryParts.__optional_keys__, + ) + required_only = state.get("required_only", False) + ctx = _ClaimContext( + db, bios_dir, zip_contents, offline, required_only, + state.get("validation_index"), state.get("owners"), repo_root, + state.get("data_registry"), + ) + lister = _CoreEntryLister( + config, base_dest, ctx, state, + ExtraResolver( + db, bios_dir, zip_contents, ctx.data_registry, ctx.validation_index or {}, + ctx.owners, offline, profiles=state.get("profiles"), + ), + ) + spares = core_file_spares(core_files, lister.region_dropped) if required_only else set() + for fe in core_files: + if required_only and (fe.get("required") is False or id(fe) in spares): + continue + lister.list_extra(fe) + return lister.total_size def _manifest_dest_of(full_dest: str, base_dest: str) -> str: @@ -4655,6 +5166,18 @@ def _claim_platform_omission(held: dict | None, emulator: str) -> bool: return True +class _SelectionOptions(TypedDict, total=False): + """The keyword options of _manifest_selection.""" + + required_only: bool + regions: list[str] | None + undeclared: list[dict] | None + zip_contents: dict | None + data_registry: dict | None + slot_overrides: dict[str, str] | None + one_per_slot: bool + + def _manifest_selection( config: dict, pack_systems: dict, @@ -4664,13 +5187,7 @@ def _manifest_selection( emu_profiles: dict, target_cores: set[str] | None, source: str, - required_only: bool, - regions: list[str] | None, - undeclared: list[dict] | None = None, - zip_contents: dict | None = None, - data_registry: dict | None = None, - slot_overrides: dict[str, str] | None = None, - one_per_slot: bool = False, + **options: Unpack[_SelectionOptions], ) -> tuple[set[str], SelectionIndex, set[str]]: """Destinations a region list and --one-per-slot remove, the groups the installer replays, and the destinations the builder holds. @@ -4679,6 +5196,10 @@ def _manifest_selection( decides on the full manifest withdraws what `--region` and `--one-per-slot` withdraw from the pack. """ + _reject_unknown("_manifest_selection", options, _SelectionOptions.__optional_keys__) + required_only = options.get("required_only", False) + regions = options.get("regions") + one_per_slot = options.get("one_per_slot", False) extras: list[dict] = [] held: set[str] = set() region_groups, _extra_dests = platform_region_groups( @@ -4694,10 +5215,10 @@ def _manifest_selection( required_only=required_only, extras_out=extras, held_out=held, - undeclared=undeclared, - zip_contents=zip_contents, - data_registry=data_registry, - slot_overrides=slot_overrides, + undeclared=options.get("undeclared"), + zip_contents=options.get("zip_contents"), + data_registry=options.get("data_registry"), + slot_overrides=options.get("slot_overrides"), ) region_index = region_mod.platform_region_index( config, emu_profiles, target_cores @@ -4863,27 +5384,623 @@ def system_titles(*entry_lists: Iterable[dict]) -> dict[str, str]: return titles +class InstallListOptions(TypedDict, total=False): + """The keyword options of generate_install_list, which it hands to + generate_manifest.""" + + emulators_dir: str + zip_contents: dict | None + emu_profiles: dict | None + target_cores: set[str] | None + source: str + regions: list[str] | None + target_name: str | None + offline: bool | None + required_only: bool + data_registry: dict | None + fold_case: bool | None + no_game_data: bool + one_per_slot: bool + + +class ManifestOptions(InstallListOptions, total=False): + """The keyword options of generate_manifest.""" + + known_slot_choices: dict | None + build_out: dict | None + + +@dataclass(frozen=True) +class _ManifestSettings: + """ManifestOptions with their defaults.""" + + emulators_dir: str = "emulators" + zip_contents: dict | None = None + emu_profiles: dict | None = None + target_cores: set[str] | None = None + source: str = "full" + regions: list[str] | None = None + target_name: str | None = None + offline: bool | None = None + required_only: bool = False + data_registry: dict | None = None + fold_case: bool | None = None + no_game_data: bool = False + one_per_slot: bool = False + known_slot_choices: dict | None = None + build_out: dict | None = None + + +@dataclass +class _ManifestBuild: + """One install manifest being listed: its files, omissions and the slots + they take, settled by the rules the pack builder follows.""" + + platform_name: str + platforms_dir: str + db: dict + bios_dir: str + opts: _ManifestSettings + config: dict + emu_profiles: dict + zip_contents: dict + data_registry: dict + game_entries: set[int] + install_section: dict + repo_root: str + pack_systems: dict + manifest_profiles: dict = field(default_factory=dict) + manifest_validation: dict = field(default_factory=dict) + manifest_owners: dict = field(default_factory=dict) + game_destinations: set[str] = field(default_factory=set) + placed: _Placed = field(init=False) + # Destination -> (entry, full destination, manifest destination) of each + # platform file, for the core claims a target build would fall back on. + platform_entries: dict[str, tuple[dict, str, str]] = field(default_factory=dict) + # Full destination -> the platform systems declaring it. A file's + # `systems` also names the systems whose cores read it there. A pack built + # for a target keeps the file only while a declaring system stays. + declared_by: dict[str, set[str]] = field(default_factory=dict) + manifest_files: list[dict] = field(default_factory=list) + omitted_by_destination: dict[str, dict] = field(default_factory=dict) + total_size: int = 0 + # Sizes of the files the pack carries and the installer cannot fetch: the + # collection does not index them, a data directory cache answered. + pack_only_sizes: list[int] = field(default_factory=list) + # Platform entries resolved into a data directory cache: destination -> + # (cache file, size). Settled once the trees are walked. + cache_held: dict[str, tuple[str, int]] = field(default_factory=dict) + rename_notes: set[str] = field(default_factory=set) + slot_choices: dict = field(default_factory=dict) + slot_overrides: dict[str, str] = field(default_factory=dict) + undeclared: list[dict] | None = None + region_drops: set[str] = field(default_factory=set) + selection: SelectionIndex | None = None + builder_held: set[str] = field(default_factory=set) + declarations: dict[str, dict[str, list[dict]]] = field(default_factory=dict) + data_members: list[tuple[str, str]] = field(default_factory=list) + data_directories: list[dict] = field(default_factory=list) + + def __post_init__(self) -> None: + self.placed = _Placed(self.case_insensitive) + + @property + def base_dest(self) -> str: + return self.config.get("base_destination", "") + + @property + def case_insensitive(self) -> bool: + return self.config.get("case_insensitive_fs", False) + + @property + def verification_mode(self) -> str: + return self.config.get("verification_mode", "existence") + + @property + def fields(self) -> SelectionIndex: + assert self.selection is not None + return self.selection + + def manifest_destination(self, full_destination: str) -> str: + return _manifest_dest_of(full_destination, self.base_dest) + + def record_omission( + self, + full_destination: str, + file_entry: dict, + system_id: str, + reason: str, + cores: list[str] | None, + ) -> None: + # A core extra (cores given) is keyed as the region pass keys it. + bare = ( + sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) + if cores is None else extra_region_key(file_entry, declared_root(self.config)) + ) + self.omitted_by_destination[full_destination] = { + **self._omission_dest(full_destination, file_entry), + "name": str(file_entry.get("name") or ""), + "system": system_id, + "required": bool(file_entry.get("required", True)), + "reason": reason, + "cores": cores, + # An omission keeps its region groups, as the builder groups it: + # a requested file the collection lacks answers the request + # without displacing a held fallback (resolve_region_drops, + # held). One the builder holds and the installer cannot fetch + # does displace it in the pack, so it says so, and the installer + # drops the same fallback. + **self.fields.fields(bare, str(file_entry.get("name") or "")), + **({"held": True} if bare in self.builder_held else {}), + **( + {"category": GAME_DATA} + if (bare in self.game_destinations if cores is None else is_game_data(file_entry)) + else {} + ), + } + + def _omission_dest(self, full_destination: str, file_entry: dict) -> dict: + # Read in the emulator's own folder, outside the BIOS tree: dest is + # the path the emulator reads, relative to that folder. + if file_entry.get("unplaced"): + return {"dest": sanitize_pack_path(file_entry.get("path") or ""), + "root": "emulator"} + if file_entry.get("root") in OUTER_ROOTS: + return {"dest": sanitize_pack_path( + file_entry.get("destination") or file_entry.get("path") or "" + ), "root": file_entry["root"]} + if file_entry.get("root") == "save": + return {"dest": save_manifest_dest(file_entry), **save_entry_fields(file_entry)} + return {"dest": self.manifest_destination(full_destination)} + + def kept_declarations(self) -> Iterator[tuple[str, dict, str, str]]: + """(system, entry, destination, full destination) of each platform + declaration this manifest keeps, in the builder's order.""" + opts = self.opts + for sys_id, system in sorted(self.pack_systems.items()): + for file_entry in system.get("files", []): + if opts.required_only and file_entry.get("required") is False: + continue + dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) + if not dest: + continue + if self.region_drops and dest in self.region_drops: + continue + full_dest = f"{self.base_dest}/{dest}" if self.base_dest else dest + yield sys_id, file_entry, dest, full_dest + + def declaration_order(self, full_dest: str) -> list[tuple[list[str], dict, str]]: + """The declarations answering a destination as its systems drop. + + A pack built for a target loses the systems no available core + reads, and the next declaration takes the destination by the + same rule: RetroArch's bare nintendo-ds dsi_bios9.bin once the + pinned nintendo-dsi one is gone. + """ + remaining = dict(self.declarations.get(full_dest, {})) + order: list[tuple[list[str], dict, str]] = [] + while remaining: + winner = _preferred_entries( + {sid: {"files": fes} for sid, fes in remaining.items()}, + self.db, self.bios_dir, self.base_dest, self.opts.required_only, + self.zip_contents, self.opts.offline, + ).get(full_dest) + first_sys, first = next( + (sid, fe) for sid, fes in sorted(remaining.items()) for fe in fes + if winner is None or id(fe) == winner + ) + systems = sorted( + sid for sid, fes in remaining.items() + if any(fe is first for fe in fes) + ) + order.append((systems, first, first_sys)) + for sid in systems: + del remaining[sid] + return order + + def list_baseline(self, settle: _Settle) -> None: + """Phase 1: the platform's own files.""" + # The same destination can be declared by more than one system, bare + # in one and hash-constrained in another. The builder lets the + # constrained sibling claim it. Without the same rule here the + # manifest named whatever answered to the name, so the pack and the + # installer disagreed about which file a destination means. + # Decided among the declarations this manifest keeps, as the pack + # does. A manifest carries no data directories. + preferred_entries = _preferred_entries( + self.pack_systems, self.db, self.bios_dir, self.base_dest, + self.opts.required_only, self.zip_contents, self.opts.offline, + ) + for sys_id, file_entry, _dest, full_dest in self.kept_declarations(): + self.declarations.setdefault(full_dest, {}).setdefault(sys_id, []).append( + file_entry + ) + for sys_id, file_entry, dest, full_dest in self.kept_declarations(): + self.declared_by.setdefault(full_dest, set()).add(sys_id) + preferred = preferred_entries.get(full_dest) + if preferred is not None and id(file_entry) != preferred: + continue + if self.placed.holds(full_dest) or self.placed.conflicts(full_dest): + continue + if file_entry.get("storage", "embedded") == "user_provided": + self._list_instructions(file_entry, sys_id, full_dest) + continue + local_path, status = settle( + file_entry, sys_id, dest, self.slot_overrides.get(full_dest) + ) + if local_path is None: + self.record_omission(full_dest, file_entry, sys_id, status, None) + continue + self._list_declared(file_entry, sys_id, dest, full_dest, local_path, settle) + + def _list_instructions(self, file_entry: dict, sys_id: str, full_dest: str) -> None: + self.record_omission( + full_dest, + file_entry, + sys_id, + "user_provided", + None, + ) + # The pack writes the instructions in the slot's place + # and holds it: one more member than the files listed. + instructions = file_entry.get( + "instructions", "Please provide this file manually." + ) + self.pack_only_sizes.append(len( + f"File needed: {file_entry['name']}\n\n{instructions}\n".encode() + )) + self.placed.take(full_dest) + + def _list_declared( + self, + file_entry: dict, + sys_id: str, + dest: str, + full_dest: str, + local_path: str, + settle: _Settle, + ) -> None: + entry, file_size = _manifest_entry( + local_path, dest, None, self.db, self.repo_root, + self.fields.fields(dest, file_entry["name"]), + ) + if entry is not None and dest in self.game_destinations: + entry["category"] = GAME_DATA + if entry is not None and self.opts.target_cores is None: + order = self.declaration_order(full_dest) + if full_dest in self.slot_choices or len(order) > 1: + _record_slot_choices( + entry, self.slot_choices.get(full_dest, []), order, + settle, dest, self.db, self.repo_root, + ) + if entry is None: + self.record_omission(full_dest, file_entry, sys_id, "not_found", None) + if file_size and full_dest not in self.placed.destinations: + if _in_data_cache(local_path, self.data_registry): + self.cache_held[full_dest] = (local_path, file_size) + else: + self.pack_only_sizes.append(file_size) + self.placed.take(full_dest) + return + + self.manifest_files.append(entry) + self.platform_entries[full_dest] = (entry, full_dest, dest) + self.omitted_by_destination.pop(full_dest, None) + self.total_size += file_size + self.placed.take(full_dest) + + def claim_context(self) -> _ClaimContext: + return _ClaimContext( + self.db, self.bios_dir, self.zip_contents, self.opts.offline, + self.opts.required_only, self.manifest_validation, self.manifest_owners, + self.repo_root, self.data_registry, + ) + + def list_core_files(self) -> None: + """Phase 2: core complement (emulator extras).""" + opts = self.opts + unplaceable: list[dict] = [] + baseline_claims: dict[str, dict] = {} + absent: list[dict] = [] + if opts.source != "platform": + core_files = _collect_emulator_extras( + self.config, + opts.emulators_dir, + self.db, + self.placed.destinations, + self.base_dest, + self.emu_profiles, + target_cores=opts.target_cores, + include_all=(opts.source == "truth"), + unplaceable=unplaceable, + baseline_claims=baseline_claims, + absent=absent, + undeclared=self.undeclared, + ) + else: + core_files = [] + _record_unplaceable(unplaceable, self.record_omission, self.config, self.emu_profiles) + _record_absent( + absent, self.config, self.base_dest, self.region_drops, opts.required_only, + self.placed.destinations, self.omitted_by_destination, self.record_omission, + ) + self.total_size += _manifest_core_entries( + core_files, self.config, self.db, self.bios_dir, self.base_dest, self.repo_root, + self.zip_contents, opts.offline, + region_drops=self.region_drops, case_insensitive=self.case_insensitive, + seen_destinations=self.placed.destinations, seen_lower=self.placed.lower, + seen_parents=self.placed.parents, manifest_files=self.manifest_files, + omitted_by_destination=self.omitted_by_destination, + record_omission=self.record_omission, pack_only_sizes=self.pack_only_sizes, + selection=self.fields, required_only=opts.required_only, + validation_index=self.manifest_validation, owners=self.manifest_owners, + data_registry=self.data_registry, profiles=self.emu_profiles, + ) + self._settle_claims(baseline_claims) + + def _settle_claims(self, baseline_claims: dict[str, dict]) -> None: + ctx = self.claim_context() + for key, (entry, full_dest, dest) in self.platform_entries.items(): + declared = self.declared_by.get(full_dest, set()) + if declared and declared != set(entry.get("systems") or []): + entry["declared_in"] = sorted(declared) + claims = baseline_claims.get(key, {}).get("other_claims") + if claims and any(not is_game_data(claim) for claim in claims): + # A core reads this path as firmware: a pack without game data + # still fills it. + entry.pop("category", None) + if claims: + _attach_claims(entry, claims, ctx, dest, dest) + # A platform omission narrows like a platform file: by the systems + # declaring it, which can be fewer than the ones whose cores read it. + for full_dest, omission in self.omitted_by_destination.items(): + declared = self.declared_by.get(full_dest, set()) + if ( + omission.get("cores") is None + and declared + and declared != set(omission.get("systems") or []) + ): + omission["declared_in"] = sorted(declared) + + def list_data_directories(self) -> list[int]: + """Phase 3: data directories, and the sizes the pack alone holds. + + They are not files of the collection: the installer fetches each + from its source archive and keeps the members whose hash the list + below records, the same tree the pack carries. + """ + opts = self.opts + required_only = opts.required_only + data_refs: dict[str, tuple[str, tuple[str, ...], str, bool]] = {} + reclaim = {full: path for full, (path, _size) in self.cache_held.items()} + core_trees = ([] if opts.source == "platform" + else core_data_trees(self.config, self.emu_profiles, self.platform_name, + self.data_registry, opts.target_cores)) + self.data_members = list(_data_directory_members( + self.pack_systems, self.data_registry, self.platform_name, self.base_dest, + self.case_insensitive, self.placed.destinations, self.placed.lower, + self.placed.parents, refs_out=data_refs, required_only=required_only, + core_trees=core_trees, + reclaim=reclaim, + )) + # A platform entry found in a tree the pack carries is that tree's member: + # the installer rebuilds it from the tree's archive. One found in a tree + # the pack does not carry stays omitted, held by the pack alone. + for full_dest, (_path, size) in self.cache_held.items(): + if full_dest in reclaim: + self.pack_only_sizes.append(size) + else: + self.omitted_by_destination.pop(full_dest, None) + self.data_directories = _manifest_data_directories( + self.data_members, data_refs, self.data_registry or {}, self.base_dest, + tree_readers(self.pack_systems, core_trees), self.pack_systems, + ) + return self.pack_only_sizes + [os.path.getsize(src) for src, _dest in self.data_members] + + def result(self, data_sizes: list[int]) -> dict: + opts, config, pack_systems = self.opts, self.config, self.pack_systems + manifest_files, platform_name = self.manifest_files, self.platform_name + omitted = self.omitted_by_destination + # The pack is unzipped into the BIOS folder: an entry the installer puts + # in the roms, emulators or configs folder is in its list, not in the ZIP. + outer = [e for e in manifest_files if e.get("root") in OUTER_ROOTS] + core_names, system_cores = _manifest_core_index( + config, self.emu_profiles, manifest_files, list(omitted.values()) + ) + result: dict = { + "manifest_version": 2, + "source": opts.source, + "regions": list(opts.regions or []), + # A target-filtered manifest is only distinguishable from the full one + # by its filename, so it records the filter the way regions does. + # Absent on an unfiltered manifest rather than empty, to leave the + # twelve default files byte-identical. + **({"target": opts.target_name} if opts.target_name else {}), + # Every game data file below says so: the installer's --no-game-data + # relies on it, and refuses a list that does not record categories. + "categorized": True, + # The entries a slot decides carry `slot`, which --one-per-slot + # reads: without this mark the installer refuses it. + "slot_fields": True, + **({"no_game_data": True} if opts.no_game_data else {}), + "platform": platform_name, + "display_name": config.get("platform", platform_name), + "version": platform_list_version(config, platform_name), + "generated": _build_timestamp(self.db), + "base_destination": self.base_dest, + "detect": self.install_section.get("detect", []), + "standalone_copies": _standalone_copies( + self.install_section.get("standalone_copies", []), self.manifest_profiles, + manifest_files, + ), + "total_files": len(manifest_files), + "total_size": self.total_size, + "pack_files": ( + len(manifest_files) - len(outer) + len(data_sizes) + len(PACK_DOCUMENTS) + + len(self.rename_notes) + + len(pack_markers(platform_name, opts.target_name, self.platforms_dir)) + ), + "pack_size": self.total_size - sum(int(e.get("size") or 0) for e in outer) + + sum(data_sizes), + "total_omitted": len(omitted), + "omitted_files": sorted( + omitted.values(), key=lambda entry: entry["dest"] + ), + "core_names": core_names, + **({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores( + config, self.emu_profiles, core_names, self.platforms_dir, + )) else {}), + **({"offered_boards": offered} if (offered := _offered_boards( + config, self.emu_profiles, core_names, + [*manifest_files, *omitted.values()], + )) else {}), + "system_cores": system_cores, + # The names the platform itself gives its systems (Batocera's psx), + # which --system accepts beside the ids. + "system_names": platform_system_names(config, list(pack_systems)), + "system_titles": system_titles(manifest_files, omitted.values()), + "files": manifest_files, + } + if self.data_directories: + result["data_directories"] = self.data_directories + self._outer_directories(result) + return result + + def _outer_directories(self, result: dict) -> None: + for root in OUTER_ROOTS: + layout = outer_layout(self.config, root) or {} + if layout and any(entry.get("root") == root + for entry in [*self.manifest_files, *result["omitted_files"]]): + # Where the installer finds the folder: relative to the folder + # holding the BIOS folder, which the platform names bios_folder. + result[f"{root}_directory"] = { + key: layout[key] for key in MANIFEST_OUTER_FIELDS if key in layout + } + saved = [entry for entry in self.manifest_files if entry.get("root") == "save"] + if saved: + save = save_layout(self.config) + result["save_directory"] = {"folder": save.folder, "by_core": save.by_core} + if save.by_system: + # The launcher writes the directory at each launch, one folder + # per system: each dest starts with that folder. + result["save_directory"]["by_system"] = True + + +def _start_manifest( + platform_name: str, + platforms_dir: str, + db: dict, + bios_dir: str, + registry_path: str, + opts: _ManifestSettings, +) -> tuple[_ManifestBuild, dict]: + """The manifest's configuration and scope, and the profiles before the + game data cut.""" + config = load_platform_config(platform_name, platforms_dir) + if opts.fold_case is not None: + config = {**config, "case_insensitive_fs": opts.fold_case} + if opts.target_name: + config = {**config, TARGET_KEY: opts.target_name} + zip_contents = {} if opts.zip_contents is None else opts.zip_contents + emu_profiles = opts.emu_profiles + if emu_profiles is None: + emu_profiles = load_emulator_profiles(opts.emulators_dir) + data_registry = opts.data_registry + if data_registry is None: + data_registry = load_data_dir_registry(platforms_dir) + full_profiles = emu_profiles + game_entries: set[int] = set() + if opts.no_game_data: + cut = without_game_data(config, emu_profiles, data_registry, opts.target_cores) + config, emu_profiles = cut.config, cut.profiles + else: + game_entries = platform_game_data(config, emu_profiles, data_registry) + + # Load registry for install metadata + registry: dict = {} + if os.path.exists(registry_path): + with open(registry_path) as f: + registry = yaml_load(f) or {} + plat_registry = registry.get("platforms", {}).get(platform_name, {}) + + plat_cores = _platform_cores(config, emu_profiles) if opts.target_cores else None + pack_systems = filter_systems_by_target( + config.get("systems", {}), + emu_profiles, + opts.target_cores, + platform_cores=plat_cores, + ) + build = _ManifestBuild( + platform_name, platforms_dir, db, bios_dir, opts, config, emu_profiles, + zip_contents, data_registry, game_entries, plat_registry.get("install", {}), + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), pack_systems, + ) + build.manifest_profiles = { + name: emu_profiles[name] + for name in _platform_cores(config, emu_profiles) + } + build.manifest_validation = _build_validation_index(build.manifest_profiles) + build.manifest_owners = destination_owners(build.manifest_profiles) + _settle_manifest_scope(build) + return build, full_profiles + + +def _settle_manifest_scope(build: _ManifestBuild) -> None: + """Game data destinations, slot choices and the region selection.""" + opts, config, emu_profiles = build.opts, build.config, build.emu_profiles + # A destination is game data when every declaration of it is: a firmware + # declaration of the same path keeps it in a pack built without game data. + declared_kinds: dict[str, set[bool]] = {} + for system in build.pack_systems.values(): + for fe in system.get("files", []): + bare = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) + if bare: + declared_kinds.setdefault(bare, set()).add(id(fe) in build.game_entries) + build.game_destinations = {d for d, kinds in declared_kinds.items() if kinds == {True}} + + # The full manifest records every core's answer at a contested slot, so a + # target narrowed from it gets what that target's own pack serves. + whole = opts.target_cores is None and opts.source != "platform" and bool(emu_profiles) + # The truth list read inside this run takes the choices already made. + build.slot_choices = ( + opts.known_slot_choices if opts.known_slot_choices is not None and whole + else slots.slot_choices(config, emu_profiles, build.db, build.zip_contents, + build.data_registry) + if whole else {} + ) + # Derived from the same choices: computed twice, it was 8% of a run. + build.slot_overrides = slots.pack_overrides( + config, emu_profiles, build.db, build.zip_contents, build.data_registry, + target_cores=opts.target_cores, source=opts.source, + choices=build.slot_choices if whole else None, + ) + + # Read by the region grouping and by phase 2 with the same arguments. + build.undeclared = ( + undeclared_report( + config, opts.emulators_dir, build.db, emu_profiles, opts.target_cores, + include_all=(opts.source == "truth"), + ) + if opts.source != "platform" + else None + ) + build.region_drops, build.selection, build.builder_held = _manifest_selection( + config, build.pack_systems, opts.emulators_dir, build.db, build.base_dest, + emu_profiles, opts.target_cores, opts.source, + required_only=opts.required_only, regions=opts.regions, + undeclared=build.undeclared, zip_contents=build.zip_contents, + data_registry=build.data_registry, slot_overrides=build.slot_overrides, + one_per_slot=opts.one_per_slot, + ) + + def generate_manifest( platform_name: str, platforms_dir: str, db: dict, bios_dir: str, registry_path: str, - emulators_dir: str = "emulators", - zip_contents: dict | None = None, - emu_profiles: dict | None = None, - target_cores: set[str] | None = None, - source: str = "full", - regions: list[str] | None = None, - target_name: str | None = None, - offline: bool | None = None, - required_only: bool = False, - data_registry: dict | None = None, - fold_case: bool | None = None, - no_game_data: bool = False, - one_per_slot: bool = False, - known_slot_choices: dict | None = None, - build_out: dict | None = None, + **options: Unpack[ManifestOptions], ) -> dict: """Generate a JSON manifest for a platform (same resolution as generate_pack). @@ -4898,520 +6015,57 @@ def generate_manifest( --standalone read. `build_out` receives the slot choices and the profiles this build read, which that second build takes over. """ - config = load_platform_config(platform_name, platforms_dir) - if fold_case is not None: - config = {**config, "case_insensitive_fs": fold_case} - if target_name: - config = {**config, TARGET_KEY: target_name} - if zip_contents is None: - zip_contents = {} - if emu_profiles is None: - emu_profiles = load_emulator_profiles(emulators_dir) - if data_registry is None: - data_registry = load_data_dir_registry(platforms_dir) - full_profiles = emu_profiles - game_entries: set[int] = set() - if no_game_data: - cut = without_game_data(config, emu_profiles, data_registry, target_cores) - config, emu_profiles = cut.config, cut.profiles - else: - game_entries = platform_game_data(config, emu_profiles, data_registry) - - platform_display = config.get("platform", platform_name) - base_dest = config.get("base_destination", "") - case_insensitive = config.get("case_insensitive_fs", False) - verification_mode = config.get("verification_mode", "existence") - manifest_profiles = { - name: emu_profiles[name] - for name in _platform_cores(config, emu_profiles) - } - manifest_validation = _build_validation_index(manifest_profiles) - manifest_owners = destination_owners(manifest_profiles) - - # Load registry for install metadata - registry: dict = {} - if os.path.exists(registry_path): - with open(registry_path) as f: - registry = yaml_load(f) or {} - plat_registry = registry.get("platforms", {}).get(platform_name, {}) - install_section = plat_registry.get("install", {}) - detect = install_section.get("detect", []) - standalone_copies = install_section.get("standalone_copies", []) - - repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - plat_cores = _platform_cores(config, emu_profiles) if target_cores else None - pack_systems = filter_systems_by_target( - config.get("systems", {}), - emu_profiles, - target_cores, - platform_cores=plat_cores, + _reject_unknown("generate_manifest", options, ManifestOptions.__optional_keys__) + opts = _ManifestSettings(**options) + build, full_profiles = _start_manifest( + platform_name, platforms_dir, db, bios_dir, registry_path, opts ) + config, verification_mode = build.config, build.verification_mode - # A destination is game data when every declaration of it is: a firmware - # declaration of the same path keeps it in a pack built without game data. - declared_kinds: dict[str, set[bool]] = {} - for system in pack_systems.values(): - for fe in system.get("files", []): - bare = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) - if bare: - declared_kinds.setdefault(bare, set()).add(id(fe) in game_entries) - game_destinations = {d for d, kinds in declared_kinds.items() if kinds == {True}} - - seen_destinations: set[str] = set() - # Destination -> (entry, full destination, manifest destination) of each - # platform file, for the core claims a target build would fall back on. - platform_entries: dict[str, tuple[dict, str, str]] = {} - # Full destination -> the platform systems declaring it. A file's - # `systems` also names the systems whose cores read it there. A pack built - # for a target keeps the file only while a declaring system stays. - declared_by: dict[str, set[str]] = {} - seen_lower: set[str] = set() - seen_parents: set[str] = set() - manifest_files: list[dict] = [] - omitted_by_destination: dict[str, dict] = {} - total_size = 0 - # Sizes of the files the pack carries and the installer cannot fetch: the - # collection does not index them, a data directory cache answered. - pack_only_sizes: list[int] = [] - # Platform entries resolved into a data directory cache: destination -> - # (cache file, size). Settled once the trees are walked. - cache_held: dict[str, tuple[str, int]] = {} - rename_notes: set[str] = set() - # The full manifest records every core's answer at a contested slot, so a - # target narrowed from it gets what that target's own pack serves. - whole = target_cores is None and source != "platform" and bool(emu_profiles) - # The truth list read inside this run takes the choices already made. - slot_choices = ( - known_slot_choices if known_slot_choices is not None and whole - else slots.slot_choices(config, emu_profiles, db, zip_contents, data_registry) - if whole else {} - ) - # Derived from the same choices: computed twice, it was 8% of a run. - slot_overrides = slots.pack_overrides( - config, emu_profiles, db, zip_contents, data_registry, - target_cores=target_cores, source=source, - choices=slot_choices if whole else None, - ) - - def manifest_destination(full_destination: str) -> str: - if base_dest and full_destination.startswith(f"{base_dest}/"): - return full_destination[len(base_dest) + 1:] - return full_destination - - def record_omission( - full_destination: str, - file_entry: dict, - system_id: str, - reason: str, - cores: list[str] | None, - ) -> None: - # A core extra (cores given) is keyed as the region pass keys it. - bare = ( - sanitize_pack_path(file_entry.get("destination", file_entry.get("name", ""))) - if cores is None else extra_region_key(file_entry, declared_root(config)) - ) - save_root = file_entry.get("root") == "save" - # Read in the emulator's own folder, outside the BIOS tree: dest is - # the path the emulator reads, relative to that folder. - outside = bool(file_entry.get("unplaced")) - if outside: - dest_fields: dict = {"dest": sanitize_pack_path(file_entry.get("path") or ""), - "root": "emulator"} - elif file_entry.get("root") in OUTER_ROOTS: - dest_fields = {"dest": sanitize_pack_path( - file_entry.get("destination") or file_entry.get("path") or "" - ), "root": file_entry["root"]} - elif save_root: - dest_fields = {"dest": save_manifest_dest(file_entry), **save_entry_fields(file_entry)} - else: - dest_fields = {"dest": manifest_destination(full_destination)} - omitted_by_destination[full_destination] = { - **dest_fields, - "name": str(file_entry.get("name") or ""), - "system": system_id, - "required": bool(file_entry.get("required", True)), - "reason": reason, - "cores": cores, - # An omission keeps its region groups, as the builder groups it: - # a requested file the collection lacks answers the request - # without displacing a held fallback (resolve_region_drops, - # held). One the builder holds and the installer cannot fetch - # does displace it in the pack, so it says so, and the installer - # drops the same fallback. - **selection.fields(bare, str(file_entry.get("name") or "")), - **({"held": True} if bare in builder_held else {}), - **( - {"category": GAME_DATA} - if (bare in game_destinations if cores is None else is_game_data(file_entry)) - else {} - ), - } - - # Read by the region grouping and by phase 2 with the same arguments. - undeclared = ( - undeclared_report( - config, emulators_dir, db, emu_profiles, target_cores, - include_all=(source == "truth"), - ) - if source != "platform" - else None - ) - region_drops, selection, builder_held = _manifest_selection( - config, pack_systems, emulators_dir, db, base_dest, emu_profiles, - target_cores, source, required_only, regions, undeclared=undeclared, - zip_contents=zip_contents, data_registry=data_registry, - slot_overrides=slot_overrides, one_per_slot=one_per_slot, - ) - - # Phase 1: baseline files - if source != "truth": - # The same destination can be declared by more than one system, bare - # in one and hash-constrained in another. The builder lets the - # constrained sibling claim it. Without the same rule here the - # manifest named whatever answered to the name, so the pack and the - # installer disagreed about which file a destination means. - # Decided among the declarations this manifest keeps, as the pack - # does. A manifest carries no data directories. - preferred_entries = _preferred_entries( - pack_systems, db, bios_dir, base_dest, required_only, - zip_contents, offline, - ) - declarations: dict[str, dict[str, list[dict]]] = {} - for sys_id, system in sorted(pack_systems.items()): - for file_entry in system.get("files", []): - if required_only and file_entry.get("required") is False: - continue - dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) - if dest and not (region_drops and dest in region_drops): - full_dest = f"{base_dest}/{dest}" if base_dest else dest - declarations.setdefault(full_dest, {}).setdefault(sys_id, []).append( - file_entry - ) - - def declaration_order(full_dest: str) -> list[tuple[list[str], dict, str]]: - """The declarations answering a destination as its systems drop. - - A pack built for a target loses the systems no available core - reads, and the next declaration takes the destination by the - same rule: RetroArch's bare nintendo-ds dsi_bios9.bin once the - pinned nintendo-dsi one is gone. - """ - remaining = dict(declarations.get(full_dest, {})) - order: list[tuple[list[str], dict, str]] = [] - while remaining: - winner = _preferred_entries( - {sid: {"files": fes} for sid, fes in remaining.items()}, - db, bios_dir, base_dest, required_only, zip_contents, offline, - ).get(full_dest) - first_sys, first = next( - (sid, fe) for sid, fes in sorted(remaining.items()) for fe in fes - if winner is None or id(fe) == winner - ) - systems = sorted( - sid for sid, fes in remaining.items() - if any(fe is first for fe in fes) - ) - order.append((systems, first, first_sys)) - for sid in systems: - del remaining[sid] - return order - - def settle( - file_entry: dict, sys_id: str, dest: str, override: str | None - ) -> tuple[str | None, str]: - """The file served once the slot is settled, or None and why not.""" - local_path, status = resolve_declaration( - file_entry, - db, - bios_dir, - zip_contents, - data_registry, - override, - offline=offline, - ) - if status == "not_found" and not reads_file_contents(verification_mode): - found = agnostic_substitute(file_entry, sys_id, db, manifest_profiles) - if found: - local_path, status = found[0], "agnostic_fallback" - if os.path.basename(local_path) != file_entry.get("name", ""): - # The pack explains the rename in a note of its own. - rename_notes.add(file_entry.get("name", "")) - # The builder's verdict: a hash platform omits what its frontend - # would reject, a zipped_file archive included when the member is - # missing whatever the outer resolution said. An existence - # platform never reads the bytes. - status, refusal = baseline_verdict( - file_entry, local_path, status, verification_mode, - config.get("hash_rule", ""), - ) - if refusal or status in ("not_found", "external"): - return None, "hash_mismatch" if refusal else status - # The variant the pack ships when an emulator rejects the - # resolved file: the installer must place the same bytes. - local_path, _disagreement = validated_choice( - file_entry, local_path, db, manifest_validation, bios_dir, - digest_algorithm(verification_mode), dest, manifest_owners, - ) - return local_path, status - - for sys_id, system in sorted(pack_systems.items()): - for file_entry in system.get("files", []): - if required_only and file_entry.get("required") is False: - continue - dest = sanitize_pack_path(file_entry.get("destination", file_entry["name"])) - if not dest: - continue - if region_drops and dest in region_drops: - continue - full_dest = f"{base_dest}/{dest}" if base_dest else dest - declared_by.setdefault(full_dest, set()).add(sys_id) - - preferred = preferred_entries.get(full_dest) - if preferred is not None and id(file_entry) != preferred: - continue - - dedup_key = full_dest - if dedup_key in seen_destinations: - continue - if case_insensitive and dedup_key.lower() in seen_lower: - continue - if _has_path_conflict(full_dest, seen_destinations, seen_parents): - continue - - storage = file_entry.get("storage", "embedded") - if storage == "user_provided": - record_omission( - full_dest, - file_entry, - sys_id, - "user_provided", - None, - ) - # The pack writes the instructions in the slot's place - # and holds it: one more member than the files listed. - instructions = file_entry.get( - "instructions", "Please provide this file manually." - ) - pack_only_sizes.append(len( - f"File needed: {file_entry['name']}\n\n{instructions}\n".encode() - )) - seen_destinations.add(dedup_key) - _register_path(dedup_key, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(dedup_key.lower()) - continue - - local_path, status = settle( - file_entry, sys_id, dest, slot_overrides.get(full_dest) - ) - if local_path is None: - record_omission(full_dest, file_entry, sys_id, status, None) - continue - - entry, file_size = _manifest_entry( - local_path, dest, None, db, repo_root, - selection.fields(dest, file_entry["name"]), - ) - if entry is not None and dest in game_destinations: - entry["category"] = GAME_DATA - if entry is not None and target_cores is None: - order = declaration_order(full_dest) - if full_dest in slot_choices or len(order) > 1: - _record_slot_choices( - entry, slot_choices.get(full_dest, []), order, - settle, dest, db, repo_root, - ) - if entry is None: - record_omission(full_dest, file_entry, sys_id, "not_found", None) - if file_size and full_dest not in seen_destinations: - if _in_data_cache(local_path, data_registry): - cache_held[full_dest] = (local_path, file_size) - else: - pack_only_sizes.append(file_size) - seen_destinations.add(dedup_key) - _register_path(dedup_key, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(dedup_key.lower()) - continue - - manifest_files.append(entry) - platform_entries[dedup_key] = (entry, full_dest, dest) - omitted_by_destination.pop(full_dest, None) - total_size += file_size - seen_destinations.add(dedup_key) - _register_path(dedup_key, seen_destinations, seen_parents) - if case_insensitive: - seen_lower.add(dedup_key.lower()) - - # Phase 2: core complement (emulator extras) - unplaceable: list[dict] = [] - baseline_claims: dict[str, dict] = {} - absent: list[dict] = [] - if source != "platform": - core_files = _collect_emulator_extras( - config, - emulators_dir, + def settle( + file_entry: dict, sys_id: str, dest: str, override: str | None + ) -> tuple[str | None, str]: + """The file served once the slot is settled, or None and why not.""" + local_path, status = resolve_declaration( + file_entry, db, - seen_destinations, - base_dest, - emu_profiles, - target_cores=target_cores, - include_all=(source == "truth"), - unplaceable=unplaceable, - baseline_claims=baseline_claims, - absent=absent, - undeclared=undeclared, + bios_dir, + build.zip_contents, + build.data_registry, + override, + offline=opts.offline, ) - else: - core_files = [] - _record_unplaceable(unplaceable, record_omission, config, emu_profiles) - _record_absent( - absent, config, base_dest, region_drops, required_only, - seen_destinations, omitted_by_destination, record_omission, - ) - total_size += _manifest_core_entries( - core_files, config, db, bios_dir, base_dest, repo_root, - zip_contents, offline, region_drops, case_insensitive, - seen_destinations, seen_lower, seen_parents, manifest_files, - omitted_by_destination, record_omission, pack_only_sizes, selection, - required_only, manifest_validation, manifest_owners, data_registry, - emu_profiles, - ) - for key, (entry, full_dest, dest) in platform_entries.items(): - declared = declared_by.get(full_dest, set()) - if declared and declared != set(entry.get("systems") or []): - entry["declared_in"] = sorted(declared) - claims = baseline_claims.get(key, {}).get("other_claims") - if claims and any(not is_game_data(claim) for claim in claims): - # A core reads this path as firmware: a pack without game data - # still fills it. - entry.pop("category", None) - if claims: - _attach_claims( - entry, claims, db, bios_dir, zip_contents, offline, required_only, - manifest_validation, manifest_owners, dest, dest, repo_root, - data_registry, - ) - # A platform omission narrows like a platform file: by the systems - # declaring it, which can be fewer than the ones whose cores read it. - for full_dest, omission in omitted_by_destination.items(): - declared = declared_by.get(full_dest, set()) - if ( - omission.get("cores") is None - and declared - and declared != set(omission.get("systems") or []) - ): - omission["declared_in"] = sorted(declared) + if status == "not_found" and not reads_file_contents(verification_mode): + found = agnostic_substitute(file_entry, sys_id, db, build.manifest_profiles) + if found: + local_path, status = found[0], "agnostic_fallback" + if os.path.basename(local_path) != file_entry.get("name", ""): + # The pack explains the rename in a note of its own. + build.rename_notes.add(file_entry.get("name", "")) + # The builder's verdict: a hash platform omits what its frontend + # would reject, a zipped_file archive included when the member is + # missing whatever the outer resolution said. An existence + # platform never reads the bytes. + status, refusal = baseline_verdict( + file_entry, local_path, status, verification_mode, + config.get("hash_rule", ""), + ) + if refusal or status in ("not_found", "external"): + return None, "hash_mismatch" if refusal else status + # The variant the pack ships when an emulator rejects the + # resolved file: the installer must place the same bytes. + local_path, _disagreement = validated_choice( + file_entry, local_path, db, build.manifest_validation, bios_dir, + digest_algorithm(verification_mode), dest, build.manifest_owners, + ) + return local_path, status - # Phase 3: data directories. They are not files of the collection: the - # installer fetches each from its source archive and keeps the members - # whose hash the list below records, the same tree the pack carries. - data_refs: dict[str, tuple[str, tuple[str, ...], str, bool]] = {} - reclaim = {full: path for full, (path, _size) in cache_held.items()} - core_trees = ([] if source == "platform" - else core_data_trees(config, emu_profiles, platform_name, data_registry, - target_cores)) - data_members = list(_data_directory_members( - pack_systems, data_registry, platform_name, base_dest, - case_insensitive, seen_destinations, seen_lower, seen_parents, - data_refs, required_only=required_only, - core_trees=core_trees, - reclaim=reclaim, - )) - # A platform entry found in a tree the pack carries is that tree's member: - # the installer rebuilds it from the tree's archive. One found in a tree - # the pack does not carry stays omitted, held by the pack alone. - for full_dest, (_path, size) in cache_held.items(): - if full_dest in reclaim: - pack_only_sizes.append(size) - else: - omitted_by_destination.pop(full_dest, None) - data_sizes = pack_only_sizes + [os.path.getsize(src) for src, _dest in data_members] - data_directories = _manifest_data_directories( - data_members, data_refs, data_registry or {}, base_dest, - tree_readers(pack_systems, core_trees), pack_systems, - ) - - # The pack is unzipped into the BIOS folder: an entry the installer puts - # in the roms, emulators or configs folder is in its list, not in the ZIP. - outer = [e for e in manifest_files if e.get("root") in OUTER_ROOTS] - now = _build_timestamp(db) - core_names, system_cores = _manifest_core_index( - config, emu_profiles, manifest_files, omitted_by_destination.values() - ) - - result: dict = { - "manifest_version": 2, - "source": source, - "regions": list(regions or []), - # A target-filtered manifest is only distinguishable from the full one - # by its filename, so it records the filter the way regions does. - # Absent on an unfiltered manifest rather than empty, to leave the - # twelve default files byte-identical. - **({"target": target_name} if target_name else {}), - # Every game data file below says so: the installer's --no-game-data - # relies on it, and refuses a list that does not record categories. - "categorized": True, - # The entries a slot decides carry `slot`, which --one-per-slot - # reads: without this mark the installer refuses it. - "slot_fields": True, - **({"no_game_data": True} if no_game_data else {}), - "platform": platform_name, - "display_name": platform_display, - "version": platform_list_version(config, platform_name), - "generated": now, - "base_destination": base_dest, - "detect": detect, - "standalone_copies": _standalone_copies( - standalone_copies, manifest_profiles, manifest_files, - ), - "total_files": len(manifest_files), - "total_size": total_size, - "pack_files": ( - len(manifest_files) - len(outer) + len(data_sizes) + len(PACK_DOCUMENTS) - + len(rename_notes) + len(pack_markers(platform_name, target_name, platforms_dir)) - ), - "pack_size": total_size - sum(int(e.get("size") or 0) for e in outer) + sum(data_sizes), - "total_omitted": len(omitted_by_destination), - "omitted_files": sorted( - omitted_by_destination.values(), key=lambda entry: entry["dest"] - ), - "core_names": core_names, - **({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores( - config, emu_profiles, core_names, platforms_dir, - )) else {}), - **({"offered_boards": offered} if (offered := _offered_boards( - config, emu_profiles, core_names, - [*manifest_files, *omitted_by_destination.values()], - )) else {}), - "system_cores": system_cores, - # The names the platform itself gives its systems (Batocera's psx), - # which --system accepts beside the ids. - "system_names": platform_system_names(config, list(pack_systems)), - "system_titles": system_titles(manifest_files, omitted_by_destination.values()), - "files": manifest_files, - } - if data_directories: - result["data_directories"] = data_directories - for root in OUTER_ROOTS: - layout = outer_layout(config, root) or {} - if layout and any(entry.get("root") == root - for entry in [*manifest_files, *result["omitted_files"]]): - # Where the installer finds the folder: relative to the folder - # holding the BIOS folder, which the platform names bios_folder. - result[f"{root}_directory"] = { - key: layout[key] for key in MANIFEST_OUTER_FIELDS if key in layout - } - saved = [entry for entry in manifest_files if entry.get("root") == "save"] - if saved: - layout = save_layout(config) - result["save_directory"] = {"folder": layout.folder, "by_core": layout.by_core} - if layout.by_system: - # The launcher writes the directory at each launch, one folder - # per system: each dest starts with that folder. - result["save_directory"]["by_system"] = True - if case_insensitive and fold_case is None and any( + if opts.source != "truth": + build.list_baseline(settle) + build.list_core_files() + result = build.result(build.list_data_directories()) + detect = build.install_section.get("detect", []) + if build.case_insensitive and opts.fold_case is None and any( d.get("os") not in CASE_FOLDING_OS for d in detect ): # RetroArch also runs where case is kept: there Mesen-CE opens @@ -5421,11 +6075,13 @@ def generate_manifest( # or macOS too, stays folded. kept = generate_manifest( platform_name, platforms_dir, db, bios_dir, registry_path, - emulators_dir, zip_contents, full_profiles, target_cores, source, - regions, target_name, offline, required_only, data_registry, - fold_case=False, no_game_data=no_game_data, + emulators_dir=opts.emulators_dir, zip_contents=build.zip_contents, + emu_profiles=full_profiles, target_cores=opts.target_cores, source=opts.source, + regions=opts.regions, target_name=opts.target_name, offline=opts.offline, + required_only=opts.required_only, data_registry=build.data_registry, + fold_case=False, no_game_data=opts.no_game_data, ) - folded = {entry["dest"] for entry in manifest_files} + folded = {entry["dest"] for entry in build.manifest_files} folded_lower = {dest.lower() for dest in folded} variants = [ entry for entry in kept["files"] @@ -5433,8 +6089,8 @@ def generate_manifest( ] if variants: result["case_variants"] = variants - if build_out is not None: - build_out.update(slot_choices=slot_choices, profiles=manifest_profiles) + if opts.build_out is not None: + opts.build_out.update(slot_choices=build.slot_choices, profiles=build.manifest_profiles) return result @@ -5445,7 +6101,7 @@ def generate_install_list( bios_dir: str, registry_path: str, standalone_out: dict | None = None, - **options: Any, + **options: Unpack[InstallListOptions], ) -> dict: """The list install.py reads: the full manifest, the files and omissions the --source truth build holds apart from it, and the emulators with a @@ -5457,22 +6113,23 @@ def generate_install_list( A manifest narrowed by a target, a case fold or --one-per-slot is no list install.py reads by default and gets neither. """ + settings = _ManifestSettings(**options) built: dict = {} result = generate_manifest(platform_name, platforms_dir, db, bios_dir, registry_path, build_out=built, **options) - if (options.get("source", "full") != "full" or options.get("target_cores") is not None - or options.get("fold_case") is not None or options.get("one_per_slot")): + if (settings.source != "full" or settings.target_cores is not None + or settings.fold_case is not None or settings.one_per_slot): return result + truth_options: InstallListOptions = {**options, "source": "truth"} with contextlib.redirect_stdout(io.StringIO()): truth = generate_manifest( platform_name, platforms_dir, db, bios_dir, registry_path, - **{**options, "source": "truth"}, known_slot_choices=built["slot_choices"], + **truth_options, known_slot_choices=built["slot_choices"], ) _mark_truth(result, truth) layouts = _standalone_layouts( - built["profiles"], options.get("emulators_dir", "emulators"), db, bios_dir, - options.get("zip_contents") or {}, options.get("offline"), platforms_dir, - os.path.dirname(os.path.dirname(os.path.abspath(__file__))), result, + built["profiles"], settings.emulators_dir, db, bios_dir, + settings.zip_contents or {}, settings.offline, platforms_dir, result, ) if layouts: result["standalone_builds"] = sorted(layouts) @@ -5539,7 +6196,6 @@ def _standalone_layouts( zip_contents: dict, offline: bool | None, platforms_dir: str, - repo_root: str, result: dict, ) -> dict[str, list]: """Per emulator with a standalone build, the files `--emulator X @@ -5550,6 +6206,7 @@ def _standalone_layouts( that entry. Another is written whole. A data tree member is left to the list's data directories. """ + repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) known = { copy["sha1"] for entry in [*result["files"], *result.get("truth_files", [])] @@ -5596,6 +6253,45 @@ def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, li return {ref: sorted(names) for ref, names in cores.items() if ref not in declared} +def _tree_group( + ref: str, prefix: str, entry: dict, base_dest: str, versions: dict[str, dict[str, dict]], +) -> dict: + """The manifest record of one data directory, before its files. + + ``versions`` caches each .versions.json read, by path. + """ + version = str(entry.get("version", "master")) + dest = prefix + if base_dest and (dest == base_dest or dest.startswith(base_dest + "/")): + dest = dest[len(base_dest):].lstrip("/") + group: dict = { + "ref": ref, + "dest": dest, + "url": str(entry.get("source_url", "")).format(version=version), + "type": "zip" if entry.get("source_type") == "zip" else "tarball", + "systems": [], + "files": {}, + } + if group["type"] == "zip": + group["strip_components"] = int(entry.get("strip_components", 0)) + else: + group["source_path"] = str(entry.get("source_path", "")).format(version=version) + if entry.get("exclude"): + group["exclude"] = [str(e) for e in entry["exclude"]] + cache = entry.get("local_cache") + if cache: + recorded = Path(cache).parent / ".versions.json" + if str(recorded) not in versions: + try: + versions[str(recorded)] = json.loads(recorded.read_text()) + except FileNotFoundError: + versions[str(recorded)] = {} + size = versions[str(recorded)].get(ref, {}).get("archive_size") + if isinstance(size, int) and size > 0: + group["archive_size"] = size + return group + + def _manifest_data_directories( members: list[tuple[str, str]], refs: dict[str, tuple[str, tuple[str, ...], str, bool]], @@ -5633,39 +6329,12 @@ def _manifest_data_directories( ref, systems, prefix, needed = refs[full] if platform_systems is not None: systems = tuple(own for sid in systems for own in by_norm.get(_norm_system_id(sid), ())) - entry = registry.get(ref, {}) key = (ref, prefix) group = grouped.get(key) if group is None: - version = str(entry.get("version", "master")) - dest = prefix - if base_dest and (dest == base_dest or dest.startswith(base_dest + "/")): - dest = dest[len(base_dest):].lstrip("/") - group = grouped[key] = { - "ref": ref, - "dest": dest, - "url": str(entry.get("source_url", "")).format(version=version), - "type": "zip" if entry.get("source_type") == "zip" else "tarball", - "systems": [], - "files": {}, - } - if group["type"] == "zip": - group["strip_components"] = int(entry.get("strip_components", 0)) - else: - group["source_path"] = str(entry.get("source_path", "")).format(version=version) - if entry.get("exclude"): - group["exclude"] = [str(e) for e in entry["exclude"]] - cache = entry.get("local_cache") - if cache: - recorded = Path(cache).parent / ".versions.json" - if str(recorded) not in versions: - try: - versions[str(recorded)] = json.loads(recorded.read_text()) - except FileNotFoundError: - versions[str(recorded)] = {} - size = versions[str(recorded)].get(ref, {}).get("archive_size") - if isinstance(size, int) and size > 0: - group["archive_size"] = size + group = grouped[key] = _tree_group( + ref, prefix, registry.get(ref, {}), base_dest, versions + ) if needed: group["needed"] = True group["systems"].extend(s for s in systems if s not in group["systems"]) @@ -6006,23 +6675,18 @@ def _content_narrowing_tags() -> tuple[str, ...]: Region and target are absent on purpose: both are handed to the check itself, which narrows its expectation instead of skipping it. """ + # (source, one_per_slot, required_only), one dimension at a time. dimensions = ( - {"source": "platform"}, - {"source": "truth"}, - {"one_per_slot": True}, - {"required_only": True}, + ("platform", False, False), + ("truth", False, False), + ("full", True, False), + ("full", False, True), ) tags: list[str] = [] - for dimension in dimensions: + for source, one_per_slot, required_only in dimensions: tags.extend( tag - for tag, _label in _narrowings( - dimension.get("source", "full"), - None, - None, - dimension.get("one_per_slot", False), - dimension.get("required_only", False), - ) + for tag, _label in _narrowings(source, None, None, one_per_slot, required_only) ) return tuple(tags) @@ -6087,18 +6751,79 @@ def _pack_archives(output_dir: str) -> list[str]: _PACK_NAME = re.compile(r"_BIOS_Pack(?:_[^/]+)?\.zip$") +class FinalizeOptions(TypedDict, total=False): + """The keyword options of verify_and_finalize_packs.""" + + platforms_dir: str + skip_conformance: bool + data_registry: dict | None + regions: list[str] | None + target_name: str | None + emulators_dir: str + no_game_data: bool + pack_systems_by_name: dict[str, dict] | None + built: Iterable[str] | None + + +@dataclass(frozen=True) +class _FinalizeSettings: + """FinalizeOptions with their defaults.""" + + platforms_dir: str = "platforms" + skip_conformance: bool = False + data_registry: dict | None = None + regions: list[str] | None = None + target_name: str | None = None + emulators_dir: str = "emulators" + no_game_data: bool = False + pack_systems_by_name: dict[str, dict] | None = None + built: Iterable[str] | None = None + + +def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> bool: + """Stage 2 for one platform of a pack: extract and verify against its + config. Prints the platform's line and its errors.""" + ( + p_ok, + _total, + _matched, + p_errors, + bl_checked, + bl_present, + core_checked, + core_present, + bl_excluded, + bl_absent, + ) = verify_pack_against_platform( + zip_path, + pname, + opts.platforms_dir, + db=db, + emulators_dir=opts.emulators_dir, + regions=opts.regions, + data_registry=opts.data_registry, + target_cores=_target_cores_for(pname, opts.target_name, opts.platforms_dir), + no_game_data=opts.no_game_data, + ) + status = "OK" if p_ok else "FAILED" + exclusion_note = "".join( + f", {part}" for part in _baseline_shortfall(bl_excluded, bl_absent) + ) + print( + f" platform {pname}: {bl_present}/{bl_checked} baseline present" + f"{exclusion_note}, " + f"{core_present}/{core_checked} cores present, {status}" + ) + if not p_ok: + for err in p_errors: + print(f" {err}") + return p_ok + + def verify_and_finalize_packs( output_dir: str, db: dict, - platforms_dir: str = "platforms", - skip_conformance: bool = False, - data_registry: dict | None = None, - regions: list[str] | None = None, - target_name: str | None = None, - emulators_dir: str = "emulators", - no_game_data: bool = False, - pack_systems_by_name: dict[str, dict] | None = None, - built: Iterable[str] | None = None, + **options: Unpack[FinalizeOptions], ) -> bool: """Verify all packs, inject manifests, generate SHA256SUMS. @@ -6116,19 +6841,22 @@ def verify_and_finalize_packs( Returns True if all packs pass verification. """ + _reject_unknown("verify_and_finalize_packs", options, FinalizeOptions.__optional_keys__) + opts = _FinalizeSettings(**options) all_ok = True # Map ZIP names to platform names # By the exact name this run's reduction gives a platform's pack, never by # substring: a _Custom or regional pack left by another run was judged # against this run's expectation and failed it. - registered = list_registered_platforms(platforms_dir) + registered = list_registered_platforms(opts.platforms_dir) expected = _expected_pack_names( - registered, platforms_dir, regions, target_name, no_game_data=no_game_data + registered, opts.platforms_dir, opts.regions, opts.target_name, + no_game_data=opts.no_game_data, ) packs = _pack_archives(output_dir) - if built is not None: - packs = [name for name in packs if name in set(built)] + if opts.built is not None: + packs = [name for name in packs if name in set(opts.built)] pack_to_platform: dict[str, list[str]] = {} for name in packs: for pname in registered: @@ -6140,7 +6868,7 @@ def verify_and_finalize_packs( zip_path = os.path.join(output_dir, name) # Stage 1: database integrity - ok, manifest = verify_pack(zip_path, db, data_registry=data_registry) + ok, manifest = verify_pack(zip_path, db, data_registry=opts.data_registry) summary = manifest["summary"] status = "OK" if ok else "ERRORS" print( @@ -6152,51 +6880,17 @@ def verify_and_finalize_packs( print(f" ERROR: {err}") all_ok = False failing.append(name) - annotate_pack_systems(manifest, (pack_systems_by_name or {}).get(name)) + annotate_pack_systems(manifest, (opts.pack_systems_by_name or {}).get(name)) inject_manifest(zip_path, manifest) # Stage 2: platform conformance (extract + verify) # Skipped for filtered/split/custom packs (intentionally partial) - if skip_conformance: + if opts.skip_conformance: continue if _narrows_contents(name): continue - platforms = pack_to_platform.get(name, []) - for pname in platforms: - ( - p_ok, - total, - matched, - p_errors, - bl_checked, - bl_present, - core_checked, - core_present, - bl_excluded, - bl_absent, - ) = verify_pack_against_platform( - zip_path, - pname, - platforms_dir, - db=db, - emulators_dir=emulators_dir, - regions=regions, - data_registry=data_registry, - target_cores=_target_cores_for(pname, target_name, platforms_dir), - no_game_data=no_game_data, - ) - status = "OK" if p_ok else "FAILED" - exclusion_note = "".join( - f", {part}" for part in _baseline_shortfall(bl_excluded, bl_absent) - ) - print( - f" platform {pname}: {bl_present}/{bl_checked} baseline present" - f"{exclusion_note}, " - f"{core_present}/{core_checked} cores present, {status}" - ) - if not p_ok: - for err in p_errors: - print(f" {err}") + for pname in pack_to_platform.get(name, []): + if not _conforms(zip_path, pname, db, opts): all_ok = False failing.append(f"{name} ({pname})") @@ -6206,71 +6900,6 @@ def verify_and_finalize_packs( print(f"ERROR: packs failed verification: {', '.join(failing)}", file=sys.stderr) return all_ok -from packpaths import ( # noqa: E402,F401 - MEDIA_MARKER, - lands_on_android, - _archive_destination, - _path_parents, - _has_path_conflict, - _register_path, - _flat, - _resolve_destination, - placement_block, - save_layout, -) -from packextras import ( # noqa: E402,F401 - ExtraResolver, - extra_full_destination, - extra_region_key, - prefixed_destination, - save_entry_fields, - save_manifest_dest, - _detect_extras_prefix, - _detect_slug_structure, - _map_emulator_to_slug, - _collect_emulator_extras, - _extra_system_ids, - extras_for_systems as _extras_for_systems, - platform_region_groups, - emulator_region_drops, - emulator_required_spares, - _emulator_region_group, - expand_agnostic_entries, - undeclared_report, -) - - -from packreadme import ( # noqa: E402 - _build_readme, - _build_agnostic_rename_readme, - save_place, -) -from packverify import ( # noqa: E402,F401 - _check_member_hash, - _hash_matches, - _repo_satisfies_declaration, - _intentional_hash_exclusion, - verify_pack_against_platform, - verify_pack, - generate_sha256sums, -) - - -# _OFFLINE is deliberately not re-exported: importing a value copies it, so a -# facade name would keep saying False after set_offline() changed the flag. -from packresolve import ( # noqa: E402,F401 - ACCEPTED_HASHES, - _detect_hash_type, - sha1_for_hash, - preferred_entries as _preferred_entries, - parse_hash_input, - parse_hash_file, - lookup_hashes, - resolve_declaration, - resolve_file, - download_external, -) - if __name__ == "__main__": from common import run_cli diff --git a/scripts/hashing.py b/scripts/hashing.py index 5383b002b..ab722c3eb 100644 --- a/scripts/hashing.py +++ b/scripts/hashing.py @@ -10,7 +10,7 @@ import os import zipfile import zlib from pathlib import Path -from typing import BinaryIO +from typing import IO, BinaryIO from collections.abc import Iterable @@ -85,16 +85,16 @@ def _compute_hashes(filepath: str | Path, algos: frozenset[str]) -> dict[str, st result["adler32"] = format(adler & 0xFFFFFFFF, "08x") return result -def md5sum(source: str | Path | object) -> str: +def md5sum(source: str | os.PathLike[str] | IO[bytes]) -> str: """Compute MD5 of a file path or file-like object - matches Batocera's md5sum().""" h = hashlib.md5() - if hasattr(source, "read"): - for chunk in iter(lambda: source.read(65536), b""): - h.update(chunk) - else: + if isinstance(source, (str, os.PathLike)): with open(source, "rb") as f: for chunk in iter(lambda: f.read(65536), b""): h.update(chunk) + else: + for chunk in iter(lambda: source.read(65536), b""): + h.update(chunk) return h.hexdigest() _md5_composite_cache: dict[str, str] = {} diff --git a/scripts/largefiles.py b/scripts/largefiles.py index 9986aa35c..94adb9f0b 100644 --- a/scripts/largefiles.py +++ b/scripts/largefiles.py @@ -159,6 +159,30 @@ def fetch_large_file( return None +def _download(name: str, tmp_path: str) -> bool: + """Stream the first release URL of *name* that answers into *tmp_path*.""" + # Only a name no candidate answers is reported: a spaced name is + # published dotted, and logging its first 404 read as a missing asset. + failures: list[str] = [] + for candidate, url in _asset_urls(name): + try: + req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"}) + with urllib.request.urlopen(req, timeout=300) as resp, open(tmp_path, "wb") as f: + while True: + chunk = resp.read(65536) + if not chunk: + break + f.write(chunk) + return True + except (urllib.error.URLError, OSError, http.client.HTTPException) as exc: + # A stalled or cut stream is a timeout or IncompleteRead, not + # a URLError: it escaped this handler and left its scratch. + failures.append(f" large file {candidate}: {exc}") + for failure in failures: + print(failure, file=sys.stderr) + return False + + def _fetch_asset( name: str, dest_dir: str, @@ -209,28 +233,7 @@ def _fetch_asset( ) os.close(tmp_fd) try: - downloaded = False - # Only a name no candidate answers is reported: a spaced name is - # published dotted, and logging its first 404 read as a missing asset. - failures: list[str] = [] - for candidate, url in _asset_urls(name): - try: - req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"}) - with urllib.request.urlopen(req, timeout=300) as resp, open(tmp_path, "wb") as f: - while True: - chunk = resp.read(65536) - if not chunk: - break - f.write(chunk) - downloaded = True - break - except (urllib.error.URLError, OSError, http.client.HTTPException) as exc: - # A stalled or cut stream is a timeout or IncompleteRead, not - # a URLError: it escaped this handler and left its scratch. - failures.append(f" large file {candidate}: {exc}") - if not downloaded: - for failure in failures: - print(failure, file=sys.stderr) + if not _download(name, tmp_path): return None snapshot = _read_once(tmp_path) if snapshot is None or not _matches(snapshot[0], expected_sha1, expected_md5): 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/packextras.py b/scripts/packextras.py index e713b229e..464150244 100644 --- a/scripts/packextras.py +++ b/scripts/packextras.py @@ -6,7 +6,9 @@ this module builds so the report and the pack withdraw the same files.""" from __future__ import annotations -from collections.abc import Iterable +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict from common import PROFILE_IDENTITY_FIELDS, _norm_system_id, entry_system_ids from alternatives import core_file_spares, required_only_spares, set_fields @@ -24,6 +26,16 @@ from validation import deliverable, read_from_save_dir, read_from_system_dir from packpaths import libretro_systems, save_destination, save_layout from region import FILE_GROUP +if TYPE_CHECKING: + from typing_extensions import Unpack + + +def reject_unknown(function: str, options: Mapping[str, object], known: frozenset[str]) -> None: + """Refuse a keyword the options do not declare, as a named parameter would.""" + for key in options: + if key not in known: + raise TypeError(f"{function}() got an unexpected keyword argument '{key}'") + def _detect_extras_prefix(config: dict, base_dest: str) -> str: """The prefix core-extra destinations take (may be empty). @@ -256,6 +268,10 @@ def _file_sha1(path: str) -> str | None: return None +class ResolverOptions(TypedDict, total=False): + pending_assets: bool + + class ExtraResolver: """How the builder finds the copy of a core's file it packs. @@ -277,7 +293,7 @@ class ExtraResolver: offline: bool | None = True, *, profiles: dict, - pending_assets: bool = False, + **options: Unpack[ResolverOptions], ) -> None: self.profiles = profiles self.db = db @@ -289,7 +305,8 @@ class ExtraResolver: self.offline = offline # verify's replay: never downloads, and counts the release asset an # online build fetches, as it does for a platform entry. - self.pending_assets = pending_assets + reject_unknown("ExtraResolver", options, ResolverOptions.__optional_keys__) + self.pending_assets = options.get("pending_assets", False) # Each profile's entries by slot, built on first use: every extra # scanned its whole profile, 33 million entries in one verify --all. self._slots: dict[str, dict[tuple[str, str], list[dict]]] = {} @@ -341,6 +358,18 @@ class ExtraResolver: return local_path, status, disagreement +class HiddenOptions(TypedDict, total=False): + """How hidden_extras replays the builder, and what else it fills.""" + + report: list[dict] | None + resolver: ExtraResolver | None + placed_kind: dict[str, str] | None + placed_local: dict[str, str] | None + system_ids: list[str] | None + include_all: bool + required_only: bool + + def hidden_extras( config: dict, emulators_dir: str, @@ -350,13 +379,7 @@ def hidden_extras( target_cores: set[str] | None = None, region_drops: set[str] | None = None, placed: set[str] | None = None, - report: list[dict] | None = None, - resolver: ExtraResolver | None = None, - placed_kind: dict[str, str] | None = None, - placed_local: dict[str, str] | None = None, - system_ids: list[str] | None = None, - include_all: bool = False, - required_only: bool = False, + **options: Unpack[HiddenOptions], ) -> dict[tuple[str, str, str], str]: """Report entries the builder holds and still leaves out, with the reason. @@ -386,6 +409,14 @@ def hidden_extras( """ from packpaths import _register_path, placement_block + reject_unknown("hidden_extras", options, HiddenOptions.__optional_keys__) + report = options.get("report") + resolver = options.get("resolver") + placed_kind = options.get("placed_kind") + placed_local = options.get("placed_local") + system_ids = options.get("system_ids") + include_all = options.get("include_all", False) + required_only = options.get("required_only", False) sha1_by_path = { entry.get("path"): sha1 for sha1, entry in db.get("files", {}).items() } @@ -416,13 +447,8 @@ def hidden_extras( for fe in extras: if required_only and (fe.get("required") is False or id(fe) in spares): continue - dest = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) - if not dest or (region_drops and extra_region_key(fe, region_prefix) in region_drops): - continue - if fe.get("root") in OUTER_ROOTS: - # As the builder does: the pack is extracted into the BIOS folder - # and cannot reach the roms, emulator or configs folder, the - # installer places these files. + dest = _packable_dest(fe, region_drops, region_prefix) + if not dest: continue full = extra_full_destination(fe, prefix) if not full: @@ -455,17 +481,43 @@ def hidden_extras( content[full.lower()] = held if case_insensitive: lower.add(full.lower()) - if placed is not None and local: - placed.add(full) - if placed_kind is not None and local: - placed_kind[full] = fe.get("category", "bios") - if placed_local is not None and local: - placed_local[full] = local + if local: + _record_placed(full, local, fe, placed, placed_kind, placed_local) # A file read below a save directory kept per system is packed once per # system: one copy left out does not leave the file out. return {key: reason for key, reason in hidden.items() if key not in packed_keys} +def _packable_dest(fe: dict, region_drops: set[str] | None, region_prefix: str) -> str: + """The extra's destination, empty when the builder never places it.""" + dest = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) + if not dest or (region_drops and extra_region_key(fe, region_prefix) in region_drops): + return "" + if fe.get("root") in OUTER_ROOTS: + # As the builder does: the pack is extracted into the BIOS folder + # and cannot reach the roms, emulator or configs folder, the + # installer places these files. + return "" + return dest + + +def _record_placed( + full: str, + local: str, + fe: dict, + placed: set[str] | None, + placed_kind: dict[str, str] | None, + placed_local: dict[str, str] | None, +) -> None: + """Note a held extra the pack carries in each record the caller asked for.""" + if placed is not None: + placed.add(full) + if placed_kind is not None: + placed_kind[full] = fe.get("category", "bios") + if placed_local is not None: + placed_local[full] = local + + def _extra_dest(u: dict) -> str: """Where a report entry lands before any platform prefix. @@ -504,6 +556,43 @@ def unplaceable_extras( return unplaced +@dataclass(frozen=True) +class _ScanContext: + """What every seed of one agnostic scan reads and fills.""" + + db: dict + files_db: dict + by_name: dict + seen_dests: set + extras_prefix: str + taken: dict[str, dict] | None + profiles: dict + + +@dataclass(frozen=True) +class _ResolvedDirs: + """Where a profile's own files resolve, the evidence a scan anchors on.""" + + dirs: dict[int, str] + named_only: set[int] + votes: dict[str, int] + + +@dataclass(frozen=True) +class _ScanSeed: + """One agnostic entry of one layout and the folder its scan walks.""" + + emu_name: str + layout: dict + entry: dict + name: str + companion_ext: str + image: dict | None + path_prefix: str + exact_dirs: frozenset[str] + folder: str + + def _agnostic_scan_extras( profiles: dict, relevant: set, @@ -513,7 +602,6 @@ def _agnostic_scan_extras( extras_prefix: str, standalone_set: set[str] | None = None, taken: dict[str, dict] | None = None, - all_profiles: dict | None = None, ) -> list[dict]: """Every interchangeable candidate a filename-agnostic core accepts. @@ -522,11 +610,11 @@ def _agnostic_scan_extras( The directory is the delicate part: anchoring it on a single filename walked into another emulator's tree, so the profile's own files have to agree before the scan follows an ambiguous name. - ``all_profiles`` are the profiles a placeholder's directory is proven - from, ``profiles`` when not given. """ extras: list[dict] = [] - files_db = db.get("files", {}) + context = _ScanContext( + db, db.get("files", {}), by_name, seen_dests, extras_prefix, taken, profiles, + ) # Third pass: the agnostic scan. For filename-agnostic cores, include all # DB files matching the system path prefix and size criteria. for emu_name, profile in sorted(profiles.items()): @@ -535,199 +623,253 @@ def _agnostic_scan_extras( if emu_name not in relevant: continue is_profile_agnostic = profile.get("bios_mode") == "agnostic" - if not is_profile_agnostic: - if not any(f.get("agnostic") for f in profile.get("files", [])): - continue - - # Where each of this profile's files resolves. A scan anchored on one - # filename walks into whatever tree that name happens to hit: rom1.bin - # is a PS2 ROM and a Roland SC-55 ROM, GameIndex.yaml belongs to four - # PS2 profiles and to an Android package. One match is not evidence - # of a directory, two files of the same profile agreeing is. - resolved_dirs: dict[int, str] = {} - named_only: set[int] = set() - agnostic_votes: dict[str, int] = {} - for candidate in profile.get("files", []): - if not isinstance(candidate, dict): - continue - local, status = resolve_local_file( - {**candidate, "source_profile": emu_name}, - db, - dest_hint=candidate.get("path", ""), - ) - if not local or "/" not in local: - continue - directory = local.rsplit("/", 1)[0] - if directory.endswith("/.variants"): - directory = directory[: -len("/.variants")] - resolved_dirs[id(candidate)] = directory + "/" - if not (resolution_is_hash_exact(status) or status == "path_exact"): - named_only.add(id(candidate)) - agnostic_votes[directory + "/"] = ( - agnostic_votes.get(directory + "/", 0) + 1 - ) - - own = profile - for profile, standalone in platform_layouts(emu_name, own, standalone_set or set()): + if not is_profile_agnostic and not any( + f.get("agnostic") for f in profile.get("files", []) + ): + continue + resolved = _resolved_dirs(emu_name, profile, db) + for layout, standalone in platform_layouts(emu_name, profile, standalone_set or set()): # A layout copies each entry in order (a launcher's folder, a # system directory): its files are looked up as the profile's # own, or a bound layout scans nothing (KNULLI's bios/ps2). origin = { id(view): entry - for view, entry in zip(profile.get("files", []), own.get("files", [])) + for view, entry in zip(layout.get("files", []), profile.get("files", [])) } - for f in profile.get("files", []): + for f in layout.get("files", []): if not is_profile_agnostic and not f.get("agnostic"): continue - fname = f.get("name", "") - if not fname: - continue - # A file of the build the platform does not run seeds nothing: - # armsx2's proverb.zip is fetched by the Android app into its own - # arcade/ folder, and the libretro packs carried it at system/. - mode = f.get("mode") - if (mode == "standalone" and not standalone) or ( - mode == "libretro" and standalone - ): - continue - # The scan walks the BIOS tree: a file read below the save - # directory is placed by the gap report's pass. - if (read_from_save_dir(f, standalone) or f.get("unplaced") - or f.get("root") in OUTER_ROOTS or f.get("unprefixed")): - continue - # An agnostic BIOS mode says the BIOS filename is free, not that - # every file the emulator loads is. A free filename still has a - # known shape, and that shape is what identifies a candidate: an - # entry declaring no size takes the whole directory, which is how - # the flag icons of an Android package walked into a PS2 pack. - if f.get("category", "bios") != "bios": - continue - if not declares_shape(f): - continue - # The free name is the BIOS directory's: a shader, a sound or a - # font the emulator reads from its resources tree has a fixed - # name and must not seed a scan (yaps2 flattened 189 of them to - # the root of the RetroArch pack). - bios_dir = profile.get("bios_directory") - fpath = f.get("path") or "" - if bios_dir and "/" in fpath and not fpath.startswith(bios_dir): - continue + seed = _scan_seed(context, emu_name, layout, f, standalone, origin, resolved) + if seed is not None: + extras.extend(_seed_extras(context, seed)) + return extras - # A companion is read under its image's name with the - # extension the code appends, in that case: only a file of - # that extension is one, spelled as the code spells it. Its - # size identifies nothing, PCSX2 reads min(size, filesize) - # (BiosTools.cpp:234), and a 4 MB bound swept every smaller - # file of the folder to the BIOS root. It sits beside its - # image, so the scan looks where the image resolves: the - # held ps2-0230a-20080220.rom1 is a DVD firmware dump filed - # under DVD Firmware/. - companion_ext, image = _companion_of(profile, fname) - path_prefix = ( - resolved_dirs.get(id(origin.get(id(image), image)), "") if image - else resolved_dirs.get(id(origin.get(id(f), f)), "") - ) - # A placeholder (.bin) resolves to nothing and anchors no - # directory. The folders where the system's other profiles - # resolve hashed files of that shape do, those folders only: - # LRPS2 and PCEE2 are made of placeholders, and on Batocera, - # where no other libretro PS2 core anchors pcsx2/bios/, the - # pack held nothing there. A companion (.nvm) looks - # where its image is proven: RetroBat's pcsx2/bios/ had - # scph39001.bin and its .nvm only at the BIOS root. - exact_dirs: frozenset[str] = frozenset() - anchor = image if image else f - if not path_prefix and "<" in str(anchor.get("name", "")): - exact_dirs = placeholder_directories( - anchor, emu_name, profile, db, all_profiles or profiles - ) - if not path_prefix and not exact_dirs: - continue - # A name matching one file identifies it. A name matching several - # identifies nothing on its own, so the profile's other files have - # to agree on the directory before the scan walks it. - ambiguous = ( - id(origin.get(id(f), f)) in named_only - and len(by_name.get(fname, [])) > 1 - ) - if ambiguous and agnostic_votes.get(path_prefix, 0) < 2: - continue +def _resolved_dirs(emu_name: str, profile: dict, db: dict) -> _ResolvedDirs: + """Where each of this profile's files resolves. - # Scan DB for all files under this prefix matching size - for sha1, entry in files_db.items(): - path = entry.get("path", "") - if exact_dirs: - if ("/" not in path or path.rsplit("/", 1)[0] not in exact_dirs - or "/.variants/" in path): - continue - elif not path.startswith(path_prefix): - continue - if not companion_ext and not shape_fits(f, path, entry.get("size", 0)): - continue - scan_name = entry.get("name", "") - if not scan_name: - continue - if companion_ext: - stem, _, ext = scan_name.rpartition(".") - if not stem or ext.lower() != companion_ext.lower(): - continue - # Read only beside the image the core selected, so a - # companion counts only next to an image the image's - # own test accepts: Namco System 246 .nvm and .mec - # dumps sit beside no PS2 BIOS. - if not _image_beside(path, stem, image, files_db): - continue - scan_name = f"{stem}.{companion_ext}" - # Into the directory the seed entry names, not the root: - # yaps2 reads its BIOS from pcsx2/bios/. - seed = f.get("path") or "" - if standalone: - seed = f.get("standalone_path") or seed - else: - seed = system_dir_path(f, seed or fname) - folder = seed.rsplit("/", 1)[0] if "/" in seed else "" - dest = f"{folder}/{scan_name}" if folder else scan_name - full_dest = prefixed_destination(dest, extras_prefix) - if full_dest in seen_dests and (taken is None or full_dest not in taken): - continue - extra = { - "name": scan_name, - "destination": dest, - # The scan already holds the entry it selected, so it - # names it by content. Emitting the filename alone - # sent the packing step back to a by-name lookup, and - # three PS2 resources came back from another - # emulator's copy of the same filename. - "sha1": sha1, - "required": False, - "hle_fallback": False, - "source_emulator": profile.get("emulator", emu_name), - "source_profile": emu_name, - "source_name": fname, - "source_path": f.get("path") or "", - "category": f.get("category", "bios"), - "source_system": f.get("system"), - "source_systems": entry_system_ids(f, profile), - "region": f.get("region"), - "selection_slot": f.get("selection_slot"), - "agnostic_scan": True, - } - extra["claim_order"] = (4, 0, emu_name) - if _take(extra, full_dest, seen_dests, taken): - extras.append(extra) - else: - # The image another core's scan placed is this core's - # too, and so are the companions it reads beside it: - # Recalbox's libretro PCSX2 opens .erom next to - # the images LRPS2 placed, which LRPS2 never reads. - held = taken.get(full_dest) if taken is not None else None - if held is None or held.get("sha1") != sha1: - continue - extras.extend(_companion_extras( - _companions(path, scan_name, _companion_extensions(profile, fname), files_db), - folder, extras_prefix, seen_dests, profile, emu_name, f, taken, - )) + A scan anchored on one filename walks into whatever tree that name + happens to hit: rom1.bin is a PS2 ROM and a Roland SC-55 ROM, + GameIndex.yaml belongs to four PS2 profiles and to an Android package. + One match is not evidence of a directory, two files of the same profile + agreeing is. + """ + resolved_dirs: dict[int, str] = {} + named_only: set[int] = set() + agnostic_votes: dict[str, int] = {} + for candidate in profile.get("files", []): + if not isinstance(candidate, dict): + continue + local, status = resolve_local_file( + {**candidate, "source_profile": emu_name}, + db, + dest_hint=candidate.get("path", ""), + ) + if not local or "/" not in local: + continue + directory = local.rsplit("/", 1)[0] + if directory.endswith("/.variants"): + directory = directory[: -len("/.variants")] + resolved_dirs[id(candidate)] = directory + "/" + if not (resolution_is_hash_exact(status) or status == "path_exact"): + named_only.add(id(candidate)) + agnostic_votes[directory + "/"] = ( + agnostic_votes.get(directory + "/", 0) + 1 + ) + return _ResolvedDirs(resolved_dirs, named_only, agnostic_votes) + + +def _seeds_a_scan(f: dict, layout: dict, standalone: bool) -> bool: + """Whether an agnostic entry may seed a scan of the BIOS directory.""" + # A file of the build the platform does not run seeds nothing: + # armsx2's proverb.zip is fetched by the Android app into its own + # arcade/ folder, and the libretro packs carried it at system/. + mode = f.get("mode") + if (mode == "standalone" and not standalone) or ( + mode == "libretro" and standalone + ): + return False + # The scan walks the BIOS tree: a file read below the save + # directory is placed by the gap report's pass. + if (read_from_save_dir(f, standalone) or f.get("unplaced") + or f.get("root") in OUTER_ROOTS or f.get("unprefixed")): + return False + # An agnostic BIOS mode says the BIOS filename is free, not that + # every file the emulator loads is. A free filename still has a + # known shape, and that shape is what identifies a candidate: an + # entry declaring no size takes the whole directory, which is how + # the flag icons of an Android package walked into a PS2 pack. + if f.get("category", "bios") != "bios": + return False + if not declares_shape(f): + return False + # The free name is the BIOS directory's: a shader, a sound or a + # font the emulator reads from its resources tree has a fixed + # name and must not seed a scan (yaps2 flattened 189 of them to + # the root of the RetroArch pack). + bios_dir = layout.get("bios_directory") + fpath = f.get("path") or "" + return not (bios_dir and "/" in fpath and not fpath.startswith(bios_dir)) + + +def _scan_seed( + context: _ScanContext, + emu_name: str, + layout: dict, + f: dict, + standalone: bool, + origin: dict[int, dict], + resolved: _ResolvedDirs, +) -> _ScanSeed | None: + """The scan an agnostic entry seeds, None when it seeds none.""" + fname = f.get("name", "") + if not fname or not _seeds_a_scan(f, layout, standalone): + return None + + # A companion is read under its image's name with the + # extension the code appends, in that case: only a file of + # that extension is one, spelled as the code spells it. Its + # size identifies nothing, PCSX2 reads min(size, filesize) + # (BiosTools.cpp:234), and a 4 MB bound swept every smaller + # file of the folder to the BIOS root. It sits beside its + # image, so the scan looks where the image resolves: the + # held ps2-0230a-20080220.rom1 is a DVD firmware dump filed + # under DVD Firmware/. + companion_ext, image = _companion_of(layout, fname) + + path_prefix = ( + resolved.dirs.get(id(origin.get(id(image), image)), "") if image + else resolved.dirs.get(id(origin.get(id(f), f)), "") + ) + # A placeholder (.bin) resolves to nothing and anchors no + # directory. The folders where the system's other profiles + # resolve hashed files of that shape do, those folders only: + # LRPS2 and PCEE2 are made of placeholders, and on Batocera, + # where no other libretro PS2 core anchors pcsx2/bios/, the + # pack held nothing there. A companion (.nvm) looks + # where its image is proven: RetroBat's pcsx2/bios/ had + # scph39001.bin and its .nvm only at the BIOS root. + exact_dirs: frozenset[str] = frozenset() + anchor = image if image else f + if not path_prefix and "<" in str(anchor.get("name", "")): + exact_dirs = placeholder_directories( + anchor, emu_name, layout, context.db, context.profiles + ) + if not path_prefix and not exact_dirs: + return None + # A name matching one file identifies it. A name matching several + # identifies nothing on its own, so the profile's other files have + # to agree on the directory before the scan walks it. + ambiguous = ( + id(origin.get(id(f), f)) in resolved.named_only + and len(context.by_name.get(fname, [])) > 1 + ) + if ambiguous and resolved.votes.get(path_prefix, 0) < 2: + return None + + # Into the directory the seed entry names, not the root: + # yaps2 reads its BIOS from pcsx2/bios/. + seed = f.get("path") or "" + if standalone: + seed = f.get("standalone_path") or seed + else: + seed = system_dir_path(f, seed or fname) + folder = seed.rsplit("/", 1)[0] if "/" in seed else "" + return _ScanSeed( + emu_name, layout, f, fname, companion_ext, image, path_prefix, exact_dirs, folder, + ) + + +def _scanned_name(context: _ScanContext, seed: _ScanSeed, entry: dict) -> tuple[str, str] | None: + """(path, name in the pack) of a database file the seed's scan accepts.""" + path = entry.get("path", "") + if seed.exact_dirs: + if ("/" not in path or path.rsplit("/", 1)[0] not in seed.exact_dirs + or "/.variants/" in path): + return None + elif not path.startswith(seed.path_prefix): + return None + if not seed.companion_ext and not shape_fits(seed.entry, path, entry.get("size", 0)): + return None + scan_name = entry.get("name", "") + if not scan_name: + return None + if seed.companion_ext: + stem, _, ext = scan_name.rpartition(".") + if not stem or ext.lower() != seed.companion_ext.lower(): + return None + # Read only beside the image the core selected, so a + # companion counts only next to an image the image's + # own test accepts: Namco System 246 .nvm and .mec + # dumps sit beside no PS2 BIOS. + if not _image_beside(path, stem, seed.image, context.files_db): + return None + scan_name = f"{stem}.{seed.companion_ext}" + return path, scan_name + + +def _scan_extra(seed: _ScanSeed, scan_name: str, dest: str, sha1: str) -> dict: + """The extra a scan emits for one database file.""" + f, layout, emu_name = seed.entry, seed.layout, seed.emu_name + extra = { + "name": scan_name, + "destination": dest, + # The scan already holds the entry it selected, so it + # names it by content. Emitting the filename alone + # sent the packing step back to a by-name lookup, and + # three PS2 resources came back from another + # emulator's copy of the same filename. + "sha1": sha1, + "required": False, + "hle_fallback": False, + "source_emulator": layout.get("emulator", emu_name), + "source_profile": emu_name, + "source_name": seed.name, + "source_path": f.get("path") or "", + "category": f.get("category", "bios"), + "source_system": f.get("system"), + "source_systems": entry_system_ids(f, layout), + "region": f.get("region"), + "selection_slot": f.get("selection_slot"), + "agnostic_scan": True, + } + extra["claim_order"] = (4, 0, emu_name) + return extra + + +def _seed_extras(context: _ScanContext, seed: _ScanSeed) -> list[dict]: + """The extras one seed's scan places, companions included.""" + extras: list[dict] = [] + taken = context.taken + # Scan DB for all files under this prefix matching size + for sha1, entry in context.files_db.items(): + scanned = _scanned_name(context, seed, entry) + if scanned is None: + continue + path, scan_name = scanned + dest = f"{seed.folder}/{scan_name}" if seed.folder else scan_name + full_dest = prefixed_destination(dest, context.extras_prefix) + if full_dest in context.seen_dests and (taken is None or full_dest not in taken): + continue + extra = _scan_extra(seed, scan_name, dest, sha1) + if _take(extra, full_dest, context.seen_dests, taken): + extras.append(extra) + else: + # The image another core's scan placed is this core's + # too, and so are the companions it reads beside it: + # Recalbox's libretro PCSX2 opens .erom next to + # the images LRPS2 placed, which LRPS2 never reads. + held = taken.get(full_dest) if taken is not None else None + if held is None or held.get("sha1") != sha1: + continue + extras.extend(_companion_extras( + _companions( + path, scan_name, _companion_extensions(seed.layout, seed.name), + context.files_db, + ), + seed.folder, context.extras_prefix, context.seen_dests, seed.layout, + seed.emu_name, seed.entry, taken, + )) return extras @@ -1220,7 +1362,7 @@ class ExtraPlacement: """The names a report entry's core goes by: its profile key and the upstream names its profile lists.""" key = entry.get("profile") or entry.get("emulator", "") - profile = self.profiles.get(key) or next( + profile: dict = self.profiles.get(key) or next( (pp for pp in self.profiles.values() if pp.get("emulator") == key), {} ) return {str(key), *(str(c) for c in profile.get("cores") or [])} - {""} @@ -1266,6 +1408,48 @@ def undeclared_report( ) +class CollectOptions(TypedDict, total=False): + """The records _collect_emulator_extras fills, and the report it reuses.""" + + claimants: dict[tuple[str, str, str], str] | None + unplaceable: list[dict] | None + baseline_claims: dict[str, dict] | None + absent: list[dict] | None + undeclared: list[dict] | None + + +@dataclass +class _FirstPass: + """The state the gap report's pass threads through its entries.""" + + config: dict + placement: ExtraPlacement + rank: _ClaimRanks + seen_dests: set[str] + # Destination -> the extra that took it, to record later claimants on. + taken: dict[str, dict] + claimants: dict[tuple[str, str, str], str] | None + unplaceable: list[dict] | None + absent: list[dict] | None + extras: list[dict] = field(default_factory=list) + + +@dataclass(frozen=True) +class _CopyScope: + """What the second pass reads to copy a covered file to another path.""" + + config_key: str + covered_names: set[str] + platform_names: set[str] + seen: set + seen_dests: set[str] + taken: dict[str, dict] + copied: dict[str, list[dict]] + by_name: dict + by_path_suffix: dict + extras_prefix: str + + def _collect_emulator_extras( config: dict, emulators_dir: str, @@ -1275,11 +1459,7 @@ def _collect_emulator_extras( emu_profiles: dict | None = None, target_cores: set[str] | None = None, include_all: bool = False, - claimants: dict[tuple[str, str, str], str] | None = None, - unplaceable: list[dict] | None = None, - baseline_claims: dict[str, dict] | None = None, - absent: list[dict] | None = None, - undeclared: list[dict] | None = None, + **options: Unpack[CollectOptions], ) -> list[dict]: """Collect core requirement files from emulator profiles not in the platform pack. @@ -1313,6 +1493,12 @@ def _collect_emulator_extras( Works for ANY platform (RetroArch, Batocera, Recalbox, etc.) """ + reject_unknown("_collect_emulator_extras", options, CollectOptions.__optional_keys__) + undeclared = options.get("undeclared") + claimants = options.get("claimants") + unplaceable = options.get("unplaceable") + absent = options.get("absent") + baseline_claims = options.get("baseline_claims") profiles = ( emu_profiles if emu_profiles is not None @@ -1322,7 +1508,6 @@ def _collect_emulator_extras( # Detect destination conventions for core extras placement = ExtraPlacement(config, base_dest, profiles) extras_prefix = placement.prefix - is_slug_based = placement.slug_based if undeclared is None: undeclared = undeclared_report( @@ -1339,86 +1524,15 @@ def _collect_emulator_extras( undeclared, placement, db, bool(config.get("case_insensitive_fs", False)) ) undeclared = rank.ordered(undeclared) - extras = [] - seen_dests: set[str] = set(seen) - # Destination -> the extra that took it, to record later claimants on. - taken: dict[str, dict] = {} + state = _FirstPass( + config, placement, rank, set(seen), {}, claimants, unplaceable, absent, + ) if baseline_claims is not None: for destination in seen: - taken[destination] = baseline_claims.setdefault(destination, {}) + state.taken[destination] = baseline_claims.setdefault(destination, {}) for u in undeclared: - if u.get("bundled"): - # Installed with the emulator for this build: already on the - # user's machine. The mode a file is bundled for was settled - # upstream, an entry scoped to another build never gets here. - continue - if u.get("unplaced"): - # Read in a folder outside the BIOS tree: named, held or not, - # never written where the emulator does not read it. - if unplaceable is not None: - unplaceable.append({**u, "unplaceable": u["unplaced"]}) - continue - if not u["in_repo"] and absent is None: - continue - # For archive entries, use the archive name for resolution - archive = u.get("archive") - name = archive if archive else u["name"] - dest = _extra_dest(u) - - # Slug-based platforms: prefix dest with system slug. A file read - # below a save directory kept per system goes below each system. - placements = placement.places(u, dest) - save_root = u.get("root") == "save" - if not u["in_repo"]: - # Each core reading it is named on the omission: a list built - # without the first reader still has to say the file is missing. - for placed in placements: - for claim in (u, *u.get("other_claims", [])): - missing = _report_extra(claim, name, placed[0]) - if save_root: - _save_fields(missing, placed[1], placement) - absent.append(missing) - continue - if not placements: - if unplaceable is not None: - reason = placement.unplaced_reason(u, dest) - unplaceable.append( - u if reason == "no_platform_slug" else {**u, "unplaceable": reason} - ) - continue - if claimants is not None: - # Keyed as extra_region_key keys the extra that wins the path: a - # losing claim kept the bare path, and on RetroDECK (declared - # root bios/) verify --region listed Rustation's scph1002b.bin - # as packed while the builder had withdrawn bios/scph1002b.bin. - claimants[(u.get("emulator", ""), u.get("name", ""), u.get("path") or "")] = ( - prefixed_destination( - sanitize_pack_path(placements[0][0]), declared_root(config) - ) - ) - for dest, full_dest in placements: - candidates = [ - _report_extra(c, name, dest) for c in (u, *u.get("other_claims", [])) - ] - if save_root: - for item in candidates: - _save_fields(item, full_dest, placement) - # Where the builder meets each claim: the strongest proof first, the - # report's profile order between equals, archives after loose files. - for item in candidates: - item["claim_order"] = ( - 1, 1 if u.get("archive") else 0, -rank.of_extra(item, full_dest), - item["source_profile"], - ) - candidates.sort(key=lambda item: item["claim_order"]) - extra, claims = candidates[0], candidates[1:] - if not _take(extra, full_dest, seen_dests, taken): - for claim in claims: - _another_claim(taken.get(full_dest), claim) - continue - for claim in claims: - _another_claim(extra, claim) - extras.append(extra) + _place_report_entry(state, u) + extras = state.extras # Second pass: find alternative destinations for files already in the pack. # A file declared by the platform or emitted above may also be needed at a @@ -1428,13 +1542,12 @@ def _collect_emulator_extras( # # Skip for slug-based platforms (RomM): alternative paths don't map to # the required {platform_slug}/{file} structure. - if is_slug_based: + if placement.slug_based: return extras relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) standalone_set = platform_standalone_set(config) by_name = db.get("indexes", {}).get("by_name", {}) - by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {}) # Build set of filenames already covered (platform baseline + first pass extras) # Enriched with canonical names from DB via MD5 (handles platform renaming) @@ -1444,7 +1557,11 @@ def _collect_emulator_extras( covered_names.add(e["name"]) # Destination -> the copies cores ask for there, in profile order. - copied: dict[str, list[dict]] = {} + scope = _CopyScope( + config.get("_key", ""), covered_names, platform_names, seen, state.seen_dests, + state.taken, {}, by_name, db.get("indexes", {}).get("by_path_suffix", {}), + extras_prefix, + ) for emu_name, profile in sorted(profiles.items()): if profile.get("type") in ("launcher", "alias"): continue @@ -1452,105 +1569,9 @@ def _collect_emulator_extras( continue for layout, is_standalone in platform_layouts(emu_name, profile, standalone_set): for f in layout.get("files", []): - fname = f.get("name", "") - if not fname: - continue - # Only duplicate files already covered at another destination. - # An unsourceable entry is a file no collection holds: the name - # covered elsewhere belongs to another program's file. - # Nor is one placed outside the BIOS tree by the layout. - if (fname not in covered_names or f.get("unsourceable") or f.get("unplaced") - or f.get("root") in OUTER_ROOTS): - continue - # Installed with the emulator or by the platform's package, - # as the first pass already decided for the same entry. - if not deliverable([f], is_standalone, config.get("_key", "")): - continue - # A member of an archive is read inside it, never as a loose - # file. The archive itself is placed by the passes above. - if f.get("archive"): - continue - # No path: the core reads it from nowhere a pack reaches - # (Dolphin's codehandler.bin ships in its Sys tree). - if "path" in f and f["path"] is None: - continue - file_mode = f.get("mode") - if file_mode == "standalone" and not is_standalone: - continue - if file_mode == "libretro" and is_standalone: - continue - if not read_from_system_dir(f, is_standalone): - continue - if is_standalone: - raw = f.get("standalone_path") or f.get("path") or fname - else: - raw = system_dir_path(f, f.get("path") or fname) - dest = f"{raw}{fname}" if raw.endswith("/") else raw - # A bare name is a destination too: the core reads it at the root - # of the directory core files go to, which the platform may not - # declare (Recalbox has its System Cards under pcenginecd/ only, - # geargrafx reads them from the root). - # A path of the install tree outside the BIOS folder keeps no - # prefix: EmuELEC's dolphin/dolphin-emu/GBA/gba_bios.bin. - full_dest = ( - sanitize_pack_path(dest) if f.get("unprefixed") - else prefixed_destination(dest, extras_prefix) - ) - if full_dest in seen_dests and full_dest not in taken: - continue - if (full_dest in taken or full_dest in copied) and full_dest not in seen \ - and fname not in platform_names: - # Another core's extra holds this path and only that - # extra covers the name: a pack without that core never - # reaches this copy, so this core claims nothing here. - # Batocera's launcher hands DuckStation one named BIOS; - # recorded on duckstation-legacy's scph100.bin, its claim - # kept the file for a target without legacy. - continue - # Only files the database indexes: members of a data - # directory are not in it and are not duplicated here. - if not ( - by_name.get(fname) - or by_name.get(dest.rsplit("/", 1)[-1]) - or by_path_suffix.get(dest) - ): - continue - extra = { - "name": fname, - "destination": dest, - "required": f.get("required", False), - "hle_fallback": f.get("hle_fallback", False), - "source_emulator": layout.get("emulator", emu_name), - "source_profile": emu_name, - # The key the gap report gives the same entry. - "source_name": fname, - "source_path": raw, - "category": f.get("category", "bios"), - "source_system": f.get("system"), - "source_systems": entry_system_ids(f, layout), - "region": f.get("region"), - "selection_slot": f.get("selection_slot"), - **set_fields(f, layout), - } - # The same identity the first pass carries: without it the copy - # resolves on its name alone and a same-named file of another - # game fills the slot the profile marks as not held. - for identity in PROFILE_IDENTITY_FIELDS: - if f.get(identity) not in (None, "", []): - extra[identity] = f[identity] - if f.get("contents"): - extra["contents"] = f["contents"] - if f.get("system_dir"): - extra["system_dir"] = f["system_dir"] - if f.get("unprefixed"): - extra["unprefixed"] = True - # A copy placed outside the BIOS tree resolves by its layout - # path alone, as the first pass does: EmuELEC's - # roms/mame/stvbios.zip took bios/Arcade/MAME's set by that tail. - if f.get("layout_path"): - extra["layout_path"] = f["layout_path"] - extra["claim_order"] = (2, 0, emu_name) - copied.setdefault(full_dest, []).append(extra) + copy = _second_pass_copy(scope, emu_name, layout, is_standalone, f) + if copy is not None: + scope.copied.setdefault(copy[0], []).append(copy[1]) # Several cores reading one archive in one roms folder: the copy of the # core the folder starts by default goes first, then the copy serving @@ -1558,31 +1579,236 @@ def _collect_emulator_extras( # neogeo.zip there, and the copy holding the 18 members its default # MAME 2003-Plus requires also holds the 3 MAME 2000 requires. defaults = _folder_defaults(config, profiles) - for full_dest, claims in copied.items(): + for full_dest, claims in scope.copied.items(): if len(claims) > 1: claims = sorted(claims, key=lambda c: ( not _starts_by_default(c, defaults), -_copy_serves(c, claims, db), )) - for extra in claims: - if _take(extra, full_dest, seen_dests, taken): - extras.append(extra) + extras.extend( + extra for extra in claims + if _take(extra, full_dest, state.seen_dests, state.taken) + ) extras.extend( _archive_prefix_extras( - profiles, relevant, covered_names, seen_dests, extras_prefix, - by_name, taken, standalone_set, + profiles, relevant, covered_names, state.seen_dests, extras_prefix, + by_name, state.taken, standalone_set, ) ) extras.extend( _agnostic_scan_extras( - profiles, relevant, db, by_name, seen_dests, extras_prefix, - standalone_set, taken, + profiles, relevant, db, by_name, state.seen_dests, extras_prefix, + standalone_set, state.taken, ) ) return extras + +def _place_report_entry(state: _FirstPass, u: dict) -> None: + """First pass: place one gap report entry, or record why it is not.""" + if u.get("bundled"): + # Installed with the emulator for this build: already on the + # user's machine. The mode a file is bundled for was settled + # upstream, an entry scoped to another build never gets here. + return + if u.get("unplaced"): + # Read in a folder outside the BIOS tree: named, held or not, + # never written where the emulator does not read it. + if state.unplaceable is not None: + state.unplaceable.append({**u, "unplaceable": u["unplaced"]}) + return + absent = state.absent + if not u["in_repo"] and absent is None: + return + # For archive entries, use the archive name for resolution + archive = u.get("archive") + name = archive if archive else u["name"] + dest = _extra_dest(u) + + # Slug-based platforms: prefix dest with system slug. A file read + # below a save directory kept per system goes below each system. + placement = state.placement + placements = placement.places(u, dest) + save_root = u.get("root") == "save" + if not u["in_repo"]: + # Each core reading it is named on the omission: a list built + # without the first reader still has to say the file is missing. + if absent is not None: + for placed in placements: + for claim in (u, *u.get("other_claims", [])): + missing = _report_extra(claim, name, placed[0]) + if save_root: + _save_fields(missing, placed[1], placement) + absent.append(missing) + return + if not placements: + if state.unplaceable is not None: + reason = placement.unplaced_reason(u, dest) + state.unplaceable.append( + u if reason == "no_platform_slug" else {**u, "unplaceable": reason} + ) + return + if state.claimants is not None: + # Keyed as extra_region_key keys the extra that wins the path: a + # losing claim kept the bare path, and on RetroDECK (declared + # root bios/) verify --region listed Rustation's scph1002b.bin + # as packed while the builder had withdrawn bios/scph1002b.bin. + state.claimants[(u.get("emulator", ""), u.get("name", ""), u.get("path") or "")] = ( + prefixed_destination( + sanitize_pack_path(placements[0][0]), declared_root(state.config) + ) + ) + for dest, full_dest in placements: + _claim_placement(state, u, name, dest, full_dest, save_root) + + +def _claim_placement( + state: _FirstPass, u: dict, name: str, dest: str, full_dest: str, save_root: bool, +) -> None: + """Race the entry's claims for one of its destinations.""" + candidates = [ + _report_extra(c, name, dest) for c in (u, *u.get("other_claims", [])) + ] + if save_root: + for item in candidates: + _save_fields(item, full_dest, state.placement) + # Where the builder meets each claim: the strongest proof first, the + # report's profile order between equals, archives after loose files. + for item in candidates: + item["claim_order"] = ( + 1, 1 if u.get("archive") else 0, -state.rank.of_extra(item, full_dest), + item["source_profile"], + ) + candidates.sort(key=lambda item: item["claim_order"]) + extra, claims = candidates[0], candidates[1:] + if not _take(extra, full_dest, state.seen_dests, state.taken): + for claim in claims: + _another_claim(state.taken.get(full_dest), claim) + return + for claim in claims: + _another_claim(extra, claim) + state.extras.append(extra) + + +def _copies_entry(f: dict, is_standalone: bool, scope: _CopyScope) -> bool: + """Whether the second pass may copy this layout entry to its own path.""" + fname = f.get("name", "") + if not fname: + return False + # Only duplicate files already covered at another destination. + # An unsourceable entry is a file no collection holds: the name + # covered elsewhere belongs to another program's file. + # Nor is one placed outside the BIOS tree by the layout. + if (fname not in scope.covered_names or f.get("unsourceable") or f.get("unplaced") + or f.get("root") in OUTER_ROOTS): + return False + # Installed with the emulator or by the platform's package, + # as the first pass already decided for the same entry. + if not deliverable([f], is_standalone, scope.config_key): + return False + # A member of an archive is read inside it, never as a loose + # file. The archive itself is placed by the passes above. + if f.get("archive"): + return False + # No path: the core reads it from nowhere a pack reaches + # (Dolphin's codehandler.bin ships in its Sys tree). + if "path" in f and f["path"] is None: + return False + file_mode = f.get("mode") + if file_mode == "standalone" and not is_standalone: + return False + if file_mode == "libretro" and is_standalone: + return False + return read_from_system_dir(f, is_standalone) + + +def _second_pass_copy( + scope: _CopyScope, emu_name: str, layout: dict, is_standalone: bool, f: dict, +) -> tuple[str, dict] | None: + """(full destination, extra) of a covered file this core reads elsewhere.""" + if not _copies_entry(f, is_standalone, scope): + return None + fname = f.get("name", "") + if is_standalone: + raw = f.get("standalone_path") or f.get("path") or fname + else: + raw = system_dir_path(f, f.get("path") or fname) + dest = f"{raw}{fname}" if raw.endswith("/") else raw + # A bare name is a destination too: the core reads it at the root + # of the directory core files go to, which the platform may not + # declare (Recalbox has its System Cards under pcenginecd/ only, + # geargrafx reads them from the root). + # A path of the install tree outside the BIOS folder keeps no + # prefix: EmuELEC's dolphin/dolphin-emu/GBA/gba_bios.bin. + full_dest = ( + sanitize_pack_path(dest) if f.get("unprefixed") + else prefixed_destination(dest, scope.extras_prefix) + ) + if full_dest in scope.seen_dests and full_dest not in scope.taken: + return None + if (full_dest in scope.taken or full_dest in scope.copied) and full_dest not in scope.seen \ + and fname not in scope.platform_names: + # Another core's extra holds this path and only that + # extra covers the name: a pack without that core never + # reaches this copy, so this core claims nothing here. + # Batocera's launcher hands DuckStation one named BIOS; + # recorded on duckstation-legacy's scph100.bin, its claim + # kept the file for a target without legacy. + return None + # Only files the database indexes: members of a data + # directory are not in it and are not duplicated here. + if not ( + scope.by_name.get(fname) + or scope.by_name.get(dest.rsplit("/", 1)[-1]) + or scope.by_path_suffix.get(dest) + ): + return None + return full_dest, _copy_extra(f, layout, emu_name, dest, raw) + + +def _copy_extra(f: dict, layout: dict, emu_name: str, dest: str, raw: str) -> dict: + """The extra the second pass emits for a copy.""" + fname = f.get("name", "") + extra = { + "name": fname, + "destination": dest, + "required": f.get("required", False), + "hle_fallback": f.get("hle_fallback", False), + "source_emulator": layout.get("emulator", emu_name), + "source_profile": emu_name, + # The key the gap report gives the same entry. + "source_name": fname, + "source_path": raw, + "category": f.get("category", "bios"), + "source_system": f.get("system"), + "source_systems": entry_system_ids(f, layout), + "region": f.get("region"), + "selection_slot": f.get("selection_slot"), + **set_fields(f, layout), + } + # The same identity the first pass carries: without it the copy + # resolves on its name alone and a same-named file of another + # game fills the slot the profile marks as not held. + for identity in PROFILE_IDENTITY_FIELDS: + if f.get(identity) not in (None, "", []): + extra[identity] = f[identity] + if f.get("contents"): + extra["contents"] = f["contents"] + if f.get("system_dir"): + extra["system_dir"] = f["system_dir"] + if f.get("unprefixed"): + extra["unprefixed"] = True + # A copy placed outside the BIOS tree resolves by its layout + # path alone, as the first pass does: EmuELEC's + # roms/mame/stvbios.zip took bios/Arcade/MAME's set by that tail. + if f.get("layout_path"): + extra["layout_path"] = f["layout_path"] + extra["claim_order"] = (2, 0, emu_name) + return extra + + class _ClaimRanks: """How strongly each claim on a contested destination proves its file. @@ -1908,6 +2134,19 @@ def _ships( )[1] is None +class RegionGroupOptions(TypedDict, total=False): + """What platform_region_groups reads besides the platform, and fills.""" + + include_all: bool + required_only: bool + extras_out: list[dict] | None + held_out: set[str] | None + undeclared: list[dict] | None + zip_contents: dict | None + data_registry: dict | None + slot_overrides: dict[str, str] | None + + def platform_region_groups( config: dict, systems: dict, @@ -1918,14 +2157,7 @@ def platform_region_groups( *, target_cores: set[str] | None = None, include_extras: bool = True, - include_all: bool = False, - required_only: bool = False, - extras_out: list[dict] | None = None, - held_out: set[str] | None = None, - undeclared: list[dict] | None = None, - zip_contents: dict | None = None, - data_registry: dict | None = None, - slot_overrides: dict[str, str] | None = None, + **options: Unpack[RegionGroupOptions], ) -> tuple[dict[str, list[tuple[str, str]]], dict[tuple[str, str, str], str]]: """Group a platform's pack candidates the way region filtering reads them. @@ -1944,6 +2176,15 @@ def platform_region_groups( and ``slot_overrides`` (keyed by full pack destination) are the ones the builder resolves with, so a held declaration is the one the pack ships. """ + reject_unknown("platform_region_groups", options, RegionGroupOptions.__optional_keys__) + include_all = options.get("include_all", False) + undeclared = options.get("undeclared") + required_only = options.get("required_only", False) + held_out = options.get("held_out") + extras_out = options.get("extras_out") + zip_contents = options.get("zip_contents") + data_registry = options.get("data_registry") + slot_overrides = options.get("slot_overrides") groups: dict[str, list[tuple[str, str]]] = {} for sys_id, system in systems.items(): members = groups.setdefault(sys_id, []) @@ -2096,7 +2337,7 @@ def emulator_region_drops( region_groups.setdefault(group_id, []).append( (dest, fe.get("name", "")) ) - if held is not None and _emulator_ships( + if held is not None and db is not None and _emulator_ships( fe, emu_name, profile, db, validation_index, zip_contents, data_registry, ): @@ -2104,6 +2345,10 @@ def emulator_region_drops( return region_mod.resolve_region_drops(region_groups, region_index, regions, held) +class SpareOptions(TypedDict, total=False): + data_registry: dict | None + + def emulator_required_spares( emu_name: str, profile: dict, @@ -2113,7 +2358,7 @@ def emulator_required_spares( db: dict, validation_index: dict, zip_contents: dict | None, - data_registry: dict | None, + **options: Unpack[SpareOptions], ) -> set[str]: """The destinations an emulator --required-only pack leaves out: of each required set, one held member stays, the first the code loads among @@ -2124,6 +2369,8 @@ def emulator_required_spares( from common import archive_entry from packpaths import _archive_destination, _resolve_destination + reject_unknown("emulator_required_spares", options, SpareOptions.__optional_keys__) + data_registry = options.get("data_registry") candidates: list[dict] = [] archives: list[str] = [] for fe in files: @@ -2136,9 +2383,10 @@ def emulator_required_spares( archive, profile.get("archive_prefix", ""), profile.get("pack_structure"), standalone, ), "entry": own}) - for fe in files: - if not fe.get("archive") and groups_of(fe): - candidates.append({"dest": _resolve_destination(fe, standalone), "entry": fe}) + candidates.extend( + {"dest": _resolve_destination(fe, standalone), "entry": fe} + for fe in files if not fe.get("archive") and groups_of(fe) + ) if not candidates: return set() spares = required_only_spares( diff --git a/scripts/packpaths.py b/scripts/packpaths.py index c7b953432..045417a45 100644 --- a/scripts/packpaths.py +++ b/scripts/packpaths.py @@ -161,9 +161,7 @@ def _has_path_conflict(dest: str, seen_files: set[str], seen_parents: set[str]) for parent in _path_parents(dest): if parent in seen_files: return True - if dest in seen_parents: - return True - return False + return dest in seen_parents def placement_block( dest: str, diff --git a/scripts/packreadme.py b/scripts/packreadme.py index 7b3aea729..7a0716a09 100644 --- a/scripts/packreadme.py +++ b/scripts/packreadme.py @@ -5,9 +5,16 @@ goes, and which ones the user has to rename.""" from __future__ import annotations +from typing import TYPE_CHECKING, TypedDict + +from packextras import reject_unknown from region import label as region_label from siteguides import INSTALL_PS1, INSTALL_SH, pack_manual +if TYPE_CHECKING: + from typing_extensions import Unpack + + def _detect_systems(detect: list[dict]) -> list[str]: """The operating systems the registry's detection rules cover, in order.""" order = ("linux", "darwin", "windows") @@ -187,27 +194,33 @@ def _save_section( return "\n".join(lines) + "\n\n" +class ReadmeOptions(TypedDict, total=False): + """What a pack's README states besides its platform and its counts.""" + + source: str + contributors: list[dict] | None + regions: list[str] | None + fallback_systems: list[str] | None + one_per_slot: bool + undecidable_slots: list[str] | None + narrowings: list[tuple[str, str]] | None + system_filter: list[str] | None + detect: list[dict] | None + standalone_copies: list[dict] | None + launch_folders: int + save_folder: str + save_where: str + save_by_system: bool + case_twins: list[tuple[str, str]] | None + + def _build_readme( platform_name: str, platform_display: str, base_dest: str, total_files: int, num_systems: int, - source: str = "full", - contributors: list[dict] | None = None, - regions: list[str] | None = None, - fallback_systems: list[str] | None = None, - one_per_slot: bool = False, - undecidable_slots: list[str] | None = None, - narrowings: list[tuple[str, str]] | None = None, - system_filter: list[str] | None = None, - detect: list[dict] | None = None, - standalone_copies: list[dict] | None = None, - launch_folders: int = 0, - save_folder: str = "", - save_where: str = "", - save_by_system: bool = False, - case_twins: list[tuple[str, str]] | None = None, + **options: Unpack[ReadmeOptions], ) -> str: """Build a personalized step-by-step README for each platform pack. @@ -222,7 +235,9 @@ def _build_readme( where names keep their case (EmuDeck and RetroArch on Linux), where the core asking for the other spelling finds nothing. """ - narrowings = narrowings or [] + reject_unknown("_build_readme", options, ReadmeOptions.__optional_keys__) + regions = options.get("regions") + launch_folders = options.get("launch_folders", 0) sep = "=" * 50 scope = ( f"{launch_folders} launch folders" if launch_folders and not num_systems @@ -235,40 +250,7 @@ def _build_readme( f"{sep}\n\n" ) - detect = list(detect or []) - bios_paths = [str(rule.get("bios_path", "")) for rule in detect] - if any(rule.get("method") == "card_marker" for rule in detect): - guide = ( - "INSTALLATION GUIDE\n\n" - + _card_section(platform_name, platform_display) - + _card_manual(platform_display) - ) - else: - guide = ( - "INSTALLATION GUIDE\n\n" - + _automatic_section(platform_name, platform_display, detect, standalone_copies) - + (pack_manual(platform_name) or _generic_manual(bios_paths)) - ) - - if case_twins: - listed = "".join( - f" {missing} (the pack has {held})\n" for missing, held in case_twins - ) - guide += ( - "NAMES THAT DIFFER ONLY BY CASE\n\n" - " Some cores open the same file under another spelling. This\n" - " pack holds one spelling of each, all Windows and macOS can\n" - " store in one folder. Linux, SteamOS and Android keep both:\n" - " there, run the installer, which adds these spellings, or\n" - " copy each file under the name below.\n\n" - f"{listed}\n" - ) - - if save_folder: - guide += _save_section( - platform_display, save_folder, save_where, save_by_system, - in_frontend_settings=not save_by_system, in_place=not base_dest, - ) + guide = _install_guide(platform_name, platform_display, base_dest, options) if regions: region_help = ( @@ -292,83 +274,158 @@ def _build_readme( f"{sep}\n" ) - source_info = "" - if source == "platform": - source_info = ( - "PACK TYPE: Platform Only\n\n" - f" This pack contains only files declared by {platform_display}.\n" - " Core extras from emulator profiles are not included.\n" - " Use the Full pack for maximum coverage.\n\n" - ) - elif source == "truth": - source_info = ( - "PACK TYPE: Ground Truth\n\n" - " This pack contains files that emulators actually load,\n" - " based on source code analysis of emulator profiles.\n" - " Independent of platform scraper accuracy.\n\n" - ) - - region_info = "" - if regions: - pretty = ", ".join(region_label(slug) for slug in regions) - region_info = ( - "PACK TYPE: Region Filtered\n\n" - f" Region priority: {pretty}\n\n" - " Only the best-matching BIOS was kept for each system.\n" - ) - if fallback_systems: - listed = "\n".join(f" {_group_label(s)}" for s in fallback_systems) - region_info += ( - "\n These systems have no BIOS in those regions, so every\n" - " BIOS file for them was kept:\n" - f"{listed}\n" - ) - region_info += ( - "\n This shrinks the pack. It does not change how cores pick\n" - " a BIOS: most already select per region from fixed filename\n" - " lists driven by the game's region. Loading imports from\n" - " another region may need the unfiltered pack.\n\n" - ) - - slot_info = "" - if one_per_slot: - slot_info = ( - " Where a core declares which BIOS it prefers, only that one was\n" - " kept for each system and region. Systems whose cores declare no\n" - " order keep every BIOS file.\n" - ) - if undecidable_slots: - slot_info += ( - f" {len(undecidable_slots)} slot(s) had no declared order.\n" - ) - slot_info += "\n" - - narrowed = "" - labels = [label for _tag, label in narrowings] - if system_filter: - labels.append(f"systems {', '.join(system_filter)}") - if labels: - listed = "".join(f" {label}\n" for label in labels) - narrowed = ( - "PACK TYPE: Narrowed\n\n" - " This pack holds fewer files than the full one:\n" - f"{listed}" - "\n The unfiltered pack is the one to use when in doubt.\n\n" - ) - - credits = "" - if contributors: - credits = "\nCONTRIBUTORS\n\n" - for cb in contributors: - username = cb.get("username", "") - credits += f" @{username}\n" - credits += "\n" + source_info = _source_info(options.get("source", "full"), platform_display) + region_info = _region_info(regions, options.get("fallback_systems")) + slot_info = _slot_info( + options.get("one_per_slot", False), options.get("undecidable_slots") + ) + narrowed = _narrowed_info( + options.get("narrowings") or [], options.get("system_filter") + ) + credits = _credits(options.get("contributors")) return ( header + narrowed + source_info + region_info + slot_info + guide + credits + footer ) + +def _install_guide( + platform_name: str, platform_display: str, base_dest: str, options: ReadmeOptions +) -> str: + """The installation steps, the case twins and the save folder.""" + detect = list(options.get("detect") or []) + bios_paths = [str(rule.get("bios_path", "")) for rule in detect] + if any(rule.get("method") == "card_marker" for rule in detect): + guide = ( + "INSTALLATION GUIDE\n\n" + + _card_section(platform_name, platform_display) + + _card_manual(platform_display) + ) + else: + guide = ( + "INSTALLATION GUIDE\n\n" + + _automatic_section( + platform_name, platform_display, detect, options.get("standalone_copies") + ) + + (pack_manual(platform_name) or _generic_manual(bios_paths)) + ) + + case_twins = options.get("case_twins") + if case_twins: + listed = "".join( + f" {missing} (the pack has {held})\n" for missing, held in case_twins + ) + guide += ( + "NAMES THAT DIFFER ONLY BY CASE\n\n" + " Some cores open the same file under another spelling. This\n" + " pack holds one spelling of each, all Windows and macOS can\n" + " store in one folder. Linux, SteamOS and Android keep both:\n" + " there, run the installer, which adds these spellings, or\n" + " copy each file under the name below.\n\n" + f"{listed}\n" + ) + + save_folder = options.get("save_folder", "") + if save_folder: + save_by_system = options.get("save_by_system", False) + guide += _save_section( + platform_display, save_folder, options.get("save_where", ""), save_by_system, + in_frontend_settings=not save_by_system, in_place=not base_dest, + ) + return guide + + +def _source_info(source: str, platform_display: str) -> str: + """The PACK TYPE block of a platform-only or ground-truth pack.""" + if source == "platform": + return ( + "PACK TYPE: Platform Only\n\n" + f" This pack contains only files declared by {platform_display}.\n" + " Core extras from emulator profiles are not included.\n" + " Use the Full pack for maximum coverage.\n\n" + ) + if source == "truth": + return ( + "PACK TYPE: Ground Truth\n\n" + " This pack contains files that emulators actually load,\n" + " based on source code analysis of emulator profiles.\n" + " Independent of platform scraper accuracy.\n\n" + ) + return "" + + +def _region_info(regions: list[str] | None, fallback_systems: list[str] | None) -> str: + """The PACK TYPE block of a region-filtered pack.""" + if not regions: + return "" + pretty = ", ".join(region_label(slug) for slug in regions) + region_info = ( + "PACK TYPE: Region Filtered\n\n" + f" Region priority: {pretty}\n\n" + " Only the best-matching BIOS was kept for each system.\n" + ) + if fallback_systems: + listed = "\n".join(f" {_group_label(s)}" for s in fallback_systems) + region_info += ( + "\n These systems have no BIOS in those regions, so every\n" + " BIOS file for them was kept:\n" + f"{listed}\n" + ) + region_info += ( + "\n This shrinks the pack. It does not change how cores pick\n" + " a BIOS: most already select per region from fixed filename\n" + " lists driven by the game's region. Loading imports from\n" + " another region may need the unfiltered pack.\n\n" + ) + return region_info + + +def _slot_info(one_per_slot: bool, undecidable_slots: list[str] | None) -> str: + """What --one-per-slot kept.""" + if not one_per_slot: + return "" + slot_info = ( + " Where a core declares which BIOS it prefers, only that one was\n" + " kept for each system and region. Systems whose cores declare no\n" + " order keep every BIOS file.\n" + ) + if undecidable_slots: + slot_info += ( + f" {len(undecidable_slots)} slot(s) had no declared order.\n" + ) + return slot_info + "\n" + + +def _narrowed_info( + narrowings: list[tuple[str, str]], system_filter: list[str] | None +) -> str: + """The PACK TYPE block of a pack holding fewer files than the full one.""" + labels = [label for _tag, label in narrowings] + if system_filter: + labels.append(f"systems {', '.join(system_filter)}") + if not labels: + return "" + listed = "".join(f" {label}\n" for label in labels) + return ( + "PACK TYPE: Narrowed\n\n" + " This pack holds fewer files than the full one:\n" + f"{listed}" + "\n The unfiltered pack is the one to use when in doubt.\n\n" + ) + + +def _credits(contributors: list[dict] | None) -> str: + """The CONTRIBUTORS block.""" + if not contributors: + return "" + credits = "\nCONTRIBUTORS\n\n" + for cb in contributors: + username = cb.get("username", "") + credits += f" @{username}\n" + return credits + "\n" + + def _build_agnostic_rename_readme( destination: str, original: str, @@ -382,8 +439,7 @@ def _build_agnostic_rename_readme( ] if alternatives: lines.append("All variants included in this pack:") - for alt in sorted(alternatives): - lines.append(f" {alt}") + lines.extend(f" {alt}" for alt in sorted(alternatives)) lines.append("") lines.append(f"To use a different variant, rename it to: {destination}") return "\n".join(lines) + "\n" diff --git a/scripts/packresolve.py b/scripts/packresolve.py index 45552b46a..8f64b55b9 100644 --- a/scripts/packresolve.py +++ b/scripts/packresolve.py @@ -283,6 +283,7 @@ def sha1_for_hash(hash_type: str, hash_val: str, db: dict) -> str | None: """The database key a looked-up hash names, or None.""" files_db = db.get("files", {}) indexes = db.get("indexes", {}) + sha1: str | None if hash_type == "sha1": sha1 = hash_val elif hash_type == "crc32": @@ -450,6 +451,53 @@ def resolve_declaration( )) +def _declarations_by_destination( + pack_systems: dict, base_dest: str, required_only: bool, +) -> dict[str, list[dict]]: + """The declarations of each full destination, in system order.""" + dest_entries: dict[str, list[dict]] = {} + for _sys_id, system in sorted(pack_systems.items()): + for file_entry in system.get("files", []): + if required_only and file_entry.get("required") is False: + continue + dest = sanitize_pack_path( + file_entry.get("destination", file_entry.get("name", "")) + ) + if not dest: + continue + full = f"{base_dest}/{dest}" if base_dest else dest + dest_entries.setdefault(full, []).append(file_entry) + return dest_entries + + +def _archive_choice( + resolved: list[tuple[dict, str | None, str]], members: list[dict], +) -> dict | None: + """The declaration whose archive the most per-ROM declarations accept.""" + # One archive declared once per ROM it must hold: the archive + # to ship is the one the most declarations accept, not the first + # that answers one of them (adam_fdc.zip: a one-member MAME set + # answered first, the eight-member set sat beside it). + def accepted(path: str | None) -> int: + if not path or not path.endswith(".zip"): + return -1 + return sum(inner_rom_check(fe, path) == "ok" for fe in members) + + fe, path, _st = max(resolved, key=lambda item: accepted(item[1])) + return fe if accepted(path) > 0 else None + + +def _hash_choice(resolved: list[tuple[dict, str | None, str]]) -> dict | None: + """The first declaration resolved by md5, else the first by any hash.""" + best = None + for fe, _lp, _st in resolved: + if _lp and _st == "md5_exact": + return fe + if best is None and _lp and resolution_is_hash_exact(_st): + best = fe + return best + + def preferred_entries( pack_systems: dict, db: dict, @@ -470,18 +518,7 @@ def preferred_entries( and could crown a declaration only a data/ cache satisfies. """ preferred_entries: dict[str, int] = {} - dest_entries: dict[str, list[dict]] = {} - for sys_id, system in sorted(pack_systems.items()): - for file_entry in system.get("files", []): - if required_only and file_entry.get("required") is False: - continue - dest = sanitize_pack_path( - file_entry.get("destination", file_entry.get("name", "")) - ) - if not dest: - continue - full = f"{base_dest}/{dest}" if base_dest else dest - dest_entries.setdefault(full, []).append(file_entry) + dest_entries = _declarations_by_destination(pack_systems, base_dest, required_only) for full, entries in dest_entries.items(): if len(entries) < 2: continue @@ -504,26 +541,11 @@ def preferred_entries( ] members = [fe for fe in entries if fe.get("zipped_file")] if members: - # One archive declared once per ROM it must hold: the archive - # to ship is the one the most declarations accept, not the first - # that answers one of them (adam_fdc.zip: a one-member MAME set - # answered first, the eight-member set sat beside it). - def accepted(path: str | None) -> int: - if not path or not path.endswith(".zip"): - return -1 - return sum(inner_rom_check(fe, path) == "ok" for fe in members) - - fe, path, _st = max(resolved, key=lambda item: accepted(item[1])) - if accepted(path) > 0: - preferred_entries[full] = id(fe) + chosen = _archive_choice(resolved, members) + if chosen is not None: + preferred_entries[full] = id(chosen) continue - best = None - for fe, _lp, _st in resolved: - if _lp and _st == "md5_exact": - best = fe - break - if best is None and _lp and resolution_is_hash_exact(_st): - best = fe + best = _hash_choice(resolved) if best is not None: preferred_entries[full] = id(best) diff --git a/scripts/packverify.py b/scripts/packverify.py index e42ab4c32..3f7e191cb 100644 --- a/scripts/packverify.py +++ b/scripts/packverify.py @@ -7,6 +7,8 @@ coverage report that disagree describe different collections.""" from __future__ import annotations from collections import Counter +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict from auto_fetch import DEFAULT_BIOS_DIR from artifacts import _build_timestamp @@ -37,7 +39,14 @@ from gamedata import without_game_data from common import resolve_platform_cores from common import sanitize_pack_path import zipfile -from collections.abc import Callable +from collections.abc import Callable, Mapping + +# Imported at run time where typing has it: a test reads the signature of +# verify_pack_against_platform with its annotations evaluated. +if sys.version_info >= (3, 11): + from typing import Unpack +elif TYPE_CHECKING: + from typing_extensions import Unpack @functools.cache @@ -121,6 +130,100 @@ def _same_members(pack: zipfile.ZipFile, name: str, source: str) -> bool: return False +def _data_indexes(data_registry: dict | None) -> tuple[dict[str, list[str]], dict[str, str]]: + """The cached data directory files by name and by relative path.""" + _data_index: dict[str, list[str]] = {} + _data_path_index: dict[str, str] = {} + if data_registry: + for _de in data_registry.values(): + cache = _de.get("local_cache", "") + if not cache or not os.path.isdir(cache): + continue + for _r, _d, _fns in os.walk(cache): + for _fn in _fns: + _fp = os.path.join(_r, _fn) + _rel = os.path.relpath(_fp, cache) + _data_path_index[_rel] = _fp + _data_index.setdefault(_fn, []).append(_fp) + return _data_index, _data_path_index + + +def _is_pack_note(name: str) -> bool: + """Whether a member is a note the builder composes, not a collected file.""" + # The builder writes its notes beside the slot they explain + # (bios/INSTRUCTIONS_x.txt, games/keen6/INSTRUCTIONS_y.txt), so + # they are told by their own name, not by a root prefix. + base = name.rsplit("/", 1)[-1] + return base.startswith(("INSTRUCTIONS_", "RENAMED_")) or base == MEDIA_MARKER or name in ( + "manifest.json", + "README.txt", + ) + + +def _member_digests(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> tuple[str, str, int]: + """(sha1, md5, size) of a pack member.""" + with zf.open(info) as f: + sha1_h = hashlib.sha1() + md5_h = hashlib.md5() + size = 0 + for chunk in iter(lambda: f.read(65536), b""): + sha1_h.update(chunk) + md5_h.update(chunk) + size += len(chunk) + return sha1_h.hexdigest(), md5_h.hexdigest(), size + + +def _rebuilt_from(zf: zipfile.ZipFile, name: str, by_name: dict, files_db: dict) -> str | None: + """The name of a held archive a rebuilt ZIP carries the members of.""" + _bn = os.path.basename(name) + for _src_sha1 in by_name.get(_bn, []): + if _src_sha1 not in files_db: + continue + _src_path = files_db[_src_sha1]["path"] + if not os.path.exists(_src_path): + continue + if _same_members(zf, name, _src_path): + return _bn + return None + + +def _cached_as( + zf: zipfile.ZipFile, + name: str, + size: int, + sha1: str, + data_indexes: tuple[dict[str, list[str]], dict[str, str]], +) -> str | None: + """The name of the data directory file a member is, or None.""" + _data_index, _data_path_index = data_indexes + _bn = os.path.basename(name) + _pr = name + for _known_prefix in ("system/", "bios/", "BIOS/", "Firmware/"): + if name.startswith(_known_prefix): + _pr = name[len(_known_prefix):] + break + _cands = [] + if _pr in _data_path_index: + _cands.append(_data_path_index[_pr]) + for _dp in _data_index.get(_bn, []): + if _dp not in _cands: + _cands.append(_dp) + for _dp in _cands: + if not os.path.exists(_dp): + continue + # The content, not the size: a member written corrupt + # keeps its length, and a same-sized homonym from another + # cache is another file. + if os.path.getsize(_dp) == size and _file_sha1(_dp) == sha1: + return _bn + if ( + name.endswith(".zip") and _dp.endswith(".zip") + and _same_members(zf, name, _dp) + ): + return _bn + return None + + def verify_pack( zip_path: str, db: dict, data_registry: dict | None = None ) -> tuple[bool, dict]: @@ -138,53 +241,23 @@ def verify_pack( by_name = db.get("indexes", {}).get("by_name", {}) # name -> [SHA1] # Data directory file index - _data_index: dict[str, list[str]] = {} - _data_path_index: dict[str, str] = {} - if data_registry: - for _dk, _de in data_registry.items(): - cache = _de.get("local_cache", "") - if not cache or not os.path.isdir(cache): - continue - for _r, _d, _fns in os.walk(cache): - for _fn in _fns: - _fp = os.path.join(_r, _fn) - _rel = os.path.relpath(_fp, cache) - _data_path_index[_rel] = _fp - _data_index.setdefault(_fn, []).append(_fp) + data_indexes = _data_indexes(data_registry) - manifest = { + manifest: dict = { "schema_version": 1, "version": 1, "generator": "retrobios generate_pack.py", "generated": _build_timestamp(db), "files": [], } - errors = [] + errors: list[str] = [] with zipfile.ZipFile(zip_path, "r") as zf: for info in zf.infolist(): - if info.is_dir(): + if info.is_dir() or _is_pack_note(info.filename): continue name = info.filename - # The builder writes its notes beside the slot they explain - # (bios/INSTRUCTIONS_x.txt, games/keen6/INSTRUCTIONS_y.txt), so - # they are told by their own name, not by a root prefix. - base = name.rsplit("/", 1)[-1] - if base.startswith(("INSTRUCTIONS_", "RENAMED_")) or base == MEDIA_MARKER or name in ( - "manifest.json", - "README.txt", - ): - continue - with zf.open(info) as f: - sha1_h = hashlib.sha1() - md5_h = hashlib.md5() - size = 0 - for chunk in iter(lambda: f.read(65536), b""): - sha1_h.update(chunk) - md5_h.update(chunk) - size += len(chunk) - sha1 = sha1_h.hexdigest() - md5 = md5_h.hexdigest() + sha1, md5, size = _member_digests(zf, info) # Look up in database: files_db keyed by SHA1 db_entry = files_db.get(sha1) @@ -195,61 +268,26 @@ def verify_pack( else: # Try MD5 -> SHA1 lookup ref_sha1 = by_md5.get(md5) - if ref_sha1: - db_entry = files_db.get(ref_sha1) - if db_entry: - file_name = db_entry.get("name", "") - status = "verified_md5" - else: - status = "untracked" + db_entry = files_db.get(ref_sha1) if ref_sha1 else None + if db_entry: + file_name = db_entry.get("name", "") + status = "verified_md5" else: status = "untracked" # Rebuilt ZIP: verify inner ROM CRC32s match source if status == "untracked" and name.endswith(".zip"): - _bn = os.path.basename(name) - for _src_sha1 in by_name.get(_bn, []): - if _src_sha1 not in files_db: - continue - _src_path = files_db[_src_sha1]["path"] - if not os.path.exists(_src_path): - continue - if _same_members(zf, name, _src_path): - status = "verified_rebuild" - file_name = _bn - break + rebuilt = _rebuilt_from(zf, name, by_name, files_db) + if rebuilt: + status = "verified_rebuild" + file_name = rebuilt # Data directory: check against cached files - if status == "untracked" and _data_index: - _bn = os.path.basename(name) - _pr = name - for _known_prefix in ("system/", "bios/", "BIOS/", "Firmware/"): - if name.startswith(_known_prefix): - _pr = name[len(_known_prefix):] - break - _cands = [] - if _pr in _data_path_index: - _cands.append(_data_path_index[_pr]) - for _dp in _data_index.get(_bn, []): - if _dp not in _cands: - _cands.append(_dp) - for _dp in _cands: - if not os.path.exists(_dp): - continue - # The content, not the size: a member written corrupt - # keeps its length, and a same-sized homonym from another - # cache is another file. - if os.path.getsize(_dp) == size and _file_sha1(_dp) == sha1: - status = "verified_data" - file_name = _bn - break - if ( - name.endswith(".zip") and _dp.endswith(".zip") - and _same_members(zf, name, _dp) - ): - status = "verified_data" - file_name = _bn - break + if status == "untracked" and data_indexes[0]: + cached = _cached_as(zf, name, size, sha1, data_indexes) + if cached: + status = "verified_data" + file_name = cached status, file_name = _settle_untracked( status, name, zf, by_md5, held_inside, errors, file_name @@ -374,8 +412,8 @@ def _check_member_hash( for h in digests.values(): h.update(chunk) crc = zlib.crc32(chunk, crc) - actual = {name: h.hexdigest() for name, h in digests.items()} - actual["crc32"] = format(crc & 0xFFFFFFFF, "08x") + computed = {name: h.hexdigest() for name, h in digests.items()} + computed["crc32"] = format(crc & 0xFFFFFFFF, "08x") def composite() -> str | None: # Recalbox's Md5Composite, over the sorted members of a ZIP. @@ -390,10 +428,10 @@ def _check_member_hash( return None if digest_verdict( - file_entry, zf.getinfo(member).file_size, lambda: actual, mode, rule, composite + file_entry, zf.getinfo(member).file_size, lambda: computed, mode, rule, composite ): return None - return f"{member}: {mode} {actual[mode]} != declared {declared}" + return f"{member}: {mode} {computed[mode]} != declared {declared}" def _repo_satisfies_declaration( entries: list[dict], db: dict, mode: str @@ -534,13 +572,14 @@ def _structural_errors(zf: zipfile.ZipFile, zip_set: set) -> list[str]: errors.append(f"path traversal: {n}") # Zero-byte check (exclude Dolphin GraphicMods markers) - for info in zf.infolist(): - if info.file_size == 0 and not info.is_dir(): - if "GraphicMods" not in info.filename and info.filename not in ( - "manifest.json", - "README.txt", - ) and info.filename.rsplit("/", 1)[-1] != MEDIA_MARKER: - errors.append(f"zero-byte: {info.filename}") + errors.extend( + f"zero-byte: {info.filename}" + for info in zf.infolist() + if info.file_size == 0 and not info.is_dir() + and "GraphicMods" not in info.filename + and info.filename not in ("manifest.json", "README.txt") + and info.filename.rsplit("/", 1)[-1] != MEDIA_MARKER + ) return errors @@ -561,20 +600,11 @@ def _shipped_copy( def _builder_extras( - config: dict, - emulators_dir: str, + expect: _Expectation, db: dict, - emu_profiles: dict, baseline_groups: dict[str, list[dict]], - base_dest: str, - is_flat: bool, - zip_set: set[str], - zip_lower: dict[str, str], - target_cores: set[str] | None, - region_drops: set[str], - data_registry: dict | None, + view: _PackView, include_all: bool = False, - required_only: bool = False, ) -> dict[str, str]: """{full destination: local copy} of each core extra the builder writes. @@ -588,15 +618,18 @@ def _builder_extras( from packextras import ExtraResolver, hidden_extras from validation import _build_validation_index, destination_owners + config, emu_profiles = expect.config, expect.emu_profiles + data_registry = expect.opts.data_registry + base_dest = expect.base_dest mode = config.get("verification_mode", "existence") hash_rule = config.get("hash_rule", "") shipped: dict[str, str | None] = {} for expected, declarations in baseline_groups.items(): - if expected not in zip_set and expected.lower() not in zip_lower: + if not view.holds(expected): continue unflat = ( f"{base_dest}/{expected}" - if is_flat and base_dest and not expected.startswith(f"{base_dest}/") + if view.is_flat and base_dest and not expected.startswith(f"{base_dest}/") else expected ) if any(fe.get("storage") in ("user_provided", "external") for fe in declarations): @@ -616,8 +649,8 @@ def _builder_extras( } placed_local: dict[str, str] = {} hidden_extras( - config, emulators_dir, db, emu_profiles, shipped, target_cores, - region_drops or None, + config, expect.opts.emulators_dir, db, emu_profiles, shipped, expect.target_cores, + expect.region_drops or None, resolver=ExtraResolver( db, DEFAULT_BIOS_DIR, build_zip_contents_index(db), data_registry, _build_validation_index(platform_profiles), @@ -625,7 +658,7 @@ def _builder_extras( ), placed_local=placed_local, include_all=include_all, - required_only=required_only, + required_only=expect.opts.required_only, ) return placed_local @@ -639,19 +672,351 @@ def _same_content(zf: zipfile.ZipFile, member: str, local: str) -> bool: return local.lower().endswith(".zip") and _same_members(zf, member, local) +class PlatformCheckOptions(TypedDict, total=False): + """The keyword options of verify_pack_against_platform.""" + + emulators_dir: str + emu_profiles: dict | None + regions: list[str] | None + data_registry: dict | None + source: str + required_only: bool + no_game_data: bool + + +@dataclass(frozen=True) +class _PlatformCheckSettings: + """PlatformCheckOptions with their defaults.""" + + emulators_dir: str = "emulators" + emu_profiles: dict | None = None + regions: list[str] | None = None + data_registry: dict | None = None + source: str = "full" + required_only: bool = False + no_game_data: bool = False + + +@dataclass(frozen=True) +class _Expectation: + """What the builder would have packed for a platform, before the pack is read.""" + + config: dict + emu_profiles: dict + expected_systems: dict + region_drops: set[str] + db: dict | None + target_cores: set[str] | None + opts: _PlatformCheckSettings + + @property + def base_dest(self) -> str: + return self.config.get("base_destination", "") + + +@dataclass(frozen=True) +class _PackView: + """A pack's member names as the checks read them.""" + + zf: zipfile.ZipFile + zip_set: set[str] + zip_lower: dict[str, str] + zip_parents: set[str] + is_flat: bool + + def holds(self, expected: str) -> bool: + return expected in self.zip_set or expected.lower() in self.zip_lower + + +@dataclass +class _BaselineCount: + """The baseline destinations checked, and what each came to.""" + + checked: int = 0 + present: int = 0 + excluded: int = 0 + absent: int = 0 + decl_by_member: dict[str, list[dict]] = field(default_factory=dict) + + +def _reject_unknown(function: str, options: Mapping[str, object], known: frozenset[str]) -> None: + """Refuse a keyword the options do not declare, as a named parameter would.""" + for key in options: + if key not in known: + raise TypeError(f"{function}() got an unexpected keyword argument '{key}'") + + +def _cut_config( + platform_name: str, + platforms_dir: str, + target_cores: set[str] | None, + opts: _PlatformCheckSettings, +) -> tuple[dict, dict]: + """The platform's config and the profiles, without game data when asked.""" + config = load_platform_config(platform_name, platforms_dir) + emu_profiles = opts.emu_profiles + if emu_profiles is None: + emu_profiles = load_emulator_profiles(opts.emulators_dir) + if opts.no_game_data: + cut = without_game_data(config, emu_profiles, opts.data_registry, target_cores) + config, emu_profiles = cut.config, cut.profiles + return config, emu_profiles + + +def _region_drops( + config: dict, + emu_profiles: dict, + expected_systems: dict, + db: dict | None, + *, + target_cores: set[str] | None, + opts: _PlatformCheckSettings, +) -> set[str]: + """The regional variants the builder leaves out, by the same selection.""" + region_drops: set[str] = set() + if not opts.regions: + return region_drops + region_index = region_mod.platform_region_index( + config, emu_profiles, target_cores + ) + held: set[str] = set() + held_zip_contents = build_zip_contents_index(db) if db is not None else {} + region_groups, _extra_dests = platform_region_groups( + config, + expected_systems, + opts.emulators_dir, + db, + config.get("base_destination", ""), + emu_profiles, + target_cores=target_cores, + include_extras=(opts.source != "platform"), + include_all=(opts.source == "truth"), + required_only=opts.required_only, + held_out=held, + zip_contents=held_zip_contents, + data_registry=opts.data_registry, + slot_overrides=slots.pack_overrides( + config, emu_profiles, db, held_zip_contents, opts.data_registry, + target_cores=target_cores, source=opts.source, + ) if db is not None else None, + ) + return region_mod.resolve_region_drops( + region_groups, region_index, opts.regions, held + ) + + +def _pack_view(zf: zipfile.ZipFile, config: dict, base_dest: str) -> _PackView: + zip_set = set(zf.namelist()) + # A case twin stands in for the file only where the platform's + # filesystem folds case, as the builder decides: on Lakka bios.col + # and BIOS.col are two files two cores open, and either one missing + # was counted present through the other. + zip_lower = ( + {n.lower(): n for n in zip_set} + if config.get("case_insensitive_fs", False) else {} + ) + + # Auto-detect flat vs nested ZIP + is_flat = bool(base_dest) and not any( + n.startswith(base_dest + "/") + for n in zip_set + if n not in ("README.txt", "manifest.json", MEDIA_MARKER) and not n.endswith("/") + ) + # Mirror the builder's path-conflict logic: a declaration whose path + # collides file-vs-directory with a packed member was skipped by the + # builder (upstream declares e.g. both SGB1.sfc and SGB1.sfc/program.rom) + zip_parents: set[str] = set() + for n in zip_set: + parts = n.split("/") + for i in range(1, len(parts)): + zip_parents.add("/".join(parts[:i])) + return _PackView(zf, zip_set, zip_lower, zip_parents, is_flat) + + +def _baseline_groups( + expect: _Expectation, is_flat: bool, +) -> tuple[dict[str, list[dict]], dict[int, str]]: + """The platform's declarations by the path they expect in the pack, and + the system of each declaration.""" + opts = expect.opts + base_dest = expect.base_dest + baseline_groups: dict[str, list[dict]] = {} + system_of: dict[int, str] = {} + for sys_id, system in (expect.expected_systems if opts.source != "truth" else {}).items(): + for fe in system.get("files", []): + system_of[id(fe)] = sys_id + if opts.required_only and fe.get("required") is False: + continue + dest = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) + if not dest: + continue + if expect.region_drops and dest in expect.region_drops: + continue + expected = f"{base_dest}/{dest}" if base_dest and not is_flat else dest + baseline_groups.setdefault(expected, []).append(fe) + return baseline_groups, system_of + + +def _count_baseline( + expect: _Expectation, + view: _PackView, + baseline_groups: dict[str, list[dict]], + system_of: dict[int, str], + errors: list[str], +) -> _BaselineCount: + """Each baseline destination present, accounted for, or missing.""" + db = expect.db + data_registry = expect.opts.data_registry + count = _BaselineCount(checked=len(baseline_groups)) + # RetroBat's group: one packed file of it is enough, as verify counts it. + packed_groups = { + (system_of[id(fe)], fe["group"]) + for expected, declarations in baseline_groups.items() + if view.holds(expected) + for fe in declarations + if fe.get("group") + } + exclusion_index = build_zip_contents_index(db) if db is not None else {} + categories = EntryCategories(expect.config, expect.emu_profiles, data_registry) + for expected, declarations in baseline_groups.items(): + if expected in view.zip_set: + member = expected + elif expected.lower() in view.zip_lower: + member = view.zip_lower[expected.lower()] + elif _has_path_conflict(expected, view.zip_set, view.zip_parents): + # Skipped by the builder for the same reason: not an error + count.present += 1 + continue + elif db is not None and _intentional_hash_exclusion( + declarations, + db, + zip_contents=exclusion_index, + data_dir_registry=data_registry, + verification_mode=expect.config.get("verification_mode", "existence"), + hash_rule=expect.config.get("hash_rule", ""), + ): + count.excluded += 1 + continue + elif all( + fe.get("group") and (system_of[id(fe)], fe["group"]) in packed_groups + for fe in declarations + ): + count.absent += 1 + continue + elif db is not None and all( + categories.category(fe, fe.get("destination", fe.get("name", "")), + system_of[id(fe)]) != BIOS + for fe in declarations + ) and _held_nowhere(declarations, db, exclusion_index, data_registry): + # A game's data or an entry no core opens that the collection + # lacks: verify counts it apart. Missing firmware stays an error. + count.absent += 1 + continue + else: + errors.append(f"baseline missing: {expected}") + continue + count.present += 1 + count.decl_by_member.setdefault(member, []).extend(declarations) + return count + + +def _native_hash_errors( + zf: zipfile.ZipFile, decl_by_member: dict[str, list[dict]], config: dict, db: dict | None, +) -> list[str]: + """The platform's native hash check replayed on the pack's bytes.""" + # Reproduce the platform's native hash check on pack bytes. + # A destination declared by several entries passes when the packed + # member satisfies any of them. A failure only counts as a pack + # error when the repo holds a file matching a declaration: without + # one, the pack ships its best effort and the gap is a data issue + # reported by verify.py, not a generation bug. + verification_mode = config.get("verification_mode", "existence") + digest = digest_algorithm(verification_mode) + hash_rule = config.get("hash_rule", "") + errors: list[str] = [] + if not (reads_file_contents(verification_mode) and digest): + return errors + for member, decl_entries in decl_by_member.items(): + checkable = [ + fe + for fe in decl_entries + if str(fe.get(digest) or "").strip() + ] + if not checkable: + continue + # An archive declared once per ROM it must hold is checked + # once per ROM by the frontend: each such declaration has to + # pass on its own, where the repository holds an archive + # that would. + for fe in checkable: + if not fe.get("zipped_file"): + continue + err = _check_member_hash(zf, member, fe, digest, hash_rule) + if err is not None and (db is None or _repo_holds_member(fe, db)): + errors.append(err) + member_errors = [] + satisfied = False + for fe in checkable: + err = _check_member_hash(zf, member, fe, digest, hash_rule) + if err is None: + satisfied = True + break + member_errors.append(err) + if satisfied: + continue + if db is None or _repo_satisfies_declaration( + checkable, db, verification_mode + ): + errors.append(member_errors[0]) + return errors + + +def _check_core_extras( + expect: _Expectation, + view: _PackView, + baseline_groups: dict[str, list[dict]], + errors: list[str], +) -> tuple[int, int]: + """(checked, present) of the core extras the builder places.""" + # 2. Core extras: the builder's own placement replayed + # (packextras.hidden_extras, which verify reads too), after the + # platform files it wrote. Each placed extra must sit at its path + # with the bytes the builder resolved: an empty seen set and a + # presence test credited a core file at a path where the pack + # holds the platform's other dump. + core_checked = 0 + core_present = 0 + opts = expect.opts + db = expect.db + if db is None or opts.source == "platform": + return core_checked, core_present + placed_local = _builder_extras( + expect, db, baseline_groups, view, include_all=(opts.source == "truth"), + ) + for full, local in sorted(placed_local.items()): + core_checked += 1 + flat = _flat(full, expect.base_dest, view.is_flat) + member = flat if flat in view.zip_set else view.zip_lower.get(flat.lower()) + if member is None: + errors.append(f"core missing: {full}") + elif not _same_content(view.zf, member, local): + errors.append( + f"core file differs: {member} is not the {os.path.basename(local)}" + " the builder places there" + ) + else: + core_present += 1 + return core_checked, core_present + + def verify_pack_against_platform( zip_path: str, platform_name: str, platforms_dir: str, db: dict | None = None, - emulators_dir: str = "emulators", - emu_profiles: dict | None = None, - regions: list[str] | None = None, - data_registry: dict | None = None, + *, target_cores: set[str] | None = None, - source: str = "full", - required_only: bool = False, - no_game_data: bool = False, + **options: Unpack[PlatformCheckOptions], ) -> tuple[bool, int, int, list[str], int, int, int, int, int, int]: """Verify a pack ZIP against its platform config and core requirements. @@ -679,19 +1044,11 @@ def verify_pack_against_platform( holds no file for that are a game's data or that no core the platform runs opens. verify.py counts them apart from firmware. """ - - config = load_platform_config(platform_name, platforms_dir) - base_dest = config.get("base_destination", "") - errors: list[str] = [] - checked = 0 - present = 0 - - if emu_profiles is None: - emu_profiles = load_emulator_profiles(emulators_dir) - if no_game_data: - cut = without_game_data(config, emu_profiles, data_registry, target_cores) - config, emu_profiles = cut.config, cut.profiles - + _reject_unknown( + "verify_pack_against_platform", options, PlatformCheckOptions.__optional_keys__ + ) + opts = _PlatformCheckSettings(**options) + config, emu_profiles = _cut_config(platform_name, platforms_dir, target_cores, opts) expected_systems = config.get("systems", {}) if target_cores is not None: expected_systems = filter_systems_by_target( @@ -700,221 +1057,35 @@ def verify_pack_against_platform( target_cores, resolve_platform_cores(config, emu_profiles), ) - - region_drops: set[str] = set() - if regions: - region_index = region_mod.platform_region_index( - config, emu_profiles, target_cores - ) - held: set[str] = set() - held_zip_contents = build_zip_contents_index(db) if db is not None else {} - region_groups, _extra_dests = platform_region_groups( - config, - expected_systems, - emulators_dir, - db, - base_dest, - emu_profiles, - target_cores=target_cores, - include_extras=(source != "platform"), - include_all=(source == "truth"), - required_only=required_only, - held_out=held, - zip_contents=held_zip_contents, - data_registry=data_registry, - slot_overrides=slots.pack_overrides( - config, emu_profiles, db, held_zip_contents, data_registry, - target_cores=target_cores, source=source, - ) if db is not None else None, - ) - region_drops = region_mod.resolve_region_drops( - region_groups, region_index, regions, held - ) + expect = _Expectation( + config, emu_profiles, expected_systems, + _region_drops( + config, emu_profiles, expected_systems, db, + target_cores=target_cores, opts=opts, + ), + db, target_cores, opts, + ) + errors: list[str] = [] with zipfile.ZipFile(zip_path, "r") as zf: - zip_set = set(zf.namelist()) - # A case twin stands in for the file only where the platform's - # filesystem folds case, as the builder decides: on Lakka bios.col - # and BIOS.col are two files two cores open, and either one missing - # was counted present through the other. - zip_lower = ( - {n.lower(): n for n in zip_set} - if config.get("case_insensitive_fs", False) else {} - ) - - # Auto-detect flat vs nested ZIP - is_flat = bool(base_dest) and not any( - n.startswith(base_dest + "/") - for n in zip_set - if n not in ("README.txt", "manifest.json", MEDIA_MARKER) and not n.endswith("/") - ) - - errors.extend(_structural_errors(zf, zip_set)) + view = _pack_view(zf, expect.config, expect.base_dest) + errors.extend(_structural_errors(zf, view.zip_set)) # 1. Baseline file presence + native hash check - verification_mode = config.get("verification_mode", "existence") - baseline_checked = 0 - baseline_present = 0 - baseline_excluded = 0 - baseline_absent = 0 - decl_by_member: dict[str, list[dict]] = {} - # Mirror the builder's path-conflict logic: a declaration whose path - # collides file-vs-directory with a packed member was skipped by the - # builder (upstream declares e.g. both SGB1.sfc and SGB1.sfc/program.rom) - zip_parents: set[str] = set() - for n in zip_set: - parts = n.split("/") - for i in range(1, len(parts)): - zip_parents.add("/".join(parts[:i])) - baseline_groups: dict[str, list[dict]] = {} - system_of: dict[int, str] = {} - for sys_id, system in (expected_systems if source != "truth" else {}).items(): - for fe in system.get("files", []): - system_of[id(fe)] = sys_id - if required_only and fe.get("required") is False: - continue - dest = sanitize_pack_path(fe.get("destination", fe.get("name", ""))) - if not dest: - continue - if region_drops and dest in region_drops: - continue - expected = f"{base_dest}/{dest}" if base_dest and not is_flat else dest - baseline_groups.setdefault(expected, []).append(fe) - - baseline_checked = len(baseline_groups) - # RetroBat's group: one packed file of it is enough, as verify counts it. - packed_groups = { - (system_of[id(fe)], fe["group"]) - for expected, declarations in baseline_groups.items() - if expected in zip_set or expected.lower() in zip_lower - for fe in declarations - if fe.get("group") - } - exclusion_index = build_zip_contents_index(db) if db is not None else {} - categories = EntryCategories(config, emu_profiles, data_registry) - for expected, declarations in baseline_groups.items(): - if expected in zip_set: - member = expected - elif expected.lower() in zip_lower: - member = zip_lower[expected.lower()] - elif _has_path_conflict(expected, zip_set, zip_parents): - # Skipped by the builder for the same reason: not an error - baseline_present += 1 - continue - elif db is not None and _intentional_hash_exclusion( - declarations, - db, - zip_contents=exclusion_index, - data_dir_registry=data_registry, - verification_mode=verification_mode, - hash_rule=config.get("hash_rule", ""), - ): - baseline_excluded += 1 - continue - elif all( - fe.get("group") and (system_of[id(fe)], fe["group"]) in packed_groups - for fe in declarations - ): - baseline_absent += 1 - continue - elif db is not None and all( - categories.category(fe, fe.get("destination", fe.get("name", "")), - system_of[id(fe)]) != BIOS - for fe in declarations - ) and _held_nowhere(declarations, db, exclusion_index, data_registry): - # A game's data or an entry no core opens that the collection - # lacks: verify counts it apart. Missing firmware stays an error. - baseline_absent += 1 - continue - else: - errors.append(f"baseline missing: {expected}") - continue - baseline_present += 1 - decl_by_member.setdefault(member, []).extend(declarations) - - # Reproduce the platform's native hash check on pack bytes. - # A destination declared by several entries passes when the packed - # member satisfies any of them. A failure only counts as a pack - # error when the repo holds a file matching a declaration: without - # one, the pack ships its best effort and the gap is a data issue - # reported by verify.py, not a generation bug. - digest = digest_algorithm(verification_mode) - hash_rule = config.get("hash_rule", "") - if reads_file_contents(verification_mode) and digest: - for member, decl_entries in decl_by_member.items(): - checkable = [ - fe - for fe in decl_entries - if str(fe.get(digest) or "").strip() - ] - if not checkable: - continue - # An archive declared once per ROM it must hold is checked - # once per ROM by the frontend: each such declaration has to - # pass on its own, where the repository holds an archive - # that would. - for fe in checkable: - if not fe.get("zipped_file"): - continue - err = _check_member_hash(zf, member, fe, digest, hash_rule) - if err is not None and (db is None or _repo_holds_member(fe, db)): - errors.append(err) - member_errors = [] - satisfied = False - for fe in checkable: - err = _check_member_hash(zf, member, fe, digest, hash_rule) - if err is None: - satisfied = True - break - member_errors.append(err) - if satisfied: - continue - if db is None or _repo_satisfies_declaration( - checkable, db, verification_mode - ): - errors.append(member_errors[0]) - - # 2. Core extras: the builder's own placement replayed - # (packextras.hidden_extras, which verify reads too), after the - # platform files it wrote. Each placed extra must sit at its path - # with the bytes the builder resolved: an empty seen set and a - # presence test credited a core file at a path where the pack - # holds the platform's other dump. - core_checked = 0 - core_present = 0 - if db is not None and source != "platform": - placed_local = _builder_extras( - config, emulators_dir, db, emu_profiles, baseline_groups, - base_dest, is_flat, zip_set, zip_lower, target_cores, - region_drops, data_registry, - include_all=(source == "truth"), required_only=required_only, - ) - for full, local in sorted(placed_local.items()): - core_checked += 1 - member = _flat(full, base_dest, is_flat) - member = member if member in zip_set else zip_lower.get(member.lower()) - if member is None: - errors.append(f"core missing: {full}") - elif not _same_content(zf, member, local): - errors.append( - f"core file differs: {member} is not the {os.path.basename(local)}" - " the builder places there" - ) - else: - core_present += 1 - - checked = baseline_checked + core_checked - present = baseline_present + core_present + baseline_groups, system_of = _baseline_groups(expect, view.is_flat) + baseline = _count_baseline(expect, view, baseline_groups, system_of, errors) + errors.extend(_native_hash_errors(zf, baseline.decl_by_member, expect.config, db)) + core_checked, core_present = _check_core_extras(expect, view, baseline_groups, errors) return ( len(errors) == 0, - checked, - present, + baseline.checked + core_checked, + baseline.present + core_present, errors, - baseline_checked, - baseline_present, + baseline.checked, + baseline.present, core_checked, core_present, - baseline_excluded, - baseline_absent, + baseline.excluded, + baseline.absent, ) diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 35040f87f..0b6e01074 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -58,6 +58,7 @@ import tempfile import time from collections.abc import Callable from pathlib import Path +from typing import TYPE_CHECKING # The build scripts need CPython 3.9, which builds the same database, # manifests and packs as 3.12. @@ -80,6 +81,9 @@ from common import ( from refresh_data_dirs import hold_data_dirs from packpaths import MEDIA_MARKER +if TYPE_CHECKING: + from generate_pack import PackRecord + class StepResults(dict): """The outcome of each step, and how long it took. @@ -195,7 +199,7 @@ def run(cmd: list[str], label: str) -> tuple[bool, str]: cwd=repo_root, env={**os.environ, "PYTHONUNBUFFERED": "1", "NODE_DISABLE_COMPILE_CACHE": "1"}, ) as proc: - for line in proc.stdout: + for line in proc.stdout or (): lines.append(line) print(line, end="", flush=True) returncode = proc.wait() @@ -378,15 +382,19 @@ def check_consistency( p_match = p_label break - if p_match and p_match in pack_extras and v_label in verify_extras: - if verify_extras[v_label] != pack_extras[p_match]: - # The cores' share: the base check passed RomM while verify - # counted 412 core files and game data and the pack held 60. - print( - f" {v_label}: MISMATCH core files verify " - f"{verify_extras[v_label]} != pack {pack_extras[p_match]}" - ) - all_ok = False + if ( + p_match + and p_match in pack_extras + and v_label in verify_extras + and verify_extras[v_label] != pack_extras[p_match] + ): + # The cores' share: the base check passed RomM while verify + # counted 412 core files and game data and the pack held 60. + print( + f" {v_label}: MISMATCH core files verify " + f"{verify_extras[v_label]} != pack {pack_extras[p_match]}" + ) + all_ok = False if p_match: p_ok, p_total = p[p_match] p_excluded = excluded.get(p_match, 0) @@ -596,8 +604,9 @@ def check_emulator_packs( with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): generate_pack.generate_emulator_pack( - names, emulators_dir, db, "bios", "", standalone, zip_contents, - offline=True, platforms_dir=platforms_dir, record=record, **narrowing, + names, emulators_dir, db, "bios", "", standalone, + zip_contents=zip_contents, offline=True, platforms_dir=platforms_dir, + record=record, **narrowing, ) report = verify.verify_emulator( names, emulators_dir, db, standalone, platforms_dir=platforms_dir, @@ -817,7 +826,7 @@ def check_narrowed_packs( def split_differences( - full: object, parts: dict[str, object], same_bytes: Callable[[str, str], bool], + full: PackRecord, parts: dict[str, PackRecord], same_bytes: Callable[[str, str], bool], ) -> list[str]: """Where the --split parts of a pack, together, are not the full pack. @@ -1074,7 +1083,7 @@ def _truth_steps(args: argparse.Namespace, results: dict) -> bool: return all_ok -def main() -> None: +def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description="Run the full retrobios pipeline") parser.add_argument( "--skip-packs", @@ -1128,45 +1137,12 @@ def main() -> None: action="store_true", help="Export native formats (implies --with-truth)", ) - args = parser.parse_args() - _refuse_unapplied_flags(parser, args) - _refuse_offline_without_caches(parser, args) - _refuse_offline_export_without_originals(parser, args) - if not args.offline: - # Read once and put in the environment every step inherits: the - # scrapers and refresh_data_dirs went anonymous unless the user had - # exported GITHUB_TOKEN by hand, though gh was logged in. - github_token() - args.output_dir = _output_dir(args.output_dir) + return parser - # A second run on the same output directory is refused before any work: - # the database rebuild alone takes minutes, and the reader holding the - # directory would otherwise see the answer only after all of it. The - # hold lasts until this process exits: taken step by step, it let another - # run purge the packs between the build and the integrity check, which - # then reported every platform SKIP and passed. - # database.json, install/, README.md, CONTRIBUTING.md and website/ sit at - # fixed paths (artifacts.REPOSITORY_OUTPUTS), so - # every run holds them too: a run on a scratch --output-dir otherwise - # rewrote them beside the run on dist/. - held = contextlib.ExitStack() - try: - root = str(Path(__file__).resolve().parent.parent) - held.enter_context(hold_repository_outputs(root)) - # Its steps write database.json, install/ and README.md themselves, - # and take the same lock to do so. - held.enter_context(publish_hold(root)) - if not args.skip_packs: - held.enter_context(hold_artifact_lock(args.output_dir)) - except ArtifactLockBusy as exc: - held.close() - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) +def _database_steps(results: dict) -> bool: + """Steps 0 to 1c: schemas, database, dump catalogs, romset recipes.""" all_ok = True - total_start = time.monotonic() - results = StepResults(total_start) - # Step 0: the schema check PR validation runs. Without it a profile with # `cores: [81]` unquoted passed the whole pipeline and failed CI on push. # jsonschema is tooling only, so its absence skips the step. @@ -1188,7 +1164,7 @@ def main() -> None: all_ok = all_ok and ok # Step 1: Generate database - ok, out = run( + ok, _ = run( [ sys.executable, "scripts/generate_db.py", @@ -1219,7 +1195,7 @@ def main() -> None: # Step 1c: Which emulator version each arcade archive corresponds to, and # which pinned archive the collection could rebuild from ROMs it holds. # Read-only: writing reconstructions is an explicit --write invocation. - ok, out = run( + ok, _ = run( [sys.executable, "scripts/romset_recipes.py"], STEP_LABELS["romset_recipes"], ) @@ -1233,10 +1209,15 @@ def main() -> None: ok = ok and captured results["romset_recipes"] = ok all_ok = all_ok and ok + return all_ok + +def _refresh_steps(args: argparse.Namespace, results: dict) -> bool: + """Steps 2 to 2b2: data directories, hash scrapers, release assets.""" + all_ok = True # Step 2: Refresh data directories if not args.offline: - ok, out = run( + ok, _ = run( [sys.executable, "scripts/refresh_data_dirs.py"], STEP_LABELS["refresh_data"], ) @@ -1295,9 +1276,18 @@ def main() -> None: else: skip_notice("check_release_assets", "--offline") results["check_release_assets"] = SKIPPED + return all_ok - all_ok = _truth_steps(args, results) and all_ok +def _verify_steps( + args: argparse.Namespace, results: dict, held: contextlib.ExitStack +) -> tuple[bool, str, str]: + """Steps 3 to 3b: verify, identities, slots. + + Returns whether they passed, verify's output and the file of the paths + each pack holds by its report. + """ + all_ok = True # Every step from here reads the data directory trees: verify, the packs, # the manifests and the integrity check. Held shared until the run ends, # a refresh from another session waits instead of swapping a tree @@ -1352,52 +1342,70 @@ def main() -> None: ok, _ = run(slots_cmd, "3b slot arbitration") results["slots"] = ok all_ok &= ok + return all_ok, verify_output, destinations_file + +def _purge_stale_packs(output_dir: str) -> None: + """Remove the packs of earlier builds from the output directory.""" + # Purge stale packs: leftover ZIPs from previous builds would be + # picked up by pack verification and shipped in releases. + out_dir = Path(output_dir) + if not out_dir.is_dir(): + return + try: + with artifact_lock(str(out_dir)): + stale = [ + p for p in out_dir.iterdir() + if p.is_file() and ( + p.suffix == ".zip" + or ".zip." in p.name + or p.name == "SHA256SUMS.txt" + ) + ] + for p in stale: + p.unlink() + if stale: + print(f"Purged {len(stale)} stale pack file(s) from {out_dir}/") + except ArtifactLockBusy as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + + +def _pack_command(args: argparse.Namespace) -> list[str]: + """The step 4 command: every platform's pack.""" + pack_cmd = [ + sys.executable, + "scripts/generate_pack.py", + "--all", + "--output-dir", + args.output_dir, + ] + if args.offline: + pack_cmd.append("--offline") + else: + # Step 2 refreshed the trees once: refreshing again here let the + # pack and the manifest describe two revisions of a moving tree. + pack_cmd.append("--no-refresh-data") + if args.target: + pack_cmd.extend(["--target", args.target]) + if args.source != "full": + pack_cmd.extend(["--source", args.source]) + if args.all_variants: + pack_cmd.append("--all-variants") + return pack_cmd + + +def _pack_steps(args: argparse.Namespace, results: dict) -> tuple[bool, str]: + """Steps 4 to 4c: packs, install manifests, target manifests. + + Returns whether they passed and the pack build's output. + """ + all_ok = True # Step 4: Generate packs pack_output = "" if not args.skip_packs: - # Purge stale packs: leftover ZIPs from previous builds would be - # picked up by pack verification and shipped in releases. - out_dir = Path(args.output_dir) - if out_dir.is_dir(): - try: - with artifact_lock(str(out_dir)): - stale = [ - p for p in out_dir.iterdir() - if p.is_file() and ( - p.suffix == ".zip" - or ".zip." in p.name - or p.name == "SHA256SUMS.txt" - ) - ] - for p in stale: - p.unlink() - if stale: - print(f"Purged {len(stale)} stale pack file(s) from {out_dir}/") - except ArtifactLockBusy as exc: - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) - - pack_cmd = [ - sys.executable, - "scripts/generate_pack.py", - "--all", - "--output-dir", - args.output_dir, - ] - if args.offline: - pack_cmd.append("--offline") - else: - # Step 2 refreshed the trees once: refreshing again here let the - # pack and the manifest describe two revisions of a moving tree. - pack_cmd.append("--no-refresh-data") - if args.target: - pack_cmd.extend(["--target", args.target]) - if args.source != "full": - pack_cmd.extend(["--source", args.source]) - if args.all_variants: - pack_cmd.append("--all-variants") - ok, pack_output = run(pack_cmd, STEP_LABELS["generate_packs"]) + _purge_stale_packs(args.output_dir) + ok, pack_output = run(_pack_command(args), STEP_LABELS["generate_packs"]) results["generate_packs"] = ok all_ok = all_ok and ok else: @@ -1445,7 +1453,12 @@ def main() -> None: else: skip_notice("generate_target_manifests", "--skip-packs") results["generate_target_manifests"] = SKIPPED + return all_ok, pack_output + +def _index_steps(results: dict) -> bool: + """Steps 4d and 4e: bundled-only copies, the games index.""" + all_ok = True # Step 4d: A collected copy that only an emulator's own install provides. # Packs leave such files out, so a copy nothing else asks for is weight # the collection carries for nobody. Read after the manifests, which say @@ -1468,7 +1481,19 @@ def main() -> None: ) results["games_index"] = ok all_ok &= ok + return all_ok + +def _check_steps( + args: argparse.Namespace, + results: dict, + *, + pack_output: str, + verify_output: str, + destinations_file: str, +) -> bool: + """Steps 5 and 6: verify against the packs, then the packs' integrity.""" + all_ok = True # Step 5: Consistency check. verify describes the full pack, and a run that # built only a reduced one (--source platform or truth) has nothing to # compare it with, and says so instead of failing on an empty parse. @@ -1509,7 +1534,12 @@ def main() -> None: else: skip_notice("pack_integrity", "--skip-packs") results["pack_integrity"] = SKIPPED + return all_ok + +def _docs_steps(args: argparse.Namespace, results: dict) -> bool: + """Steps 7 to 8b: README and pages, site pages, the rendered site.""" + all_ok = True # Step 7: Generate README if not args.skip_docs: ok, _ = run( @@ -1565,8 +1595,11 @@ def main() -> None: "8b validate site") results["render_site"] = ok all_ok = all_ok and ok + return all_ok - # Summary + +def _print_summary(results: StepResults, total_start: float, all_ok: bool) -> None: + """The table of every step's outcome and duration, then the verdict.""" total_elapsed = time.monotonic() - total_start print(f"\n{'=' * 60}") warned = [] @@ -1590,10 +1623,72 @@ def main() -> None: if warned: print(f" {', '.join(warned)} reported a difference, which does not fail the run") print(f"{'=' * 60}") + + +def main() -> None: + parser = _parser() + args = parser.parse_args() + _refuse_unapplied_flags(parser, args) + _refuse_offline_without_caches(parser, args) + _refuse_offline_export_without_originals(parser, args) + if not args.offline: + # Read once and put in the environment every step inherits: the + # scrapers and refresh_data_dirs went anonymous unless the user had + # exported GITHUB_TOKEN by hand, though gh was logged in. + github_token() + args.output_dir = _output_dir(args.output_dir) + held = _hold_outputs(args) + + total_start = time.monotonic() + results = StepResults(total_start) + + all_ok = _database_steps(results) + all_ok = _refresh_steps(args, results) and all_ok + all_ok = _truth_steps(args, results) and all_ok + ok, verify_output, destinations_file = _verify_steps(args, results, held) + all_ok = all_ok and ok + ok, pack_output = _pack_steps(args, results) + all_ok = all_ok and ok + all_ok = _index_steps(results) and all_ok + all_ok = _check_steps( + args, results, pack_output=pack_output, verify_output=verify_output, + destinations_file=destinations_file, + ) and all_ok + all_ok = _docs_steps(args, results) and all_ok + + _print_summary(results, total_start, all_ok) held.close() sys.exit(0 if all_ok else 1) +def _hold_outputs(args: argparse.Namespace) -> contextlib.ExitStack: + """Take every lock the run holds until it exits, or exit when one is busy.""" + # A second run on the same output directory is refused before any work: + # the database rebuild alone takes minutes, and the reader holding the + # directory would otherwise see the answer only after all of it. The + # hold lasts until this process exits: taken step by step, it let another + # run purge the packs between the build and the integrity check, which + # then reported every platform SKIP and passed. + # database.json, install/, README.md, CONTRIBUTING.md and website/ sit at + # fixed paths (artifacts.REPOSITORY_OUTPUTS), so + # every run holds them too: a run on a scratch --output-dir otherwise + # rewrote them beside the run on dist/. + held = contextlib.ExitStack() + try: + root = str(Path(__file__).resolve().parent.parent) + held.enter_context(hold_repository_outputs(root)) + # Its steps write database.json, install/ and README.md themselves, + # and take the same lock to do so. + held.enter_context(publish_hold(root)) + if not args.skip_packs: + held.enter_context(hold_artifact_lock(args.output_dir)) + except ArtifactLockBusy as exc: + held.close() + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + return held + + if __name__ == "__main__": from common import run_cli 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/provenance_report.py b/scripts/provenance_report.py index 8eba45d91..1857de953 100644 --- a/scripts/provenance_report.py +++ b/scripts/provenance_report.py @@ -139,7 +139,9 @@ def profile_needs(profiles: dict, db: dict) -> dict: def needs_filled(entry: dict, needs: dict) -> list[dict]: """The profile needs a catalog dump answers, required ones first.""" found: dict[tuple[str, str], dict] = {} - keys = [(field, v) for field in HASH_FIELDS for v in _values(entry, field)] + keys: list[tuple[object, ...]] = [ + (field, v) for field in HASH_FIELDS for v in _values(entry, field) + ] if entry.get("size") is not None: keys += [("crc32", _crc_key(v), entry["size"]) for v in _values(entry, "crc32")] for key in keys: @@ -344,12 +346,11 @@ def build_report( out_of_scope = len({ dump_identity(e) for e in unmatched if e.get("dat", "") not in covered_dats }) - matched = len(matched) report[source] = { "imported_at": snapshot.get("imported_at", ""), "dats": snapshot.get("dats", {}), "total": len(snapshot["entries"]), - "matched": matched, + "matched": len(matched), "covered_dats": sorted(covered_dats), "missing": missing, "out_of_scope": out_of_scope, @@ -357,6 +358,27 @@ def build_report( return report +def _print_missing(entry: dict, derived: dict[str, dict]) -> None: + """One missing dump, with what derives it, reads it and holds it.""" + label = entry.get("description") or entry["name"] + source = derived.get(entry.get("sha1", "")) + if source: + print(f" DERIVABLE {entry['name']} ({label}): {source['transform']} " + f"of {' + '.join(source['from'])}") + else: + print(f" MISSING {entry['name']} ({label}) sha1={entry.get('sha1')}") + for need in entry.get("needed_by", []): + print(f" needed by {need['emulator']} as {need['name']} " + f"({'required' if need['required'] else 'optional'}, " + f"matched by {need['by']})") + for hit in entry.get("romsets", []): + versions = hit["dats"][0] if len(hit["dats"]) == 1 else ( + f"{hit['dats'][0]} to {hit['dats'][-1]}" + ) + print(f" in {hit['source']} {hit['archive']} as " + f"{hit['member']} ({versions})") + + def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description="Dump-catalog coverage report") parser.add_argument("--db", default="database.json", help="Database path") @@ -437,23 +459,7 @@ def main() -> int: if args.missing: # A dump an emulator reads comes first: it fills a hole in a pack. for entry in sorted(data["missing"], key=lambda e: not e.get("needed_by")): - label = entry.get("description") or entry["name"] - source = derived.get(entry.get("sha1", "")) - if source: - print(f" DERIVABLE {entry['name']} ({label}): {source['transform']} " - f"of {' + '.join(source['from'])}") - else: - print(f" MISSING {entry['name']} ({label}) sha1={entry.get('sha1')}") - for need in entry.get("needed_by", []): - print(f" needed by {need['emulator']} as {need['name']} " - f"({'required' if need['required'] else 'optional'}, " - f"matched by {need['by']})") - for hit in entry.get("romsets", []): - versions = hit["dats"][0] if len(hit["dats"]) == 1 else ( - f"{hit['dats'][0]} to {hit['dats'][-1]}" - ) - print(f" in {hit['source']} {hit['archive']} as " - f"{hit['member']} ({versions})") + _print_missing(entry, derived) total_missing = distinct_missing(report) if total_missing: diff --git a/scripts/refresh_data_dirs.py b/scripts/refresh_data_dirs.py index eb3655a0c..f0fd8ed74 100644 --- a/scripts/refresh_data_dirs.py +++ b/scripts/refresh_data_dirs.py @@ -278,9 +278,7 @@ def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool: return False resolved = (dest / member.name).resolve() dest_str = str(dest.resolve()) + os.sep - if not str(resolved).startswith(dest_str) and str(resolved) != str(dest.resolve()): - return False - return True + return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve()) def _download_and_extract( @@ -349,11 +347,11 @@ def _download_and_extract( elif member.isfile(): dest_file = extract_dir / rel dest_file.parent.mkdir(parents=True, exist_ok=True) - with tf.extractfile(member) as src: - if src is None: - continue - with open(dest_file, "wb") as dst: - shutil.copyfileobj(src, dst) + src = tf.extractfile(member) + if src is None: + continue + with src, open(dest_file, "wb") as dst: + shutil.copyfileobj(src, dst) file_count += 1 if not file_count: 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/romset_recipes.py b/scripts/romset_recipes.py index c8dcb5cb5..c2adaf235 100644 --- a/scripts/romset_recipes.py +++ b/scripts/romset_recipes.py @@ -581,6 +581,25 @@ def _resolve_modes(args: argparse.Namespace) -> None: args.identify = args.missing = True +def print_identification(ident: dict) -> None: + """Which recipe reproduces each local archive, counted by recipe.""" + print( + f"\nIdentification: {len(ident['identified'])} archives reproduced " + f"by a recipe, {len(ident['unidentified'])} unidentified" + ) + print( + " The label is the oldest version producing these bytes: a recipe " + "unchanged since 0.177 is counted there, not at its own version." + ) + by_recipe: dict[str, int] = defaultdict(int) + for record in ident["identified"]: + by_recipe[record["recipe"]] += 1 + for label, count in sorted(by_recipe.items(), key=lambda kv: (-kv[1], kv[0])): + print(f" {label}: {count}") + for record in ident["unidentified"][:10]: + print(f" UNIDENTIFIED: {record['path']}") + + def main() -> int: parser = argparse.ArgumentParser( allow_abbrev=False, @@ -692,22 +711,7 @@ def main() -> int: print(f" UNREADABLE: {problem}") if args.identify: - ident = result["identify"] - print( - f"\nIdentification: {len(ident['identified'])} archives reproduced " - f"by a recipe, {len(ident['unidentified'])} unidentified" - ) - print( - " The label is the oldest version producing these bytes: a recipe " - "unchanged since 0.177 is counted there, not at its own version." - ) - by_recipe: dict[str, int] = defaultdict(int) - for record in ident["identified"]: - by_recipe[record["recipe"]] += 1 - for label, count in sorted(by_recipe.items(), key=lambda kv: (-kv[1], kv[0])): - print(f" {label}: {count}") - for record in ident["unidentified"][:10]: - print(f" UNIDENTIFIED: {record['path']}") + print_identification(result["identify"]) if args.missing: print_missing(result["missing"]) diff --git a/scripts/safeparse.py b/scripts/safeparse.py index a0f0caa7a..1ec703159 100644 --- a/scripts/safeparse.py +++ b/scripts/safeparse.py @@ -64,31 +64,29 @@ def _pick_yaml_loader() -> type[yaml.constructor.SafeConstructor] | None: return None base = getattr(yaml, "CSafeLoader", None) or yaml.SafeLoader - class _UniqueKeyLoader(base): - """Refuses a mapping that names a key twice. + def construct_mapping( + self: yaml.constructor.SafeConstructor, node: yaml.MappingNode, deep: bool = False + ) -> dict: + """Refuse a mapping that names a key twice. PyYAML keeps the last value without a word: the registry once carried two target_source keys for Recalbox and read only one. Only a mapping that came out shorter than its source is re-read. No data here uses merge keys (<<), which would count as repeats too. """ + mapping = base.construct_mapping(self, node, deep=deep) + if len(mapping) < len(node.value): + seen: set = set() + for key_node, _value in node.value: + key = self.construct_object(key_node, deep=deep) + if key in seen: + raise yaml.constructor.ConstructorError( + None, None, f"duplicate key {key!r}", key_node.start_mark + ) + seen.add(key) + return mapping - def construct_mapping( - self, node: yaml.MappingNode, deep: bool = False - ) -> dict: - mapping = super().construct_mapping(node, deep=deep) - if len(mapping) < len(node.value): - seen: set = set() - for key_node, _value in node.value: - key = self.construct_object(key_node, deep=deep) - if key in seen: - raise yaml.constructor.ConstructorError( - None, None, f"duplicate key {key!r}", key_node.start_mark - ) - seen.add(key) - return mapping - - return _UniqueKeyLoader + return type("_UniqueKeyLoader", (base,), {"construct_mapping": construct_mapping}) _YAML_LOADER = _pick_yaml_loader() 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/torrentzip.py b/scripts/torrentzip.py index 5e2faff66..41f1588fb 100644 --- a/scripts/torrentzip.py +++ b/scripts/torrentzip.py @@ -217,6 +217,8 @@ def main() -> int: parser.add_argument("--rebuild", metavar="ZIP", help="normalize an archive") parser.add_argument("--output", "-o", help="output path for --rebuild") args = parser.parse_args() + if not (args.check or args.rebuild): + parser.error("nothing to do: pass --check or --rebuild") if args.check: data = Path(args.check).read_bytes() @@ -228,14 +230,11 @@ def main() -> int: print(f" conform: {data == rebuilt}") return 0 if data == rebuilt else 1 - if args.rebuild: - data = rebuild_torrentzip(args.rebuild) - dest = args.output or args.rebuild - Path(dest).write_bytes(data) - print(f"{dest}: {len(data)} bytes, md5 {hashlib.md5(data).hexdigest()}") - return 0 - - parser.error("nothing to do: pass --check or --rebuild") + data = rebuild_torrentzip(args.rebuild) + dest = args.output or args.rebuild + Path(dest).write_bytes(data) + print(f"{dest}: {len(data)} bytes, md5 {hashlib.md5(data).hexdigest()}") + return 0 if __name__ == "__main__": 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/scripts/ziptools.py b/scripts/ziptools.py index 4fcf14e06..4567e2ef3 100644 --- a/scripts/ziptools.py +++ b/scripts/ziptools.py @@ -5,6 +5,8 @@ capping a real romset: the largest pack is already several gigabytes.""" from __future__ import annotations +from dataclasses import dataclass + import functools import hashlib import os @@ -235,6 +237,109 @@ MAX_ZIP_COMPRESSION_RATIO = 1_100 _BOUNDED_RATIO_METHODS = (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED) +@dataclass(frozen=True) +class _ZipLimits: + """The resource bounds safe_extract_zip enforces.""" + + members: int + member_size: int + total_size: int + compression_ratio: int + + +def _member_path(member: zipfile.ZipInfo, seen: set[str]) -> tuple[str, list[str], int]: + """(name, path components, mode) of a member whose path and type are safe.""" + # Archives written on Windows store a backslash separator. It is a + # separator, not a filename character, so it is normalized before + # the component checks rather than rejected. + name = member.filename.replace("\\", "/") + if not name or "\x00" in name: + raise ValueError(f"Unsafe ZIP member name: {member.filename!r}") + if name.startswith("/") or re.match(r"^[A-Za-z]:", name): + raise ValueError(f"Absolute ZIP member path: {name}") + parts = [part for part in name.split("/") if part] + if any(part in (".", "..") for part in parts): + raise ValueError(f"ZIP traversal detected: {name}") + normalized = "/".join(parts) + if normalized in seen: + raise ValueError(f"Duplicate ZIP member path: {name}") + seen.add(normalized) + + mode = (member.external_attr >> 16) & 0xFFFF + file_type = stat.S_IFMT(mode) + if file_type not in (0, stat.S_IFREG, stat.S_IFDIR): + raise ValueError(f"ZIP link or special file rejected: {name}") + if member.flag_bits & 0x1: + raise ValueError(f"Encrypted ZIP member rejected: {name}") + return name, parts, mode + + +def _check_member_size( + member: zipfile.ZipInfo, name: str, declared_total: int, limits: _ZipLimits, +) -> int: + """The declared total with this member, after its size limits are checked.""" + if member.file_size > limits.member_size: + raise ValueError( + f"ZIP member {name} is {member.file_size} bytes; " + f"limit is {limits.member_size}" + ) + declared_total += member.file_size + if declared_total > limits.total_size: + raise ValueError( + f"ZIP expands to {declared_total} bytes, limit is {limits.total_size}" + ) + if member.file_size and member.compress_type in _BOUNDED_RATIO_METHODS: + if member.compress_size == 0: + raise ValueError(f"Invalid compression size for ZIP member: {name}") + if member.file_size / member.compress_size > limits.compression_ratio: + raise ValueError(f"Suspicious compression ratio for ZIP member: {name}") + return declared_total + + +def _install_member( + zf: zipfile.ZipFile, + member: zipfile.ZipInfo, + name: str, + target: str, + mode: int, + umask: int, + max_member_size: int, +) -> None: + """Stream a member to a temporary sibling, check it, then move it in place.""" + os.makedirs(os.path.dirname(target), exist_ok=True) + tmp_path = "" + try: + with tempfile.NamedTemporaryFile( + mode="wb", dir=os.path.dirname(target), delete=False + ) as tmp_file: + tmp_path = tmp_file.name + actual_size = 0 + with zf.open(member, "r") as source: + while True: + chunk = source.read(1024 * 1024) + if not chunk: + break + actual_size += len(chunk) + if actual_size > member.file_size or actual_size > max_member_size: + raise ValueError( + f"ZIP member exceeded declared or configured size: {name}" + ) + tmp_file.write(chunk) + if actual_size != member.file_size: + raise ValueError( + f"ZIP member size mismatch for {name}: " + f"{actual_size} != {member.file_size}" + ) + # The member's own mode, else what a plain open() gives. The + # temporary file is private and would keep 0600 otherwise. + os.chmod(tmp_path, ((mode & 0o777) or 0o666) & ~umask) + os.replace(tmp_path, target) + tmp_path = "" + finally: + if tmp_path and os.path.exists(tmp_path): + os.unlink(tmp_path) + + def safe_extract_zip( zip_path: str, dest_dir: str, @@ -249,56 +354,22 @@ def safe_extract_zip( Files are streamed to a temporary sibling and atomically installed only after their declared length and CRC have been checked by ``zipfile``. """ + limits = _ZipLimits(max_members, max_member_size, max_total_size, max_compression_ratio) dest = os.path.realpath(dest_dir) os.makedirs(dest, exist_ok=True) umask = process_umask() with zipfile.ZipFile(zip_path, "r") as zf: members = zf.infolist() - if len(members) > max_members: + if len(members) > limits.members: raise ValueError( - f"ZIP has {len(members)} members, limit is {max_members}" + f"ZIP has {len(members)} members, limit is {limits.members}" ) declared_total = 0 seen: set[str] = set() for member in members: - # Archives written on Windows store a backslash separator. It is a - # separator, not a filename character, so it is normalized before - # the component checks rather than rejected. - name = member.filename.replace("\\", "/") - if not name or "\x00" in name: - raise ValueError(f"Unsafe ZIP member name: {member.filename!r}") - if name.startswith("/") or re.match(r"^[A-Za-z]:", name): - raise ValueError(f"Absolute ZIP member path: {name}") - parts = [part for part in name.split("/") if part] - if any(part in (".", "..") for part in parts): - raise ValueError(f"ZIP traversal detected: {name}") - normalized = "/".join(parts) - if normalized in seen: - raise ValueError(f"Duplicate ZIP member path: {name}") - seen.add(normalized) - - mode = (member.external_attr >> 16) & 0xFFFF - file_type = stat.S_IFMT(mode) - if file_type not in (0, stat.S_IFREG, stat.S_IFDIR): - raise ValueError(f"ZIP link or special file rejected: {name}") - if member.flag_bits & 0x1: - raise ValueError(f"Encrypted ZIP member rejected: {name}") - if member.file_size > max_member_size: - raise ValueError( - f"ZIP member {name} is {member.file_size} bytes; " - f"limit is {max_member_size}" - ) - declared_total += member.file_size - if declared_total > max_total_size: - raise ValueError( - f"ZIP expands to {declared_total} bytes, limit is {max_total_size}" - ) - if member.file_size and member.compress_type in _BOUNDED_RATIO_METHODS: - if member.compress_size == 0: - raise ValueError(f"Invalid compression size for ZIP member: {name}") - if member.file_size / member.compress_size > max_compression_ratio: - raise ValueError(f"Suspicious compression ratio for ZIP member: {name}") + name, parts, mode = _member_path(member, seen) + declared_total = _check_member_size(member, name, declared_total, limits) target = os.path.realpath(os.path.join(dest, *parts)) if not target.startswith(dest + os.sep) and target != dest: @@ -306,36 +377,4 @@ def safe_extract_zip( if member.is_dir() or name.endswith("/"): os.makedirs(target, exist_ok=True) continue - - os.makedirs(os.path.dirname(target), exist_ok=True) - tmp_path = "" - try: - with tempfile.NamedTemporaryFile( - mode="wb", dir=os.path.dirname(target), delete=False - ) as tmp_file: - tmp_path = tmp_file.name - actual_size = 0 - with zf.open(member, "r") as source: - while True: - chunk = source.read(1024 * 1024) - if not chunk: - break - actual_size += len(chunk) - if actual_size > member.file_size or actual_size > max_member_size: - raise ValueError( - f"ZIP member exceeded declared or configured size: {name}" - ) - tmp_file.write(chunk) - if actual_size != member.file_size: - raise ValueError( - f"ZIP member size mismatch for {name}: " - f"{actual_size} != {member.file_size}" - ) - # The member's own mode, else what a plain open() gives. The - # temporary file is private and would keep 0600 otherwise. - os.chmod(tmp_path, ((mode & 0o777) or 0o666) & ~umask) - os.replace(tmp_path, target) - tmp_path = "" - finally: - if tmp_path and os.path.exists(tmp_path): - os.unlink(tmp_path) + _install_member(zf, member, name, target, mode, umask, limits.member_size) 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: