From 6ba52a96828289e90b4a38a4e1dbe5cc8841e625 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:12:16 +0100 Subject: [PATCH] refactor: move verify, slots, crossref into packs The three commands keep their parser, main and printing. Scans, scopes, report text, the JSON forms, the strict gate and the destinations file live in new packs modules, one subject each. --- scripts/cross_reference.py | 313 +------------------------- scripts/packs/crossreflaunchers.py | 49 ++++ scripts/packs/crossrefrun.py | 32 +++ scripts/packs/crossrefscope.py | 100 ++++++++ scripts/packs/crossreftext.py | 133 +++++++++++ scripts/packs/slotreport.py | 156 +++++++++++++ scripts/packs/slotscan.py | 61 +++++ scripts/packs/strictgate.py | 35 +++ scripts/packs/verifyoutput.py | 35 +++ scripts/packs/verifyplatforms.py | 116 ++++++++++ scripts/packs/verifysummary.py | 77 +++++++ scripts/slots.py | 194 +--------------- scripts/verify.py | 268 +++------------------- tests/sources.py | 12 +- tests/test_audit_regressions.py | 28 +-- tests/test_cross_reference_sources.py | 2 +- tests/test_e2e.py | 7 +- tests/test_launcher_gaps.py | 19 +- tests/test_slots.py | 21 +- tests/test_target_verify.py | 7 +- tests/test_tool_messages.py | 6 +- 21 files changed, 897 insertions(+), 774 deletions(-) create mode 100644 scripts/packs/crossreflaunchers.py create mode 100644 scripts/packs/crossrefrun.py create mode 100644 scripts/packs/crossrefscope.py create mode 100644 scripts/packs/crossreftext.py create mode 100644 scripts/packs/slotreport.py create mode 100644 scripts/packs/slotscan.py create mode 100644 scripts/packs/strictgate.py create mode 100644 scripts/packs/verifyoutput.py create mode 100644 scripts/packs/verifyplatforms.py create mode 100644 scripts/packs/verifysummary.py diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index e3219cb41..b819bb3c9 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -18,169 +18,23 @@ import argparse import json import os import sys -from dataclasses import dataclass sys.path.insert(0, os.path.dirname(__file__)) from core.cli import add_repo_inputs -from core.text import count_text from model.cliargs import platform_arg, list_emulator_profiles, require_platform from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles from model.database import load_database -from model.registry import list_registered_platforms, load_data_dir_registry -from model.platforms import load_platform_config +from model.registry import load_data_dir_registry from model.safeparse import require_yaml -from resolve.standalone import standalone_set -from resolve.launchers import ( - LauncherLayer, - declared_destinations, - launcher_unproven, -) -from packs.crossref import ( - build_supplemental_index, - cross_reference, - global_report_scope, - launcher_reads_not_held, - platform_configs, - profile_breakdown, -) +from packs.crossreflaunchers import LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, launcher_rows +from packs.crossrefrun import scope_gaps +from packs.crossrefscope import TreeScope, tree_scope +from packs.crossreftext import print_launcher_reads, print_launcher_unproven, print_report yaml = require_yaml() -# The --json key of the launcher reads category, beside the emulator keys. -LAUNCHER_READS_KEY = "_launcher_reads_not_held" -# The --json key of the launcher records a config file does not prove. -LAUNCHER_UNPROVEN_KEY = "_launcher_unproven" - - -def print_launcher_unproven(rows: list[dict]) -> None: - """The launcher records resting on a config file the code does not prove. - - Neither a pack, a manifest nor a severity reads them: each is listed - with the links it lacks. - """ - if not rows: - return - platforms = sorted({r["platform"] for r in rows}) - print(f"\nLauncher records unproven: {len(rows)} across {count_text(len(platforms), 'platform')}") - for platform in platforms: - print(f"\n{platform}") - for row in (r for r in rows if r["platform"] == platform): - print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}") - for link in row["missing"]: - print(f" missing {link}") - - -def print_launcher_reads(rows: list[dict]) -> None: - """The launcher reads gap category, after the profile gaps. - - A name its reader declares unsourceable is listed apart, with the - reason: it is no file left to find. - """ - unsourceable = [r for r in rows if r.get("unsourceable")] - rows = [r for r in rows if not r.get("unsourceable")] - platforms = sorted({r["platform"] for r in rows}) - print(f"\nLauncher reads, not held: {count_text(len(rows), 'name')} " - f"across {count_text(len(platforms), 'platform')}") - for platform in platforms: - print(f"\n{platform}") - for row in (r for r in rows if r["platform"] == platform): - first = row["readers"][0] - more = f" (+{count_text(len(row['readers']) - 1, 'record')})" if len(row["readers"]) > 1 else "" - casing = f", held as {row['held_as']}" if row.get("held_as") else "" - print( - f" {row['name']} [{', '.join(row['emulators'])}, {first['kind']}, " - f"{first['source_ref']}]{more}{casing}" - ) - if not unsourceable: - return - platforms = sorted({r["platform"] for r in unsourceable}) - print( - f"\nLauncher reads, unsourceable: {count_text(len(unsourceable), 'name')} " - f"across {count_text(len(platforms), 'platform')}" - ) - for row in unsourceable: - print( - f" {row['platform']}: {row['name']} [{', '.join(row['emulators'])}, " - f"{row['readers'][0]['source_ref']}]: {row['unsourceable']}" - ) - - -def print_report( - report: dict, scope: str = "all emulators", show_clean: bool = False -) -> None: - """Print a human-readable gap analysis report. - - `scope` names what the totals cover: under --platform, the emulators - that platform runs, not all of them. `show_clean` lists an emulator with - nothing undeclared too: asked about by name, it was the whole answer and - the report used to leave it out. - """ - print("Emulator vs Platform Gap Analysis") - print("=" * 60) - print("* marks a file the emulator requires") - - total_gaps = 0 - totals: dict[str, int] = {"bios": 0, "data": 0, "large_file": 0, "missing": 0} - # A runtime component bundled with its emulator is left out of the - # collection by design, as verify and the gaps page say: not a file to find. - bundled = 0 - - for _emu_name, data in sorted(report.items()): - gaps = data["gaps"] - if gaps == 0 and not show_clean: - continue - - # Counted once, for the heading and the total alike: a file installed - # with its emulator is neither one to source nor one the pack brings, - # held or not (validation.deliverable leaves it out of every pack). - bundled_gaps = [g for g in data["gap_details"] if g.get("bundled")] - emulator_bundled = len(bundled_gaps) - counts = {key: data.get(f"gap_{key}", 0) for key in totals} - for g in bundled_gaps: - counts[g.get("source", "missing")] -= 1 - counts["bundled"] = emulator_bundled - parts = [f"{count} {key}" for key, count in counts.items() if count] - status = ", ".join(parts) if parts else "OK" - - systems = ", ".join(data["systems"]) - print(f"\n{data['emulator']}" + (f" ({systems})" if systems else "")) - print(f" {data['total_files']} files in profile: {profile_breakdown(data)}") - print(f" Gaps: {status}") - - for g in data["gap_details"]: - req = "*" if g["required"] else " " - src = g.get("source", "missing").upper() - if g.get("bundled"): - src = "BUNDLED" - # One line per file: a note spanning lines fell to column 0 - # between entries and read as an emulator heading. - note = f": {' '.join(str(g['note']).split())}" if g["note"] else "" - archive_info = "" - if g.get("archive"): - fc = g.get("archive_file_count", 0) - rc = g.get("archive_required_count", 0) - archive_info = f" ({fc} files, {rc} required)" - if g.get("alternatives") and not g.get("in_repo"): - archive_info += f" (or {', '.join(g['alternatives'])})" - print(f" {req} {g['name']} [{src}]{archive_info}{note}") - - total_gaps += gaps - for key in totals: - totals[key] += counts[key] - bundled += emulator_bundled - - print(f"\n{'=' * 60}") - print(f"Total: {total_gaps} undeclared files across {scope}") - available = totals["bios"] + totals["data"] + totals["large_file"] - print(f" {available} available (bios: {totals['bios']}, data: {totals['data']}, " - f"large_file: {totals['large_file']})") - print(f" {totals['missing']} missing (need to be sourced)") - if bundled: - print(f" {bundled} bundled with their emulator, not packed") - - def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description="Emulator vs platform gap analysis") add_repo_inputs(parser, "emulators", "platforms", "db") @@ -204,98 +58,7 @@ def _build_parser() -> argparse.ArgumentParser: return parser -@dataclass(frozen=True) -class _PlatformScope: - """The profiles a --platform run compares, and how the platform runs them.""" - - profiles: dict[str, dict] - standalone_cores: set[str] - config: dict - relevant: set[str] - run_anywhere: set[str] - - -def _platform_scope(args: argparse.Namespace, profiles: dict[str, dict]) -> _PlatformScope: - from model.targets import target_scope - from resolve.cores import resolve_platform_cores - - # A typo ended in a traceback where verify and slots name the closest - # target, and is refused the way they refuse it. - target_cores = target_scope( - [args.platform], args.target, args.platforms_dir - )[0].get(args.platform) - config = load_platform_config(args.platform, args.platforms_dir) - relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) - run_anywhere = ( - set(resolve_platform_cores(config, profiles)) if args.target else relevant - ) - return _PlatformScope( - {k: v for k, v in profiles.items() if k in relevant}, - standalone_set(config), - config, - relevant, - run_anywhere, - ) - - -@dataclass(frozen=True) -class _TreeScope: - """What a run compares: the profiles, the platforms whose lists and - launchers they are measured against (None for every platform), and the - standalone layout of those platforms.""" - - profiles: dict[str, dict] - standalone_cores: set[str] - selected: list[str] | None - platform: _PlatformScope | None = None - - -def _target_platforms_scope(args: argparse.Namespace, profiles: dict[str, dict]) -> _TreeScope: - """--target without --platform: every platform that has the target, each - with the cores it builds for it, the way verify and generate_pack read - --all --target. A target no platform has ends the run.""" - from model.targets import target_scope - from resolve.cores import resolve_platform_cores - from resolve.standalone import merged_standalone_set - - cache, kept = target_scope( - list_registered_platforms(args.platforms_dir), args.target, args.platforms_dir, - is_all=True, - ) - configs = {name: load_platform_config(name, args.platforms_dir) for name in kept} - relevant: set[str] = set() - for name, config in configs.items(): - relevant |= set(resolve_platform_cores(config, profiles, target_cores=cache.get(name))) - return _TreeScope( - {k: v for k, v in profiles.items() if k in relevant}, - merged_standalone_set(configs.values()), - kept, - ) - - -def _tree_scope(args: argparse.Namespace, profiles: dict[str, dict]) -> _TreeScope: - """The scope --platform, --target or neither asks for.""" - if args.platform: - scope = _platform_scope(args, profiles) - return _TreeScope(scope.profiles, scope.standalone_cores, [args.platform], scope) - if args.target: - return _target_platforms_scope(args, profiles) - # The tree as every platform runs it: a profile some platform runs - # standalone keeps its standalone entries. Laid out as libretro only, - # eka2l1, dolphin and xenia-edge lost 133 files no platform declares. - from resolve.standalone import merged_standalone_set - - return _TreeScope( - profiles, - merged_standalone_set( - load_platform_config(name, args.platforms_dir) - for name in list_registered_platforms(args.platforms_dir) - ), - None, - ) - - -def _refuse_empty_scope(args: argparse.Namespace, emulator: str | None, tree: _TreeScope) -> None: +def _refuse_empty_scope(args: argparse.Namespace, emulator: str | None, tree: TreeScope) -> None: """Why the scope holds no profile, said before ending the run.""" platform_scope = tree.platform if (emulator and args.target and platform_scope is not None @@ -318,42 +81,6 @@ def _refuse_empty_scope(args: argparse.Namespace, emulator: str | None, tree: _T print(f"{args.platform or 'The tree'} runs no profiled emulator.", file=sys.stderr) -def _launcher_rows( - args: argparse.Namespace, - selected: list[str] | None, - db: dict, - all_profiles: dict[str, dict], - registry: dict, - emulator: str | None, -) -> tuple[list[dict], list[dict]]: - """The names a launcher reads that the collection lacks, and the - launcher records nothing proves.""" - # Counted apart from the profile gaps: a name only a launcher reads is - # reported, not yet judged. - launcher_reads = launcher_reads_not_held( - { - name: load_platform_config(name, args.platforms_dir) - for name in (selected or list_registered_platforms(args.platforms_dir)) - }, - db, all_profiles, registry, emulator or "", - ) - - unproven = [ - row for row in launcher_unproven( - { - name: load_platform_config(name, args.platforms_dir) - for name in (selected or list_registered_platforms(args.platforms_dir)) - }, - all_profiles, - ) - if not emulator or any( - emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles)) - for part in row["emulator"].split(", ") - ) - ] - return launcher_reads, unproven - - def main() -> None: parser = _build_parser() args = parser.parse_args() @@ -399,33 +126,15 @@ def main() -> None: raise SystemExit(f"ERROR: {exc}") from None profiles = {k: v for k, v in profiles.items() if k == emulator} - tree = _tree_scope(args, profiles) - profiles = tree.profiles - platform_scope = tree.platform - if not profiles: + tree = tree_scope(args.platform, args.target, args.platforms_dir, profiles) + if not tree.profiles: _refuse_empty_scope(args, emulator, tree) return - selected = tree.selected db = load_database(args.db) - declared, global_scope = global_report_scope( - platform_configs(args.platforms_dir, selected), db) - global_scope["standalone_cores"] = tree.standalone_cores - data_names = build_supplemental_index() - report = cross_reference( - profiles, declared, db, data_names, **global_scope, - platform=( - platform_scope.config.get("_key", args.platform) if platform_scope else "" - ), - # What the platform's launchers open, as verify and the builder read it. - launcher_layer=LauncherLayer( - platform_scope.config, profiles, platform_scope.relevant, db, - declared_destinations(platform_scope.config), - ) if platform_scope else None, - ) - - launcher_reads, unproven = _launcher_rows( - args, selected, db, all_profiles, registry, emulator, + report = scope_gaps(tree, db, args.platforms_dir, args.platform) + launcher_reads, unproven = launcher_rows( + tree.selected, args.platforms_dir, db, all_profiles, registry, emulator, ) if args.json: diff --git a/scripts/packs/crossreflaunchers.py b/scripts/packs/crossreflaunchers.py new file mode 100644 index 000000000..1c71a78f6 --- /dev/null +++ b/scripts/packs/crossreflaunchers.py @@ -0,0 +1,49 @@ +"""The launcher rows of a gap report: names read and not held, records left unproven.""" + +from __future__ import annotations + +from model.platforms import load_platform_config +from model.registry import list_registered_platforms +from packs.crossref import launcher_reads_not_held +from resolve.launchers import LauncherLayer, launcher_unproven + +# The --json key of the launcher reads category, beside the emulator keys. +LAUNCHER_READS_KEY = "_launcher_reads_not_held" +# The --json key of the launcher records a config file does not prove. +LAUNCHER_UNPROVEN_KEY = "_launcher_unproven" + + +def launcher_rows( + selected: list[str] | None, + platforms_dir: str, + db: dict, + all_profiles: dict[str, dict], + registry: dict, + emulator: str | None, +) -> tuple[list[dict], list[dict]]: + """The names a launcher reads that the collection lacks, and the + launcher records nothing proves.""" + # Counted apart from the profile gaps: a name only a launcher reads is + # reported, not yet judged. + launcher_reads = launcher_reads_not_held( + { + name: load_platform_config(name, platforms_dir) + for name in (selected or list_registered_platforms(platforms_dir)) + }, + db, all_profiles, registry, emulator or "", + ) + + unproven = [ + row for row in launcher_unproven( + { + name: load_platform_config(name, platforms_dir) + for name in (selected or list_registered_platforms(platforms_dir)) + }, + all_profiles, + ) + if not emulator or any( + emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles)) + for part in row["emulator"].split(", ") + ) + ] + return launcher_reads, unproven diff --git a/scripts/packs/crossrefrun.py b/scripts/packs/crossrefrun.py new file mode 100644 index 000000000..69105e56c --- /dev/null +++ b/scripts/packs/crossrefrun.py @@ -0,0 +1,32 @@ +"""The profile gaps of one gap report scope, measured as verify and the builder measure them.""" + +from __future__ import annotations + +from packs.crossref import ( + build_supplemental_index, + cross_reference, + global_report_scope, + platform_configs, +) +from packs.crossrefscope import TreeScope +from resolve.launchers import LauncherLayer, declared_destinations + + +def scope_gaps(tree: TreeScope, db: dict, platforms_dir: str, platform: str | None) -> dict: + """Each profile of the scope with the files its platforms leave undeclared.""" + platform_scope = tree.platform + declared, global_scope = global_report_scope( + platform_configs(platforms_dir, tree.selected), db) + global_scope["standalone_cores"] = tree.standalone_cores + data_names = build_supplemental_index() + return cross_reference( + tree.profiles, declared, db, data_names, **global_scope, + platform=( + platform_scope.config.get("_key", platform) if platform_scope else "" + ), + # What the platform's launchers open, as verify and the builder read it. + launcher_layer=LauncherLayer( + platform_scope.config, tree.profiles, platform_scope.relevant, db, + declared_destinations(platform_scope.config), + ) if platform_scope else None, + ) diff --git a/scripts/packs/crossrefscope.py b/scripts/packs/crossrefscope.py new file mode 100644 index 000000000..16dea8e5b --- /dev/null +++ b/scripts/packs/crossrefscope.py @@ -0,0 +1,100 @@ +"""The profiles a gap report compares and the platforms it measures them against.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from model.platforms import load_platform_config +from model.registry import list_registered_platforms +from model.targets import target_scope +from resolve.cores import resolve_platform_cores +from resolve.standalone import merged_standalone_set, standalone_set + + +@dataclass(frozen=True) +class PlatformScope: + """The profiles a --platform run compares, and how the platform runs them.""" + + profiles: dict[str, dict] + standalone_cores: set[str] + config: dict + relevant: set[str] + run_anywhere: set[str] + + +def platform_scope( + platform: str, target: str | None, platforms_dir: str, profiles: dict[str, dict], +) -> PlatformScope: + """The scope of a --platform run, narrowed to its --target cores.""" + # A typo ended in a traceback where verify and slots name the closest + # target, and is refused the way they refuse it. + target_cores = target_scope( + [platform], target, platforms_dir + )[0].get(platform) + config = load_platform_config(platform, platforms_dir) + relevant = resolve_platform_cores(config, profiles, target_cores=target_cores) + run_anywhere = ( + set(resolve_platform_cores(config, profiles)) if target else relevant + ) + return PlatformScope( + {k: v for k, v in profiles.items() if k in relevant}, + standalone_set(config), + config, + relevant, + run_anywhere, + ) + + +@dataclass(frozen=True) +class TreeScope: + """What a run compares: the profiles, the platforms whose lists and + launchers they are measured against (None for every platform), and the + standalone layout of those platforms.""" + + profiles: dict[str, dict] + standalone_cores: set[str] + selected: list[str] | None + platform: PlatformScope | None = None + + +def target_platforms_scope( + target: str, platforms_dir: str, profiles: dict[str, dict], +) -> TreeScope: + """--target without --platform: every platform that has the target, each + with the cores it builds for it, the way verify and generate_pack read + --all --target. A target no platform has ends the run.""" + cache, kept = target_scope( + list_registered_platforms(platforms_dir), target, platforms_dir, + is_all=True, + ) + configs = {name: load_platform_config(name, platforms_dir) for name in kept} + relevant: set[str] = set() + for name, config in configs.items(): + relevant |= set(resolve_platform_cores(config, profiles, target_cores=cache.get(name))) + return TreeScope( + {k: v for k, v in profiles.items() if k in relevant}, + merged_standalone_set(configs.values()), + kept, + ) + + +def tree_scope( + platform: str | None, target: str | None, platforms_dir: str, profiles: dict[str, dict], +) -> TreeScope: + """The scope --platform, --target or neither asks for.""" + if platform: + scope = platform_scope(platform, target, platforms_dir, profiles) + return TreeScope(scope.profiles, scope.standalone_cores, [platform], scope) + if target: + return target_platforms_scope(target, platforms_dir, profiles) + # The tree as every platform runs it: a profile some platform runs + # standalone keeps its standalone entries. Laid out as libretro only, + # eka2l1, dolphin and xenia-edge lost 133 files no platform declares. + return TreeScope( + profiles, + merged_standalone_set( + load_platform_config(name, platforms_dir) + for name in list_registered_platforms(platforms_dir) + ), + None, + ) diff --git a/scripts/packs/crossreftext.py b/scripts/packs/crossreftext.py new file mode 100644 index 000000000..e4af4bdb1 --- /dev/null +++ b/scripts/packs/crossreftext.py @@ -0,0 +1,133 @@ +"""The gap report printed for a person: profile gaps, then the launcher rows.""" + +from __future__ import annotations + +from core.text import count_text +from packs.crossref import profile_breakdown + + +def print_launcher_unproven(rows: list[dict]) -> None: + """The launcher records resting on a config file the code does not prove. + + Neither a pack, a manifest nor a severity reads them: each is listed + with the links it lacks. + """ + if not rows: + return + platforms = sorted({r["platform"] for r in rows}) + print(f"\nLauncher records unproven: {len(rows)} across {count_text(len(platforms), 'platform')}") + for platform in platforms: + print(f"\n{platform}") + for row in (r for r in rows if r["platform"] == platform): + print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}") + for link in row["missing"]: + print(f" missing {link}") + + +def print_launcher_reads(rows: list[dict]) -> None: + """The launcher reads gap category, after the profile gaps. + + A name its reader declares unsourceable is listed apart, with the + reason: it is no file left to find. + """ + unsourceable = [r for r in rows if r.get("unsourceable")] + rows = [r for r in rows if not r.get("unsourceable")] + platforms = sorted({r["platform"] for r in rows}) + print(f"\nLauncher reads, not held: {count_text(len(rows), 'name')} " + f"across {count_text(len(platforms), 'platform')}") + for platform in platforms: + print(f"\n{platform}") + for row in (r for r in rows if r["platform"] == platform): + first = row["readers"][0] + more = f" (+{count_text(len(row['readers']) - 1, 'record')})" if len(row["readers"]) > 1 else "" + casing = f", held as {row['held_as']}" if row.get("held_as") else "" + print( + f" {row['name']} [{', '.join(row['emulators'])}, {first['kind']}, " + f"{first['source_ref']}]{more}{casing}" + ) + if not unsourceable: + return + platforms = sorted({r["platform"] for r in unsourceable}) + print( + f"\nLauncher reads, unsourceable: {count_text(len(unsourceable), 'name')} " + f"across {count_text(len(platforms), 'platform')}" + ) + for row in unsourceable: + print( + f" {row['platform']}: {row['name']} [{', '.join(row['emulators'])}, " + f"{row['readers'][0]['source_ref']}]: {row['unsourceable']}" + ) + + +def print_report( + report: dict, scope: str = "all emulators", show_clean: bool = False +) -> None: + """Print a human-readable gap analysis report. + + `scope` names what the totals cover: under --platform, the emulators + that platform runs, not all of them. `show_clean` lists an emulator with + nothing undeclared too: asked about by name, it was the whole answer and + the report used to leave it out. + """ + print("Emulator vs Platform Gap Analysis") + print("=" * 60) + print("* marks a file the emulator requires") + + total_gaps = 0 + totals: dict[str, int] = {"bios": 0, "data": 0, "large_file": 0, "missing": 0} + # A runtime component bundled with its emulator is left out of the + # collection by design, as verify and the gaps page say: not a file to find. + bundled = 0 + + for _emu_name, data in sorted(report.items()): + gaps = data["gaps"] + if gaps == 0 and not show_clean: + continue + + # Counted once, for the heading and the total alike: a file installed + # with its emulator is neither one to source nor one the pack brings, + # held or not (validation.deliverable leaves it out of every pack). + bundled_gaps = [g for g in data["gap_details"] if g.get("bundled")] + emulator_bundled = len(bundled_gaps) + counts = {key: data.get(f"gap_{key}", 0) for key in totals} + for g in bundled_gaps: + counts[g.get("source", "missing")] -= 1 + counts["bundled"] = emulator_bundled + parts = [f"{count} {key}" for key, count in counts.items() if count] + status = ", ".join(parts) if parts else "OK" + + systems = ", ".join(data["systems"]) + print(f"\n{data['emulator']}" + (f" ({systems})" if systems else "")) + print(f" {data['total_files']} files in profile: {profile_breakdown(data)}") + print(f" Gaps: {status}") + + for g in data["gap_details"]: + req = "*" if g["required"] else " " + src = g.get("source", "missing").upper() + if g.get("bundled"): + src = "BUNDLED" + # One line per file: a note spanning lines fell to column 0 + # between entries and read as an emulator heading. + note = f": {' '.join(str(g['note']).split())}" if g["note"] else "" + archive_info = "" + if g.get("archive"): + fc = g.get("archive_file_count", 0) + rc = g.get("archive_required_count", 0) + archive_info = f" ({fc} files, {rc} required)" + if g.get("alternatives") and not g.get("in_repo"): + archive_info += f" (or {', '.join(g['alternatives'])})" + print(f" {req} {g['name']} [{src}]{archive_info}{note}") + + total_gaps += gaps + for key in totals: + totals[key] += counts[key] + bundled += emulator_bundled + + print(f"\n{'=' * 60}") + print(f"Total: {total_gaps} undeclared files across {scope}") + available = totals["bios"] + totals["data"] + totals["large_file"] + print(f" {available} available (bios: {totals['bios']}, data: {totals['data']}, " + f"large_file: {totals['large_file']})") + print(f" {totals['missing']} missing (need to be sourced)") + if bundled: + print(f" {bundled} bundled with their emulator, not packed") diff --git a/scripts/packs/slotreport.py b/scripts/packs/slotreport.py new file mode 100644 index 000000000..711a0ab52 --- /dev/null +++ b/scripts/packs/slotreport.py @@ -0,0 +1,156 @@ +"""The slots report: one line per contested slot, its totals and its JSON form.""" + +from __future__ import annotations + +from model.platforms import load_platform_config +from packs.slots import ADDRESSEE, Claim, Conflict, Decision, arbitrate +from resolve.collisions import Collision +from resolve.localfile import resolution_is_hash_exact +from resolve.nativemode import platform_mode + + +def _pinned_elsewhere(claims: list[Claim], winner: str | None) -> set[str]: + """Emulators that pin content the served file does not carry.""" + return { + c.emulator for c in claims + if c.emulator and c.local_path != winner and resolution_is_hash_exact(c.status) + } + + +def format_decision(decision: Decision) -> str: + """One line naming the contested slot, the winner and the ground for it.""" + conflict = decision.conflict + if decision.serves_both: + winner = decision.winner.local_path + # A claim that only matched a path is answered by whatever file sits + # there. Only one that pins content can be left wanting. + pinned_elsewhere = _pinned_elsewhere(conflict.profile_claims, winner) + served = sorted({ + c.emulator for c in conflict.profile_claims if c.emulator + } - pinned_elsewhere) + others = sorted(pinned_elsewhere) + line = ( + f"{conflict.destination}: serve {winner} " + f"({', '.join(served) or 'profile'}): the frontend only " + "checks the path, so both are satisfied" + ) + if others: + # One path holds one file: an emulator pinning another is not served. + line += f"; {', '.join(others)} expected another file" + return line + if decision.reason == ADDRESSEE: + return ( + f"{conflict.destination}: serve {decision.winner.local_path}, " + "the pack answers to the emulator" + ) + rejected = ", ".join( + f"{path}, the file {', '.join(emulators) or 'the profile'} reads" + for path, emulators, _status in conflict.files_read() + ) + return ( + f"{conflict.destination}: keep {decision.winner.local_path}, the frontend " + f"verifies content and would reject {rejected}" + ) + + +def _collision_json(collision: Collision) -> dict: + return { + "destination": collision.destination, + "resolved": list(collision.resolved), + "shipped": collision.shipped, + "declarations": [ + {"system": system, "name": entry.get("name", ""), "file": local} + for system, (entry, local) in zip(collision.systems, collision.declarations) + ], + } + + +def format_collision(collision: Collision) -> str: + """One line naming the destination, which system declares which file, + and the one the pack ships there.""" + owners: dict[str, list[str]] = {} + for system, (_entry, local) in zip(collision.systems, collision.declarations): + if local and system not in owners.setdefault(local, []): + owners[local].append(system) + parts = [ + f"{path} ({', '.join(owners[path])}) " + + ("packed" if path == collision.shipped else "left out") + for path in collision.resolved + ] + return f"{collision.destination}: " + ", ".join(parts) + + +def format_conflict(conflict: Conflict) -> str: + """One line per conflict, naming both answers and who gave them.""" + emus = ", ".join(conflict.emulators) or "profile" + return ( + f"{conflict.destination}: pack ships {conflict.platform_claim.local_path} " + f"({conflict.platform_claim.status}), {emus} says " + f"{conflict.profile_claims[0].local_path} " + f"({conflict.profile_claims[0].status})" + ) + + +def report_json( + found: dict[str, list[Conflict]], collided: dict[str, list[Collision]], +) -> dict: + """The --json document: every contested slot and every doubled destination.""" + # --strict gates on collisions too, so a document that carries only + # conflicts hands a consumer an empty answer and a non-zero exit. + return { + "conflicts": { + platform: [ + { + "destination": c.destination, + "ships": c.platform_claim.local_path, + "ships_evidence": c.platform_claim.status, + "emulators": c.emulators, + "expected": [ + {"file": path, "evidence": status, "emulators": emulators} + for path, emulators, status in c.files_read() + ], + } + for c in conflicts + ] + for platform, conflicts in found.items() + }, + "collisions": { + platform: [_collision_json(c) for c in platform_collisions] + for platform, platform_collisions in collided.items() + }, + } + + +def report_lines( + found: dict[str, list[Conflict]], collided: dict[str, list[Collision]], + platforms_dir: str, strict: bool, +) -> list[str]: + """The text report: each decision with its ground, then the totals.""" + lines: list[str] = [] + fixable = 0 + for platform, conflicts in found.items(): + config = load_platform_config(platform, platforms_dir) + mode = platform_mode(config) + lines.append(f"{platform}: {len(conflicts)} contradicted [{mode}]") + for conflict in conflicts: + decision = arbitrate(conflict, mode, rule=config.get("hash_rule", "")) + fixable += decision.serves_both + lines.append(f" {format_decision(decision)}") + total = sum(len(c) for c in found.values()) + for platform, collisions in collided.items(): + lines.append(f"{platform}: {len(collisions)} destinations declared twice") + lines.extend(f" {format_collision(collision)}" for collision in collisions) + # The totals close the run, collisions counted: printed before that + # section, they were not the last word and left it out. + doubled = sum(len(c) for c in collided.values()) + lines.append( + f"\n{total} contested destinations. {fixable} the pack settles on " + f"its own, {total - fixable} follow the platform's list. " + f"{doubled} destinations declared twice." + ) + if not strict and (total or doubled): + lines.append( + "Reported, not failed: the remainder changes when the platform's " + "list does, which no build can do. Use --strict to gate on them." + ) + return lines diff --git a/scripts/packs/slotscan.py b/scripts/packs/slotscan.py new file mode 100644 index 000000000..c35e4d441 --- /dev/null +++ b/scripts/packs/slotscan.py @@ -0,0 +1,61 @@ +"""Contested and doubly declared destinations, platform by platform.""" + +from __future__ import annotations + +from core.paths import PLATFORMS_DIR +from core.ziptools import build_zip_contents_index +from model.platforms import load_platform_config +from model.registry import load_data_dir_registry +from packs.slots import Conflict, find_conflicts +from resolve.collisions import Collision, find_collisions +from resolve.cores import resolve_platform_cores +from resolve.standalone import standalone_set as platform_standalone_set + + +def scan_platform( + platform: str, profiles: dict, db: dict, platforms_dir: str = PLATFORMS_DIR, + target_cores: set[str] | None = None, zip_index: dict | None = None, + data_registry: dict | None = None, +) -> list[Conflict]: + """Conflicts on one platform, using the cores that platform actually runs.""" + config = load_platform_config(platform, platforms_dir) + keys = resolve_platform_cores(config, profiles, target_cores=target_cores) + relevant = {k: profiles[k] for k in keys if k in profiles} + # The same evidence the builder and the verifier resolve with: without + # the ZIP index and the data-directory registry the arbitration judged + # with less than the tools that read its verdict. + return find_conflicts( + config, + relevant, + db, + config.get("base_destination", ""), + platform_standalone_set(config), + build_zip_contents_index(db) if zip_index is None else zip_index, + load_data_dir_registry(platforms_dir) if data_registry is None else data_registry, + ) + + +def scan_platforms( + names: list[str], profiles: dict, db: dict, platforms_dir: str, + target_cores: dict[str, set[str] | None], data_registry: dict, +) -> tuple[dict[str, list[Conflict]], dict[str, list[Collision]]]: + """The platforms with a contested destination, and those declaring one twice.""" + zip_index = build_zip_contents_index(db) + found: dict[str, list[Conflict]] = {} + collided: dict[str, list[Collision]] = {} + for name in names: + conflicts = scan_platform( + name, profiles, db, platforms_dir, target_cores.get(name), + zip_index, data_registry, + ) + if conflicts: + found[name] = conflicts + collisions = find_collisions( + load_platform_config(name, platforms_dir), + db, + zip_index, + data_registry, + ) + if collisions: + collided[name] = collisions + return found, collided diff --git a/scripts/packs/strictgate.py b/scripts/packs/strictgate.py new file mode 100644 index 000000000..10f3f810a --- /dev/null +++ b/scripts/packs/strictgate.py @@ -0,0 +1,35 @@ +"""What fails a verify run under --strict, and the line that says why.""" + +from __future__ import annotations + +from packs.verdicts import Severity, Status + + +def platform_strict_failure(results: list[dict]) -> str | None: + """The failure of platform results counting a critical file: a required + file missing where the frontend reads hashes, or None. + + A file present whose hash the frontend does not confirm is UNTESTED, a + warning (Batocera's BiosStatus calls it so): reported, not failed. + """ + critical = sum(r["severity_counts"].get(Severity.CRITICAL, 0) for r in results) + if not critical: + return None + return (f"ERROR: {critical} required file(s) missing where the frontend " + "checks hashes") + + +def emulator_strict_failure(result: dict) -> str | None: + """The failure of an emulator lacking a file it cannot run without, or None. + + The emulator, not a frontend, is the judge here: a required file with no + HLE fallback that the collection does not hold stops the core. + """ + missing = sorted({ + d["name"] for d in result["details"] + if d["status"] == Status.MISSING and d.get("required", True) + and not d.get("hle_fallback") + }) + if not missing: + return None + return f"ERROR: {len(missing)} required file(s) missing: {', '.join(missing)}" diff --git a/scripts/packs/verifyoutput.py b/scripts/packs/verifyoutput.py new file mode 100644 index 000000000..bd122eb63 --- /dev/null +++ b/scripts/packs/verifyoutput.py @@ -0,0 +1,35 @@ +"""What a verify run hands a program: its JSON entries and the pack destinations file.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from packs.verdicts import Status + + +def json_details(details: list[dict], verbose: bool) -> list[dict]: + """The entries a JSON report lists: what needs attention, or every one. + + --verbose shows each entry with its ground truth in the text report. It + used to be accepted beside --json and dropped, the output byte for byte + the same, so a script asking for the passing entries got nothing. + """ + return list(details) if verbose else [ + d for d in details if d["status"] != Status.OK or d.get("release_asset") + ] + + +def write_pack_destinations( + path: str, + groups: list[tuple[list[str], str]], + group_results: list[tuple[dict, list[str]]], +) -> None: + """The paths each pack holds according to the report, per platform, as JSON.""" + destinations = {} + for (result, names), (group, _rep) in zip(group_results, groups): + for name, key in zip(names, group): + destinations[name] = { + "platform": key, "pack_destinations": result["pack_destinations"], + } + Path(path).write_text(json.dumps(destinations, indent=1, sort_keys=True)) diff --git a/scripts/packs/verifyplatforms.py b/scripts/packs/verifyplatforms.py new file mode 100644 index 000000000..c47c0f82f --- /dev/null +++ b/scripts/packs/verifyplatforms.py @@ -0,0 +1,116 @@ +"""Verify the platforms a run selects, one result per group of identical platforms.""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from model.registry import load_data_dir_registry +from model.targets import canonical_target_name, target_scope +from packs.coverage import verify_platform +from resolve.contentlayout import TARGET_KEY +from resolve.cores import platforms_with_systems, without_profile_blind +from resolve.grouping import group_identical_platforms + + +@dataclass(frozen=True) +class PlatformRun: + """What a platform-mode run asks of each platform it verifies.""" + + platforms_dir: str + emulators_dir: str + target: str | None = None + is_all: bool = False + regions: list[str] = field(default_factory=list) + system_filter: list[str] | None = None + no_game_data: bool = False + required_only: bool = False + + +@dataclass +class PlatformResults: + """The groups verified, each result with its platform names, and each platform's result.""" + + groups: list[tuple[list[str], str]] + group_results: list[tuple[dict, list[str]]] + all_results: dict[str, dict] + + +def run_target_scope( + run: PlatformRun, platforms: list[str], emu_profiles: dict, +) -> tuple[dict[str, set[str] | None], list[str]]: + """The cores of each platform on --target, and the platforms that have + it and a system of the --system list. A system the target leaves no + core for was reported 0/0 with exit 0, where generate_pack refuses the + same request.""" + target_cores_cache, platforms = target_scope( + platforms, run.target, run.platforms_dir, is_all=run.is_all + ) + if run.system_filter: + platforms = platforms_with_systems( + platforms, run.system_filter, emu_profiles, target_cores_cache, + run.platforms_dir, run.target, run.is_all, + ) + return target_cores_cache, platforms + + +def verify_platforms(platforms: list[str], db: dict, run: PlatformRun) -> PlatformResults: + """Each group of identical platforms verified once, as generate_pack builds it.""" + # Load emulator profiles once for cross-reference (not per-platform) + emu_profiles = load_emulator_profiles(run.emulators_dir) + data_registry = load_data_dir_registry(run.platforms_dir) + + target_cores_cache, platforms = run_target_scope(run, platforms, emu_profiles) + + # generate_pack refuses these on a platform whose cores no profile + # describes, and the report answers the same request the same way. + platforms = without_profile_blind( + platforms, + [ + flag for flag, given in ( + ("--region", run.regions), + ("--no-game-data", run.no_game_data), + ) if given + ], + run.platforms_dir, + emu_profiles, + target_cores_cache if run.target else None, + run.is_all, + ) + + # Group identical platforms (same function as generate_pack) + groups = group_identical_platforms( + platforms, run.platforms_dir, target_cores_cache if run.target else None + ) + + all_results = {} + group_results: list[tuple[dict, list[str]]] = [] + for group_platforms, representative in groups: + config = load_platform_config(representative, run.platforms_dir) + tc = target_cores_cache.get(representative) if run.target else None + if tc is not None: + # A core a roms folder offers on other boards only is not placed + # there, as generate_pack builds the board's pack. + config = {**config, TARGET_KEY: canonical_target_name( + [representative], run.target, run.platforms_dir)} + result = verify_platform( + config, + db, + run.emulators_dir, + emu_profiles, + target_cores=tc, + data_dir_registry=data_registry, + regions=run.regions, + system_filter=run.system_filter, + no_game_data=run.no_game_data, + required_only=run.required_only, + ) + names = [ + load_platform_config(p, run.platforms_dir).get("platform", p) + for p in group_platforms + ] + group_results.append((result, names)) + for p in group_platforms: + all_results[p] = result + return PlatformResults(groups, group_results, all_results) diff --git a/scripts/packs/verifysummary.py b/scripts/packs/verifysummary.py new file mode 100644 index 000000000..13cc81188 --- /dev/null +++ b/scripts/packs/verifysummary.py @@ -0,0 +1,77 @@ +"""The closing lines of a verify run over several platforms.""" + +from __future__ import annotations + +from core.text import count_text +from packs.report import NOT_FIRMWARE, core_required_missing, discrepancy_keys, split_undeclared +from packs.verdicts import Severity + + +def overall_summary(group_results: list[tuple[dict, list[str]]]) -> str: + """The closing lines of a multi-platform run, worst severity first. + + Each count names the platforms carrying it, and the core files a core + cannot run without are counted too: a reader of the summary alone used + to conclude nothing required was missing, and could not tell where the + one warning was without reading the whole output. + """ + platforms = sum(len(group) for _, group in group_results) + + def where(counts: dict[str, int]) -> str: + named = [f"{name} {count}" for name, count in counts.items() if count] + return f" ({', '.join(named)})" if named else "" + + def on(groups: tuple[str, ...]) -> str: + """The platforms a file is missing on, by the shorter side.""" + if len(group_results) < 2 or len(groups) * 2 <= len(group_results): + return ", ".join(groups) + others = [" / ".join(g) for _, g in group_results if " / ".join(g) not in groups] + return "every platform" + (f" but {', '.join(others)}" if others else "") + + parts = [] + for severity, label in ((Severity.CRITICAL, "critical"), (Severity.WARNING, "warning"), + (Severity.INFO, "info")): + counts = { + " / ".join(group): r["severity_counts"].get(severity, 0) + for r, group in group_results + } + parts.append(f"{sum(counts.values())} {label}{where(counts)}") + # Shipped files whose bytes contradict a declaration or a core's own + # check: the body printed 19 of them under a last line that read clean. + counts = { + " / ".join(group): len(discrepancy_keys(r.get("details", []))) + for r, group in group_results + } + total = sum(counts.values()) + parts.append(f"{count_text(total, 'discrepancy', 'discrepancies')}{where(counts)}") + lines = [f"{count_text(platforms, 'platform')}: {', '.join(parts)}"] + + # Grouped by file, not by platform: sfiii2a.zip missing everywhere was + # counted and printed once per platform, 24 files for 10 distinct ones. + holders: dict[str, list[str]] = {} + for r, group in group_results: + for name in sorted({ + u["name"] for u in core_required_missing(split_undeclared( + r.get("undeclared_files", []))[1]) + }): + holders.setdefault(name, []).append(" / ".join(group)) + if holders: + by_platforms: dict[tuple[str, ...], list[str]] = {} + for name, groups in sorted(holders.items()): + by_platforms.setdefault(tuple(groups), []).append(name) + detail = "; ".join( + f"{', '.join(names)} ({on(groups)})" + for groups, names in sorted(by_platforms.items(), + key=lambda item: (-len(item[0]), item[1])) + ) + lines.append(f"{len(holders)} core file(s) a core cannot run without are " + f"missing: {detail}") + for category, label in NOT_FIRMWARE.items(): + counts = { + " / ".join(group): len((r.get("missing_not_firmware") or {}).get(category, [])) + for r, group in group_results + } + total = sum(counts.values()) + if total: + lines.append(f"{total} platform entries missing, not firmware, {label}{where(counts)}") + return "\n".join(lines) diff --git a/scripts/slots.py b/scripts/slots.py index fa2b29f61..36c0ab0a6 100644 --- a/scripts/slots.py +++ b/scripts/slots.py @@ -20,129 +20,15 @@ feeds the report this module prints. from __future__ import annotations -from core.paths import PLATFORMS_DIR from core.cli import add_repo_inputs from model.cliargs import platform_arg, require_platform from model.database import load_database -from model.platforms import load_platform_config -from core.ziptools import build_zip_contents_index from model.profiles import load_emulator_profiles from model.registry import list_registered_platforms, load_data_dir_registry from model.targets import target_scope -from resolve.localfile import resolution_is_hash_exact -from resolve.nativemode import platform_mode -from resolve.standalone import standalone_set as platform_standalone_set -from packs.slots import ADDRESSEE, Claim, Conflict, Decision, arbitrate, find_conflicts -from resolve.collisions import Collision, find_collisions - - -def _pinned_elsewhere(claims: list[Claim], winner: str | None) -> set[str]: - """Emulators that pin content the served file does not carry.""" - return { - c.emulator for c in claims - if c.emulator and c.local_path != winner and resolution_is_hash_exact(c.status) - } - - -def format_decision(decision: Decision) -> str: - """One line naming the contested slot, the winner and the ground for it.""" - conflict = decision.conflict - if decision.serves_both: - winner = decision.winner.local_path - # A claim that only matched a path is answered by whatever file sits - # there. Only one that pins content can be left wanting. - pinned_elsewhere = _pinned_elsewhere(conflict.profile_claims, winner) - served = sorted({ - c.emulator for c in conflict.profile_claims if c.emulator - } - pinned_elsewhere) - others = sorted(pinned_elsewhere) - line = ( - f"{conflict.destination}: serve {winner} " - f"({', '.join(served) or 'profile'}): the frontend only " - "checks the path, so both are satisfied" - ) - if others: - # One path holds one file: an emulator pinning another is not served. - line += f"; {', '.join(others)} expected another file" - return line - if decision.reason == ADDRESSEE: - return ( - f"{conflict.destination}: serve {decision.winner.local_path}, " - "the pack answers to the emulator" - ) - rejected = ", ".join( - f"{path}, the file {', '.join(emulators) or 'the profile'} reads" - for path, emulators, _status in conflict.files_read() - ) - return ( - f"{conflict.destination}: keep {decision.winner.local_path}, the frontend " - f"verifies content and would reject {rejected}" - ) - - -def _collision_json(collision: Collision) -> dict: - return { - "destination": collision.destination, - "resolved": list(collision.resolved), - "shipped": collision.shipped, - "declarations": [ - {"system": system, "name": entry.get("name", ""), "file": local} - for system, (entry, local) in zip(collision.systems, collision.declarations) - ], - } - - -def format_collision(collision: Collision) -> str: - """One line naming the destination, which system declares which file, - and the one the pack ships there.""" - owners: dict[str, list[str]] = {} - for system, (_entry, local) in zip(collision.systems, collision.declarations): - if local and system not in owners.setdefault(local, []): - owners[local].append(system) - parts = [ - f"{path} ({', '.join(owners[path])}) " - + ("packed" if path == collision.shipped else "left out") - for path in collision.resolved - ] - return f"{collision.destination}: " + ", ".join(parts) - - -def format_conflict(conflict: Conflict) -> str: - """One line per conflict, naming both answers and who gave them.""" - emus = ", ".join(conflict.emulators) or "profile" - return ( - f"{conflict.destination}: pack ships {conflict.platform_claim.local_path} " - f"({conflict.platform_claim.status}), {emus} says " - f"{conflict.profile_claims[0].local_path} " - f"({conflict.profile_claims[0].status})" - ) - - -def scan_platform( - platform: str, profiles: dict, db: dict, platforms_dir: str = PLATFORMS_DIR, - target_cores: set[str] | None = None, zip_index: dict | None = None, - data_registry: dict | None = None, -) -> list[Conflict]: - """Conflicts on one platform, using the cores that platform actually runs.""" - from model.platforms import load_platform_config - from resolve.cores import resolve_platform_cores - - config = load_platform_config(platform, platforms_dir) - keys = resolve_platform_cores(config, profiles, target_cores=target_cores) - relevant = {k: profiles[k] for k in keys if k in profiles} - # The same evidence the builder and the verifier resolve with: without - # the ZIP index and the data-directory registry the arbitration judged - # with less than the tools that read its verdict. - return find_conflicts( - config, - relevant, - db, - config.get("base_destination", ""), - platform_standalone_set(config), - build_zip_contents_index(db) if zip_index is None else zip_index, - load_data_dir_registry(platforms_dir) if data_registry is None else data_registry, - ) +from packs.slotreport import report_json, report_lines +from packs.slotscan import scan_platforms def main() -> int: @@ -197,79 +83,15 @@ def main() -> int: names, args.target, args.platforms_dir, is_all=not args.platform ) - zip_index = build_zip_contents_index(db) - found: dict[str, list[Conflict]] = {} - collided: dict[str, list[Collision]] = {} - for name in names: - conflicts = scan_platform( - name, profiles, db, args.platforms_dir, target_cores.get(name), - zip_index, data_registry, - ) - if conflicts: - found[name] = conflicts - collisions = find_collisions( - load_platform_config(name, args.platforms_dir), - db, - zip_index, - data_registry, - ) - if collisions: - collided[name] = collisions + found, collided = scan_platforms( + names, profiles, db, args.platforms_dir, target_cores, data_registry, + ) if args.json: - # --strict gates on collisions too, so a document that carries only - # conflicts hands a consumer an empty answer and a non-zero exit. - payload = { - "conflicts": { - platform: [ - { - "destination": c.destination, - "ships": c.platform_claim.local_path, - "ships_evidence": c.platform_claim.status, - "emulators": c.emulators, - "expected": [ - {"file": path, "evidence": status, "emulators": emulators} - for path, emulators, status in c.files_read() - ], - } - for c in conflicts - ] - for platform, conflicts in found.items() - }, - "collisions": { - platform: [_collision_json(c) for c in platform_collisions] - for platform, platform_collisions in collided.items() - }, - } - print(json.dumps(payload, indent=2)) + print(json.dumps(report_json(found, collided), indent=2)) else: - fixable = 0 - for platform, conflicts in found.items(): - config = load_platform_config(platform, args.platforms_dir) - mode = platform_mode(config) - print(f"{platform}: {len(conflicts)} contradicted [{mode}]") - for conflict in conflicts: - decision = arbitrate(conflict, mode, rule=config.get("hash_rule", "")) - fixable += decision.serves_both - print(f" {format_decision(decision)}") - total = sum(len(c) for c in found.values()) - for platform, collisions in collided.items(): - print(f"{platform}: {len(collisions)} destinations declared twice") - for collision in collisions: - print(f" {format_collision(collision)}") - # The totals close the run, collisions counted: printed before that - # section, they were not the last word and left it out. - doubled = sum(len(c) for c in collided.values()) - print( - f"\n{total} contested destinations. {fixable} the pack settles on " - f"its own, {total - fixable} follow the platform's list. " - f"{doubled} destinations declared twice." - ) - if not args.strict and (total or doubled): - print( - "Reported, not failed: the remainder changes when the platform's " - "list does, which no build can do. Use --strict to gate on them." - ) + for line in report_lines(found, collided, args.platforms_dir, args.strict): + print(line) return 1 if ((found or collided) and args.strict) else 0 diff --git a/scripts/verify.py b/scripts/verify.py index 2dc1e552c..75a80b1e3 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -28,17 +28,10 @@ import contextlib import json import os import sys -from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) from core.cli import add_emulator_selection, add_repo_inputs -from core.text import count_text -from resolve.contentlayout import TARGET_KEY -from model.targets import ( - canonical_target_name, - target_scope, -) from model.cliargs import ( LISTING_FLAGS, comma_list, @@ -52,31 +45,17 @@ from model.cliargs import ( resolve_system_ids, selected_platforms, ) -from model.profiles import ( - load_emulator_profiles, -) from model.registry import load_data_dir_registry -from resolve.grouping import group_identical_platforms from model.database import load_database -from model.platforms import load_platform_config -from resolve.cores import ( - platforms_with_systems, - without_profile_blind, -) from model.safeparse import require_yaml -from packs.coverage import verify_platform from packs.emulatorcheck import verify_emulator, verify_system -from packs.report import ( - NOT_FIRMWARE, - core_required_missing, - discrepancy_keys, - split_undeclared, - print_emulator_result, - print_platform_result, -) -from packs.verdicts import Severity, Status +from packs.report import print_emulator_result, print_platform_result +from packs.strictgate import emulator_strict_failure, platform_strict_failure +from packs.verifyoutput import json_details, write_pack_destinations +from packs.verifyplatforms import PlatformResults, PlatformRun, verify_platforms +from packs.verifysummary import overall_summary yaml = require_yaml() @@ -201,7 +180,7 @@ def _run_emulator_mode(args: argparse.Namespace, db: dict, requested_regions: li required_only=args.required_only, ) if args.json: - result["details"] = _json_details(result["details"], args.verbose) + result["details"] = json_details(result["details"], args.verbose) print(json.dumps(result, indent=2)) else: print_emulator_result(result, verbose=args.verbose) @@ -216,60 +195,29 @@ def _run_system_mode(args: argparse.Namespace, db: dict, requested_regions: list required_only=args.required_only, ) if args.json: - result["details"] = _json_details(result["details"], args.verbose) + result["details"] = json_details(result["details"], args.verbose) print(json.dumps(result, indent=2)) else: print_emulator_result(result, verbose=args.verbose) _exit_if_strict_emulator(args.strict, result) -def _target_scope( - args: argparse.Namespace, - platforms: list[str], - emu_profiles: dict, - platform_systems: list[str] | None, -) -> tuple[dict[str, set[str] | None], list[str]]: - """The cores of each platform on --target, and the platforms that have - it and a system of the --system list. A system the target leaves no - core for was reported 0/0 with exit 0, where generate_pack refuses the - same request.""" - target_cores_cache, platforms = target_scope( - platforms, args.target, args.platforms_dir, is_all=args.all - ) - if platform_systems: - platforms = platforms_with_systems( - platforms, platform_systems, emu_profiles, target_cores_cache, - args.platforms_dir, args.target, args.all, - ) - return target_cores_cache, platforms - - -def _print_platform_results( - args: argparse.Namespace, - groups: list[tuple[list[str], str]], - group_results: list[tuple[dict, list[str]]], - all_results: dict[str, dict], -) -> None: +def _print_platform_results(args: argparse.Namespace, results: PlatformResults) -> None: + group_results = results.group_results if not args.json: for result, group in group_results: print_platform_result(result, group, verbose=args.verbose) print() if len(group_results) > 1: - print(_overall_summary(group_results)) + print(overall_summary(group_results)) if args.destinations: - destinations = {} - for (result, names), (group, _rep) in zip(group_results, groups): - for name, key in zip(names, group): - destinations[name] = { - "platform": key, "pack_destinations": result["pack_destinations"], - } - Path(args.destinations).write_text(json.dumps(destinations, indent=1, sort_keys=True)) + write_pack_destinations(args.destinations, results.groups, group_results) if args.json: - for r in all_results.values(): - r["details"] = _json_details(r["details"], args.verbose) - print(json.dumps(all_results, indent=2)) + for r in results.all_results.values(): + r["details"] = json_details(r["details"], args.verbose) + print(json.dumps(results.all_results, indent=2)) def _run_platform_mode( @@ -279,69 +227,18 @@ def _run_platform_mode( requested_regions: list[str], platform_systems: list[str] | None, ) -> None: - platforms = selected_platforms(args, parser) - - # Load emulator profiles once for cross-reference (not per-platform) - emu_profiles = load_emulator_profiles(args.emulators_dir) - data_registry = load_data_dir_registry(args.platforms_dir) - - target_cores_cache, platforms = _target_scope( - args, platforms, emu_profiles, platform_systems, - ) - - # generate_pack refuses these on a platform whose cores no profile - # describes, and the report answers the same request the same way. - platforms = without_profile_blind( - platforms, - [ - flag for flag, given in ( - ("--region", requested_regions), - ("--no-game-data", getattr(args, "no_game_data", False)), - ) if given - ], - args.platforms_dir, - emu_profiles, - target_cores_cache if args.target else None, - args.all, - ) - - # Group identical platforms (same function as generate_pack) - groups = group_identical_platforms( - platforms, args.platforms_dir, target_cores_cache if args.target else None - ) - - all_results = {} - group_results: list[tuple[dict, list[str]]] = [] - for group_platforms, representative in groups: - config = load_platform_config(representative, args.platforms_dir) - tc = target_cores_cache.get(representative) if args.target else None - if tc is not None: - # A core a roms folder offers on other boards only is not placed - # there, as generate_pack builds the board's pack. - config = {**config, TARGET_KEY: canonical_target_name( - [representative], args.target, args.platforms_dir)} - result = verify_platform( - config, - db, - args.emulators_dir, - emu_profiles, - target_cores=tc, - data_dir_registry=data_registry, - regions=requested_regions, - system_filter=platform_systems, - no_game_data=getattr(args, "no_game_data", False), - required_only=args.required_only, - ) - names = [ - load_platform_config(p, args.platforms_dir).get("platform", p) - for p in group_platforms - ] - group_results.append((result, names)) - for p in group_platforms: - all_results[p] = result - - _print_platform_results(args, groups, group_results, all_results) - _exit_if_strict(args.strict, [r for r, _ in group_results]) + results = verify_platforms(selected_platforms(args, parser), db, PlatformRun( + platforms_dir=args.platforms_dir, + emulators_dir=args.emulators_dir, + target=args.target, + is_all=args.all, + regions=requested_regions, + system_filter=platform_systems, + no_game_data=getattr(args, "no_game_data", False), + required_only=args.required_only, + )) + _print_platform_results(args, results) + _exit_if_strict(args.strict, [r for r, _ in results.group_results]) def _main(held: contextlib.ExitStack) -> None: @@ -382,119 +279,22 @@ def _main(held: contextlib.ExitStack) -> None: _run_platform_mode(args, parser, db, regions, platform_systems) -def _json_details(details: list[dict], verbose: bool) -> list[dict]: - """The entries a JSON report lists: what needs attention, or every one. - - --verbose shows each entry with its ground truth in the text report. It - used to be accepted beside --json and dropped, the output byte for byte - the same, so a script asking for the passing entries got nothing. - """ - return list(details) if verbose else [ - d for d in details if d["status"] != Status.OK or d.get("release_asset") - ] - - def _exit_if_strict(strict: bool, results: list[dict]) -> None: - """Exit 1 under --strict when a platform result counts a critical file: - a required file missing where the frontend reads hashes. - - A file present whose hash the frontend does not confirm is UNTESTED, a - warning (Batocera's BiosStatus calls it so): reported, not failed. - """ - critical = sum(r["severity_counts"].get(Severity.CRITICAL, 0) for r in results) - if strict and critical: - print(f"ERROR: {critical} required file(s) missing where the frontend " - "checks hashes", file=sys.stderr) + """Exit 1 under --strict when a platform result counts a critical file.""" + failure = platform_strict_failure(results) + if strict and failure: + print(failure, file=sys.stderr) sys.exit(1) def _exit_if_strict_emulator(strict: bool, result: dict) -> None: - """Exit 1 under --strict when an emulator lacks a file it cannot run without. - - The emulator, not a frontend, is the judge here: a required file with no - HLE fallback that the collection does not hold stops the core. - """ - missing = sorted({ - d["name"] for d in result["details"] - if d["status"] == Status.MISSING and d.get("required", True) - and not d.get("hle_fallback") - }) - if strict and missing: - print(f"ERROR: {len(missing)} required file(s) missing: " - f"{', '.join(missing)}", file=sys.stderr) + """Exit 1 under --strict when an emulator lacks a file it cannot run without.""" + failure = emulator_strict_failure(result) + if strict and failure: + print(failure, file=sys.stderr) sys.exit(1) -def _overall_summary(group_results: list[tuple[dict, list[str]]]) -> str: - """The closing lines of a multi-platform run, worst severity first. - - Each count names the platforms carrying it, and the core files a core - cannot run without are counted too: a reader of the summary alone used - to conclude nothing required was missing, and could not tell where the - one warning was without reading the whole output. - """ - platforms = sum(len(group) for _, group in group_results) - - def where(counts: dict[str, int]) -> str: - named = [f"{name} {count}" for name, count in counts.items() if count] - return f" ({', '.join(named)})" if named else "" - - def on(groups: tuple[str, ...]) -> str: - """The platforms a file is missing on, by the shorter side.""" - if len(group_results) < 2 or len(groups) * 2 <= len(group_results): - return ", ".join(groups) - others = [" / ".join(g) for _, g in group_results if " / ".join(g) not in groups] - return "every platform" + (f" but {', '.join(others)}" if others else "") - - parts = [] - for severity, label in ((Severity.CRITICAL, "critical"), (Severity.WARNING, "warning"), - (Severity.INFO, "info")): - counts = { - " / ".join(group): r["severity_counts"].get(severity, 0) - for r, group in group_results - } - parts.append(f"{sum(counts.values())} {label}{where(counts)}") - # Shipped files whose bytes contradict a declaration or a core's own - # check: the body printed 19 of them under a last line that read clean. - counts = { - " / ".join(group): len(discrepancy_keys(r.get("details", []))) - for r, group in group_results - } - total = sum(counts.values()) - parts.append(f"{count_text(total, 'discrepancy', 'discrepancies')}{where(counts)}") - lines = [f"{count_text(platforms, 'platform')}: {', '.join(parts)}"] - - # Grouped by file, not by platform: sfiii2a.zip missing everywhere was - # counted and printed once per platform, 24 files for 10 distinct ones. - holders: dict[str, list[str]] = {} - for r, group in group_results: - for name in sorted({ - u["name"] for u in core_required_missing(split_undeclared( - r.get("undeclared_files", []))[1]) - }): - holders.setdefault(name, []).append(" / ".join(group)) - if holders: - by_platforms: dict[tuple[str, ...], list[str]] = {} - for name, groups in sorted(holders.items()): - by_platforms.setdefault(tuple(groups), []).append(name) - detail = "; ".join( - f"{', '.join(names)} ({on(groups)})" - for groups, names in sorted(by_platforms.items(), - key=lambda item: (-len(item[0]), item[1])) - ) - lines.append(f"{len(holders)} core file(s) a core cannot run without are " - f"missing: {detail}") - for category, label in NOT_FIRMWARE.items(): - counts = { - " / ".join(group): len((r.get("missing_not_firmware") or {}).get(category, [])) - for r, group in group_results - } - total = sum(counts.values()) - if total: - lines.append(f"{total} platform entries missing, not firmware, {label}{where(counts)}") - return "\n".join(lines) - - if __name__ == "__main__": from core.cli import run_cli diff --git a/tests/sources.py b/tests/sources.py index 30ef7bbb0..731c8f8e3 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -24,10 +24,16 @@ COMMANDS = { ), "verify.py": ( "packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py", - "packs/report.py", + "packs/report.py", "packs/verifyplatforms.py", "packs/verifysummary.py", + "packs/verifyoutput.py", "packs/strictgate.py", + ), + "cross_reference.py": ( + "packs/crossref.py", "packs/crossrefscope.py", "packs/crossrefrun.py", + "packs/crossreflaunchers.py", "packs/crossreftext.py", + ), + "slots.py": ( + "packs/slots.py", "resolve/collisions.py", "packs/slotscan.py", "packs/slotreport.py", ), - "cross_reference.py": ("packs/crossref.py",), - "slots.py": ("packs/slots.py", "resolve/collisions.py"), "validate_pr.py": ("resolve/review.py", "core/gitclone.py"), "refresh_data_dirs.py": ("packs/datadirs.py",), "split_pack.py": ("packs/parts.py",), diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 180fb4c18..5c0692719 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -572,7 +572,7 @@ class VerboseAppliesToJson(unittest.TestCase): def test_every_json_branch_reads_the_flag(self): source = script_source("verify.py") - self.assertEqual(source.count("_json_details("), 4) + self.assertEqual(source.count("json_details("), 4) self.assertNotIn('if d["status"] != Status.OK\n ]', source) @@ -5391,7 +5391,7 @@ class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase): say which platform carried it.""" def test_counts_carry_platforms_and_core_misses(self): - import verify + from packs import verifysummary from packs import verdicts clean = {"severity_counts": {}, "undeclared_files": []} @@ -5403,7 +5403,7 @@ class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase): "category": "bios", "in_pack": True, }], } - summary = verify._overall_summary( + summary = verifysummary.overall_summary( [(clean, ["RetroArch"]), (warned, ["RetroDECK"]), (core_miss, ["ROCKNIX"])] ) self.assertIn("1 warning (RetroDECK 1)", summary) @@ -5413,7 +5413,7 @@ class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase): def test_a_file_missing_on_several_platforms_is_counted_once(self): """sfiii2a.zip missing on 15 platforms read '24 core file(s)' for 10 distinct files, the name printed 15 times on one line.""" - import verify + from packs import verifysummary def missing(*names: str) -> dict: return {"severity_counts": {}, "undeclared_files": [ @@ -5421,7 +5421,7 @@ class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase): "category": "bios", "in_pack": True} for name in names ]} - summary = verify._overall_summary([ + summary = verifysummary.overall_summary([ (missing("sfiii2a.zip"), ["Batocera"]), (missing("sfiii2a.zip", "ROM"), ["RetroPie"]), (missing("sfiii2a.zip"), ["RomM"]), @@ -5462,13 +5462,13 @@ class BundledFilesAreNotToSource(unittest.TestCase): listed among the files to source, with 19 more like it.""" def test_verify_does_not_count_it_missing(self): - import verify + from packs import verifysummary from packs import report as packs_report entry = {"name": "n64.psh", "required": True, "in_repo": False, "category": "bios", "in_pack": True, "bundled": True} self.assertEqual(packs_report.core_required_missing([entry]), []) - summary = verify._overall_summary( + summary = verifysummary.overall_summary( [({"severity_counts": {}, "undeclared_files": [entry]}, ["ROCKNIX"])] ) self.assertNotIn("n64.psh", summary) @@ -6391,13 +6391,13 @@ class StrictFailsOnMissingOnly(unittest.TestCase): but a rejected file is UNTESTED, a warning, and --strict never saw it.""" def test_the_contract(self): - from scripts import verify as verify_mod + from scripts.packs.strictgate import platform_strict_failure from scripts.packs.verdicts import Severity - verify_mod._exit_if_strict(True, [{"severity_counts": {Severity.WARNING: 2}}]) - with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()): - verify_mod._exit_if_strict(True, [{"severity_counts": {Severity.CRITICAL: 1}}]) - self.assertNotIn("or rejected", verify_mod._exit_if_strict.__doc__) + self.assertIsNone(platform_strict_failure([{"severity_counts": {Severity.WARNING: 2}}])) + self.assertIsNotNone( + platform_strict_failure([{"severity_counts": {Severity.CRITICAL: 1}}])) + self.assertNotIn("or rejected", platform_strict_failure.__doc__) class TheRepairCommandWritesTheFileNamed(unittest.TestCase): @@ -6465,7 +6465,7 @@ class AHashScanningCoreContradictsNoPlatform(unittest.TestCase): def test_no_conflict_names_ares(self): import json - from scripts import slots + from scripts.packs import slotscan from scripts.model.registry import list_registered_platforms from scripts.model.profiles import load_emulator_profiles @@ -6477,7 +6477,7 @@ class AHashScanningCoreContradictsNoPlatform(unittest.TestCase): claimed = [ (platform, conflict.destination) for platform in list_registered_platforms(str(root / "platforms")) - for conflict in slots.scan_platform(platform, profiles, db, str(root / "platforms")) + for conflict in slotscan.scan_platform(platform, profiles, db, str(root / "platforms")) if any(claim.emulator == "ares" for claim in conflict.profile_claims) ] self.assertEqual(claimed, []) diff --git a/tests/test_cross_reference_sources.py b/tests/test_cross_reference_sources.py index 8fa2aee3f..d872ab6a6 100644 --- a/tests/test_cross_reference_sources.py +++ b/tests/test_cross_reference_sources.py @@ -17,7 +17,7 @@ import unittest from pathlib import Path from packs.crossref import build_supplemental_index, cross_reference, entry_source -from cross_reference import print_report +from packs.crossreftext import print_report REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_e2e.py b/tests/test_e2e.py index b45dcd80b..eeb0ee142 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -6896,15 +6896,14 @@ class OneOfASearchList(unittest.TestCase): """second.bin used to read required: false beside a required first.bin: the set is required and held, so nothing is critical for it, and the strict exit names only the set nobody holds.""" - from verify import _exit_if_strict_emulator + from packs.strictgate import emulator_strict_failure result = self._verify() critical = [d["name"] for d in result["details"] if d["status"] == "missing" and d["required"]] self.assertEqual(critical, ["none_a.bin"]) - with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()) as err: - _exit_if_strict_emulator(True, result) - self.assertIn("1 required file(s) missing: none_a.bin", err.getvalue()) + self.assertIn("1 required file(s) missing: none_a.bin", + emulator_strict_failure(result) or "") def test_pack_and_verify_agree(self): from packs.emulatorpack import generate_emulator_pack diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index f7f564d98..621fdbe38 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -27,12 +27,13 @@ from unittest import mock import yaml -import verify from packs import coverage from packs import report as packs_report from model.profiles import emulator_profiles_cache, load_emulator_profiles from model.platforms import load_platform_config -from cross_reference import LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, print_launcher_reads +from packs.crossreflaunchers import LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY +from packs.crossreftext import print_launcher_reads +from packs.strictgate import platform_strict_failure from packs.crossref import launcher_file_names, launcher_reads_not_held ROOT = Path(__file__).resolve().parent.parent @@ -298,16 +299,10 @@ class LauncherGapTest(unittest.TestCase): {"absent.bin", "mixed.rom", "labelled.rom", "user.sf2"}) self.assertEqual(with_rows, without) - def exit_code(result: dict) -> int: - try: - with contextlib.redirect_stderr(io.StringIO()): - verify._exit_if_strict(True, [result]) - except SystemExit as exc: - return int(exc.code or 0) - return 0 - - self.assertEqual(exit_code({**with_rows, "launcher_reads_not_held": rows}), - exit_code(without)) + self.assertEqual( + platform_strict_failure([{**with_rows, "launcher_reads_not_held": rows}]), + platform_strict_failure([without]), + ) def test_verify_prints_a_count_and_lists_on_verbose(self) -> None: result = coverage.verify_platform( diff --git a/tests/test_slots.py b/tests/test_slots.py index 028ea269c..88efa94c0 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -4,6 +4,7 @@ from __future__ import annotations import tests +import inspect import os import re import shutil @@ -12,11 +13,11 @@ import tempfile import unittest from pathlib import Path -import slots +from packs import slotreport from packs import slots as packs_slots from resolve import collisions as resolve_collisions from packs.slots import Claim, Conflict, arbitrate -from slots import format_decision +from packs.slotreport import format_decision from tests.sources import script_source @@ -346,7 +347,7 @@ class TestConflicts(unittest.TestCase): conflicts = packs_slots.find_conflicts( self._config("m" * 32), self._profile("GC/JAP/IPL.bin"), REGIONS_DB ) - line = slots.format_conflict(conflicts[0]) + line = slotreport.format_conflict(conflicts[0]) self.assertIn("USA/IPL.bin", line) self.assertIn("JAP/IPL.bin", line) self.assertIn("dolphin", line) @@ -443,12 +444,12 @@ class TestArbitration(unittest.TestCase): self.assertEqual(served, decision.winner.local_path) def test_the_reported_line_gives_the_ground_for_the_decision(self): - kept = slots.format_decision(packs_slots.arbitrate(self._conflict(), "md5")) + kept = slotreport.format_decision(packs_slots.arbitrate(self._conflict(), "md5")) self.assertIn("verifies content", kept) # A fact about each layer, no verdict on the platform's list. self.assertIn("the file dolphin reads", kept) - self.assertNotIn("wrong", slots.__loader__.get_source("slots").lower()) - served = slots.format_decision(packs_slots.arbitrate(self._conflict(), "existence")) + self.assertNotIn("wrong", inspect.getsource(slotreport).lower()) + served = slotreport.format_decision(packs_slots.arbitrate(self._conflict(), "existence")) self.assertIn("both are satisfied", served) def test_each_emulator_is_given_the_file_it_reads(self): @@ -461,7 +462,7 @@ class TestArbitration(unittest.TestCase): packs_slots.Claim("profile", "neocdz.zip", "neocdz.zip", emulator="geolith", local_path="b/neocdz.zip.712816a3", status="md5_exact"), ] - kept = slots.format_decision(packs_slots.arbitrate(conflict, "md5")) + kept = slotreport.format_decision(packs_slots.arbitrate(conflict, "md5")) self.assertIn("a/neocdz.zip.ba20a7be, the file fbneo reads", kept) self.assertIn("b/neocdz.zip.712816a3, the file geolith reads", kept) self.assertEqual(conflict.files_read(), [ @@ -510,7 +511,7 @@ class TestBuilderAndVerifierAgree(unittest.TestCase): self.assertNotIn("decision.serves_both", text, source.name) self.assertIn( "decision.serves_both", - (scripts / "slots.py").read_text(encoding="utf-8"), + (scripts / "packs" / "slotreport.py").read_text(encoding="utf-8"), ) def test_neither_reimplements_the_mode_test(self): @@ -554,7 +555,7 @@ class TestSelfContradictingDestinations(unittest.TestCase): "md5": "n" * 32}]}, }} collision = resolve_collisions.find_collisions(config, REGIONS_DB)[0] - line = slots.format_collision(collision) + line = slotreport.format_collision(collision) left, packed = collision.resolved # The builder walks the systems sorted: alpha's declaration ships. self.assertIn(f"{packed} (alpha) packed", line) @@ -633,7 +634,7 @@ class TestSelfContradictingDestinations(unittest.TestCase): {"name": "IPL.bin", "destination": "disk.rom", "md5": "m" * 32}, {"name": "IPL.bin", "destination": "disk.rom", "md5": "n" * 32}, ) - line = slots.format_collision(resolve_collisions.find_collisions(config, REGIONS_DB)[0]) + line = slotreport.format_collision(resolve_collisions.find_collisions(config, REGIONS_DB)[0]) self.assertIn("USA/IPL.bin", line) self.assertIn("JAP/IPL.bin", line) diff --git a/tests/test_target_verify.py b/tests/test_target_verify.py index c49074a53..1b3eaaf67 100644 --- a/tests/test_target_verify.py +++ b/tests/test_target_verify.py @@ -222,9 +222,7 @@ class CrossReferenceReadsTheTargetAcrossPlatforms(unittest.TestCase): each narrowed to the cores it builds for it.""" def test_the_scope_is_the_union_of_each_platforms_target_cores(self): - import argparse - - import cross_reference + from packs.crossrefscope import tree_scope from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from model.registry import list_registered_platforms @@ -232,9 +230,8 @@ class CrossReferenceReadsTheTargetAcrossPlatforms(unittest.TestCase): platforms_dir = str(REPO_ROOT / "platforms") profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) - args = argparse.Namespace(platform=None, target="switch", platforms_dir=platforms_dir) with contextlib.redirect_stderr(io.StringIO()): - tree = cross_reference._tree_scope(args, profiles) + tree = tree_scope(None, "switch", platforms_dir, profiles) cache, kept = build_target_cores_cache( list_registered_platforms(platforms_dir), "switch", platforms_dir, is_all=True, ) diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index d6dbc7e46..38786dafa 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -24,10 +24,10 @@ import diff_truth import pipeline from orchestrate import guards, labels, prepare, runner from resolve import truth -import verify from packs import coverage from packs import report as packs_report from packs import verdicts +from packs import verifysummary from tests.sources import script_source REPO_ROOT = Path(__file__).resolve().parents[1] @@ -527,7 +527,7 @@ class TheVerifySummaryCountsDiscrepancies(unittest.TestCase): "discrepancy": "unmet"}, {"system": "arcade", "name": "x.zip", "status": verdicts.Status.MISSING}, ] - summary = verify._overall_summary([ + summary = verifysummary.overall_summary([ ({"severity_counts": {}, "details": details}, ["RetroArch"]), ({"severity_counts": {}, "details": []}, ["Batocera"]), ]) @@ -552,7 +552,7 @@ class EveryPlatformInTheSummaryCarriesItsCount(unittest.TestCase): def test_a_count_of_one_is_written(self): one = {"severity_counts": {verdicts.Severity.WARNING: 1}, "details": []} two = {"severity_counts": {verdicts.Severity.WARNING: 2}, "details": []} - summary = verify._overall_summary([(two, ["Lakka"]), (one, ["ROCKNIX"])]) + summary = verifysummary.overall_summary([(two, ["Lakka"]), (one, ["ROCKNIX"])]) self.assertIn("3 warning (Lakka 2, ROCKNIX 1)", summary)