From 4d62c56730bf168c798c9529eb02c141aa31a641 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:19:27 +0100 Subject: [PATCH] feat: cross_reference --all --target --target without --platform keeps every platform with the target, each narrowed to the cores it builds for it, as verify and generate_pack read --all --target. --all is accepted as the explicit whole-tree scope. Remaining CLI plurals go through count_text ("1 name", "+1 record"). --- scripts/cross_reference.py | 151 ++++++++++++++++++++++--------- scripts/download.py | 3 +- scripts/packs/report.py | 3 +- scripts/sitegen/emulatorcards.py | 2 +- tests/test_launcher_gaps.py | 2 +- tests/test_target_verify.py | 53 +++++++++++ wiki/tools.md | 4 + 7 files changed, 172 insertions(+), 46 deletions(-) diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index 5a998bd65..e3219cb41 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -8,6 +8,8 @@ Usage: python scripts/cross_reference.py python scripts/cross_reference.py --emulator dolphin python scripts/cross_reference.py --json + python scripts/cross_reference.py --platform retroarch --target switch + python scripts/cross_reference.py --all --target switch """ from __future__ import annotations @@ -20,6 +22,7 @@ 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 @@ -60,8 +63,7 @@ def print_launcher_unproven(rows: list[dict]) -> None: if not rows: return platforms = sorted({r["platform"] for r in rows}) - noun = "platform" if len(platforms) == 1 else "platforms" - print(f"\nLauncher records unproven: {len(rows)} across {len(platforms)} {noun}") + 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): @@ -79,13 +81,13 @@ def print_launcher_reads(rows: list[dict]) -> None: 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}) - noun = "platform" if len(platforms) == 1 else "platforms" - print(f"\nLauncher reads, not held: {len(rows)} names across {len(platforms)} {noun}") + 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" (+{len(row['readers']) - 1} records)" if len(row["readers"]) > 1 else "" + 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']}, " @@ -94,10 +96,9 @@ def print_launcher_reads(rows: list[dict]) -> None: if not unsourceable: return platforms = sorted({r["platform"] for r in unsourceable}) - noun = "platform" if len(platforms) == 1 else "platforms" print( - f"\nLauncher reads, unsourceable: {len(unsourceable)} names " - f"across {len(platforms)} {noun}" + f"\nLauncher reads, unsourceable: {count_text(len(unsourceable), 'name')} " + f"across {count_text(len(platforms), 'platform')}" ) for row in unsourceable: print( @@ -187,7 +188,15 @@ def _build_parser() -> argparse.ArgumentParser: parser.add_argument( "--platform", "-p", type=platform_arg, help="Restrict analysis to one platform's cores" ) - parser.add_argument("--target", "-t", help="Hardware target (e.g., switch, rpi4)") + parser.add_argument( + "--all", action="store_true", + help="Analyze the emulators every platform runs (the default without --platform)", + ) + parser.add_argument( + "--target", "-t", + help="Hardware target (e.g., switch, rpi4): with --platform, the cores built " + "for it there, otherwise the cores each platform with the target builds for it", + ) parser.add_argument("--json", action="store_true", help="JSON output") parser.add_argument( "--list-emulators", action="store_true", help="List available emulators" @@ -229,6 +238,86 @@ def _platform_scope(args: argparse.Namespace, profiles: dict[str, dict]) -> _Pla ) +@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: + """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 + and emulator in platform_scope.run_anywhere): + raise SystemExit( + f"ERROR: {emulator} is not built for {args.platform}'s " + f"{args.target} target; {args.platform} runs it elsewhere " + f"(drop --target to see its files)" + ) + if emulator and args.platform: + raise SystemExit(f"ERROR: {emulator} is not run by {args.platform}") + if emulator: + raise SystemExit( + f"ERROR: no platform with the {args.target} target builds {emulator} " + f"for it (drop --target to see its files)" + ) + if args.target and not args.platform: + print(f"No platform runs a profiled emulator on {args.target}.", file=sys.stderr) + else: + print(f"{args.platform or 'The tree'} runs no profiled emulator.", file=sys.stderr) + + def _launcher_rows( args: argparse.Namespace, selected: list[str] | None, @@ -274,12 +363,14 @@ def main() -> None: if args.list_emulators: ignored = [flag for flag, on in ( ("--emulator", args.emulator), ("--platform", args.platform), - ("--target", args.target), ("--json", args.json), + ("--all", args.all), ("--target", args.target), ("--json", args.json), ) if on] if ignored: parser.error(f"--list-emulators does not apply {', '.join(ignored)}") list_emulator_profiles(args.emulators_dir) return + if args.platform and args.all: + parser.error("--platform and --all are mutually exclusive") if args.platform: require_platform(args.platform, args.platforms_dir) @@ -308,44 +399,18 @@ def main() -> None: raise SystemExit(f"ERROR: {exc}") from None profiles = {k: v for k, v in profiles.items() if k == emulator} - if args.target and not args.platform: - parser.error("--target requires --platform") - - platform_scope: _PlatformScope | None = None - standalone_cores: set[str] = set() - if args.platform: - platform_scope = _platform_scope(args, profiles) - profiles = platform_scope.profiles - standalone_cores = platform_scope.standalone_cores - else: - # 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 - - standalone_cores = merged_standalone_set( - load_platform_config(name, args.platforms_dir) - for name in list_registered_platforms(args.platforms_dir) - ) - + tree = _tree_scope(args, profiles) + profiles = tree.profiles + platform_scope = tree.platform if not profiles: - if (emulator and args.target and platform_scope is not None - and emulator in platform_scope.run_anywhere): - raise SystemExit( - f"ERROR: {emulator} is not built for {args.platform}'s " - f"{args.target} target; {args.platform} runs it elsewhere " - f"(drop --target to see its files)" - ) - if emulator: - raise SystemExit(f"ERROR: {emulator} is not run by {args.platform}") - print(f"{args.platform or 'The tree'} runs no profiled emulator.", file=sys.stderr) + _refuse_empty_scope(args, emulator, tree) return - selected = [args.platform] if args.platform else None + 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"] = standalone_cores + global_scope["standalone_cores"] = tree.standalone_cores data_names = build_supplemental_index() report = cross_reference( profiles, declared, db, data_names, **global_scope, @@ -373,6 +438,8 @@ def main() -> None: scope = emulator elif args.platform: scope = f"the emulators {args.platform} runs" + elif args.target: + scope = f"the emulators built for {args.target}" else: scope = "all emulators" print_report(report, scope, show_clean=bool(args.emulator)) diff --git a/scripts/download.py b/scripts/download.py index 0eb58be40..f73a45130 100644 --- a/scripts/download.py +++ b/scripts/download.py @@ -35,6 +35,7 @@ sys.path.insert(0, os.path.dirname(__file__)) from core.hashing import compute_hashes, parse_sha256sums from core.paths import REPO_ROOT from core.sizes import size_text +from core.text import count_text from core.upstream import UpstreamError, forge_headers, open_retrying from core.ziptools import safe_extract_zip from packs.parts import part_of @@ -337,7 +338,7 @@ def show_info(platform: str, release: dict) -> None: print(f" Platform: {pack.platform}") print(f" File: {pack.name}") - print(f" Parts: {len(pack.parts)} part{'s' if len(pack.parts) > 1 else ''}") + print(f" Parts: {count_text(len(pack.parts), 'part')}") print(f" Size: {pack.size:,} bytes ({size_text(pack.size)})") for part in pack.parts: print(f" {part['name']} ({part.get('size', 0):,} bytes)") diff --git a/scripts/packs/report.py b/scripts/packs/report.py index 97f13df76..d097d6fd2 100644 --- a/scripts/packs/report.py +++ b/scripts/packs/report.py @@ -4,6 +4,7 @@ from __future__ import annotations from collections import Counter +from core.text import count_text from packs.verdicts import Severity, Status from resolve.categories import BIOS from resolve.nativemode import reads_file_contents @@ -205,7 +206,7 @@ def _print_undeclared_entry( name = u["path"] if u["name"] in repeated and u.get("path") else u["name"] arc_count = u.get("archive_file_count") if arc_count: - name_label = f"{name} ({arc_count} file{'s' if arc_count != 1 else ''})" + name_label = f"{name} ({count_text(arc_count, 'file')})" else: name_label = name if u.get("alternatives") and not u.get("in_repo"): diff --git a/scripts/sitegen/emulatorcards.py b/scripts/sitegen/emulatorcards.py index 407691807..6f12b4cb0 100644 --- a/scripts/sitegen/emulatorcards.py +++ b/scripts/sitegen/emulatorcards.py @@ -884,7 +884,7 @@ def _version_said(value: object, basis: dict, profile: dict, mode: str = "") -> distance = int(basis.get("distance") or 0) if not distance: return f"{value}, the tag at this revision" - return f"{value}, {distance} commit{'s' if distance != 1 else ''} after tag {shown(basis.get('tag'))}" + return f"{value}, {count_text(distance, 'commit')} after tag {shown(basis.get('tag'))}" if kind == "package": return f"{value}, read from {basis.get('artifact')}" if kind == "unverified": diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index e82aeb77d..f7f564d98 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -208,7 +208,7 @@ class LauncherGapTest(unittest.TestCase): print_launcher_reads(list(self._rows().values())) text = out.getvalue() self.assertIn("Launcher reads, not held: 3 names", text) - self.assertIn("Launcher reads, unsourceable: 1 names across 1 platform", text) + self.assertIn("Launcher reads, unsourceable: 1 name across 1 platform", text) self.assertIn("gaptest: user.sf2 [setemu, gen/setemu.py:1]: user supplied, no canonical file", text) held_part = text.split("Launcher reads, unsourceable")[0] diff --git a/tests/test_target_verify.py b/tests/test_target_verify.py index 154ef08ea..d47b1325f 100644 --- a/tests/test_target_verify.py +++ b/tests/test_target_verify.py @@ -213,6 +213,59 @@ class APlatformWithoutTheSystemIsOutOfScope(unittest.TestCase): self.assertNotIn("misterfpga", report) +class CrossReferenceReadsTheTargetAcrossPlatforms(unittest.TestCase): + """cross_reference refused --target without --platform, where verify and + generate_pack read --all --target as every platform with the target, + 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 model.platforms import load_platform_config + from model.profiles import load_emulator_profiles + from model.registry import list_registered_platforms + from resolve.cores import resolve_platform_cores + + 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) + cache, kept = build_target_cores_cache( + list_registered_platforms(platforms_dir), "switch", platforms_dir, is_all=True, + ) + self.assertEqual(tree.selected, kept) + self.assertIsNone(tree.platform) + expected: set[str] = set() + for name in kept: + expected |= set(resolve_platform_cores( + load_platform_config(name, platforms_dir), profiles, target_cores=cache[name], + )) + self.assertEqual(set(tree.profiles), expected) + self.assertLess(len(tree.profiles), len(profiles)) + + def test_the_command_line(self): + import json + import subprocess + + def run(*argv: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, "scripts/cross_reference.py", *argv], + cwd=REPO_ROOT, capture_output=True, text=True, check=False, timeout=600, + ) + + proc = run("--all", "--target", "switch", "--emulator", "snes9x", "--json") + self.assertEqual(proc.returncode, 0, proc.stderr[-500:]) + self.assertIn("snes9x", json.loads(proc.stdout)) + proc = run("--target", "switch", "--emulator", "xemu") + self.assertEqual(proc.returncode, 1, proc.stderr[-500:]) + self.assertIn("no platform with the switch target builds xemu", proc.stderr) + proc = run("--all", "--target", "swtich") + self.assertEqual(proc.returncode, 1, proc.stderr[-500:]) + self.assertIn("Close matches: switch", proc.stderr) + + class TheSplitDirectoryReadsThePackStem(unittest.TestCase): """The split prefix was assembled by hand: a version 'release/1.22' made 'RetroArch_release/1.22_Split', a nested directory the check never diff --git a/wiki/tools.md b/wiki/tools.md index 851c9cc07..83cabc8e7 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -321,8 +321,12 @@ python scripts/cross_reference.py --emulator dolphin # single python scripts/cross_reference.py --emulator dolphin --json # JSON output python scripts/cross_reference.py --platform batocera # single platform python scripts/cross_reference.py --platform retroarch --target switch +python scripts/cross_reference.py --all --target switch # every platform with the target ``` +Without `--platform`, `--target` keeps each platform that has the target, +narrowed to the cores it builds for it, as `verify.py --all --target` does. + ### truth.py, generate_truth.py, diff_truth.py Generate ground truth from emulator profiles, diff against scraped platform data.