From a1b8a10cf952229ea1522f006de3f8292d9f320f Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:11:48 +0100 Subject: [PATCH] refactor: move generate_pack runs into packs --- scripts/generate_pack.py | 781 ++-------------------------- scripts/packs/manifestrun.py | 152 ++++++ scripts/packs/outputdir.py | 67 +++ scripts/packs/packcheck.py | 182 +++++++ scripts/packs/platformrun.py | 334 ++++++++++++ scripts/packs/variants.py | 63 +++ tests/sources.py | 3 +- tests/test_audit_regressions.py | 4 +- tests/test_pack_conformance_dirs.py | 8 +- tests/test_pack_failures.py | 20 +- tests/test_release_packs.py | 6 +- tests/test_target_verify.py | 5 +- tests/test_verify_pack_choice.py | 29 +- 13 files changed, 866 insertions(+), 788 deletions(-) create mode 100644 scripts/packs/manifestrun.py create mode 100644 scripts/packs/outputdir.py create mode 100644 scripts/packs/packcheck.py create mode 100644 scripts/packs/platformrun.py create mode 100644 scripts/packs/variants.py diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index adb274722..af806883f 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -19,20 +19,14 @@ import sys if sys.version_info < (3, 9): sys.exit(f"generate_pack.py needs Python 3.9 or newer, this is {sys.version.split()[0]}") -from collections.abc import Iterator - import argparse import contextlib -import json import os -from pathlib import Path -from dataclasses import dataclass sys.path.insert(0, os.path.dirname(__file__)) -from resolve.cores import resolve_platform_cores as _platform_cores -from model.profiles import ( - load_emulator_profiles, -) +from core.artifacts import ArtifactLockBusy +from core.cli import add_emulator_selection, add_repo_inputs, require_directory +from core.ziptools import build_zip_contents_index from model.cliargs import ( LISTING_FLAGS, comma_list, @@ -44,115 +38,32 @@ from model.cliargs import ( resolve_system_ids, run_listing, ) -from core.cli import add_emulator_selection, add_repo_inputs, require_directory -from model.targets import ( - target_scope, -) -from core.artifacts import ( - write_if_changed, - artifact_lock, - repository_output_lock, - ArtifactLockBusy, -) -from core.ziptools import build_zip_contents_index -from core.text import count_text -from resolve.cores import ( - platforms_with_systems, - without_profile_blind, -) -from resolve.grouping import group_identical_platforms +from model.database import load_database from model.registry import ( list_registered_platforms, list_release_pack_platforms, load_data_dir_registry, - load_platform_registry, ) -from model.database import load_database -from model.platforms import load_platform_config -from model.safeparse import require_yaml -from resolve import packfiles as packresolve -from packs.datadirs import hold_data_dirs - -from packs.integrity import verify_pack_against_platform -from resolve.packfiles import ( - ACCEPTED_HASHES, - parse_hash_input, - parse_hash_file, - lookup_hashes, -) - from packs.archive import DamagedArchiveError -from packs.platformpack import generate_split_packs +from packs.datadirs import hold_data_dirs from packs.datatrees import MISSING_DATA_DIRS from packs.emulatorpack import generate_emulator_pack, generate_system_pack -from packs.finalize import baseline_shortfall, verify_and_finalize_packs -from packs.manifest import generate_install_list, generate_manifest from packs.md5pack import generate_md5_pack -from packs.naming import ( - expected_pack_names, - pack_narrowings, - pack_variant, - platform_pack_name, - platform_target, +from packs.outputdir import holds_other_kind, pack_output_lock +from packs.packcheck import run_verify_packs +from packs.platformrun import run_platform_mode +from packs.targets import generate_target_manifests +from resolve import packfiles as packresolve +from resolve.packfiles import ( + ACCEPTED_HASHES, + lookup_hashes, + parse_hash_file, + parse_hash_input, ) -from packs.platformpack import generate_pack -from packs.scope import pack_systems, platform_list_version -from packs.standalone import STANDALONE_DIR, standalone_copies -from packs.targets import generate_target_manifests, target_list - - -yaml = require_yaml() DEFAULT_OUTPUT_DIR = "dist" -def _json_artifact_kind(path: Path) -> str | None: - """"manifest" for an install manifest, "targets" for a per-target core - list, None for anything else. The two share their file names: install.py - fetches install/.json and install/targets/.json.""" - try: - data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, UnicodeDecodeError, json.JSONDecodeError): - return None - if not isinstance(data, dict) or not data: - return None - if "manifest_version" in data: - return "manifest" - if all(v is None or isinstance(v, list) for v in data.values()): - return "targets" - return None - - -def _refuse_mixed_output(output_dir: str, writing: str) -> None: - """Stop before one kind of installer JSON overwrites the other. - - Both are named .json, so --manifest-targets aimed at install/ - replaced install/retroarch.json, the file every installer downloads, with - a target table, and the reverse replaced a target list by a manifest. - """ - directory = Path(output_dir) - if not directory.is_dir(): - return - other = "targets" if writing == "manifest" else "manifest" - held = sorted( - p.name for p in directory.glob("*.json") if _json_artifact_kind(p) == other - ) - if not held: - return - what = { - "manifest": "install manifests (install/ in the repository)", - "targets": "per-target core lists (install/targets/ in the repository)", - } - flag = "--manifest" if writing == "manifest" else "--manifest-targets" - print( - f"ERROR: {output_dir} holds {what[other]}: {', '.join(held[:3])}" - f"{', ...' if len(held) > 3 else ''}. {flag} writes {what[writing]} under the " - f"same file names; pass the --output-dir that holds those instead.", - file=sys.stderr, - ) - sys.exit(1) - - def _refuse_for_verify_packs(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: """What --verify-packs cannot be combined with, refused before any lock. @@ -233,544 +144,6 @@ def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> parser.error(message) -def _run_manifest_mode( - args: argparse.Namespace, - groups: list[tuple[list[str], str]], - db: dict, - zip_contents: dict, - emu_profiles: dict, - target_cores_cache: dict[str, set[str] | None], -) -> None: - """Generate JSON manifests instead of ZIP packs.""" - registry_path = os.path.join(args.platforms_dir, "_registry.yml") - os.makedirs(args.output_dir, exist_ok=True) - platform_registry = load_platform_registry(args.platforms_dir) - - variants = ALL_VARIANTS if args.all_variants else ((args.source, args.required_only),) - - failed: list[str] = [] - for source, required_only in variants: - for group_platforms, representative in groups: - print(f"\nGenerating manifest for {representative} [source={source}]...") - tc = target_cores_cache.get(representative) if args.target else None - if _skip_empty_truth(args, source, representative, emu_profiles, tc, failed): - continue - layouts: dict = {} - try: - manifest = generate_install_list( - representative, - args.platforms_dir, - db, - args.bios_dir, - registry_path, - emulators_dir=args.emulators_dir, - zip_contents=zip_contents, - emu_profiles=emu_profiles, - target_cores=tc, - source=source, - regions=getattr(args, "regions", None), - target_name=platform_target( - representative, args.target, args.platforms_dir - ), - offline=args.offline, - required_only=required_only, - no_game_data=getattr(args, "no_game_data", False), - standalone_out=layouts, - ) - narrow_suffix = "".join( - tag.lower() - for tag, _label in pack_narrowings( - source, - getattr(args, "regions", None), - platform_target(representative, args.target, args.platforms_dir), - False, - required_only, - no_game_data=getattr(args, "no_game_data", False), - ) - ) - out_path = os.path.join( - args.output_dir, - f"{representative}{narrow_suffix}.json", - ) - write_if_changed(out_path, json.dumps(manifest, indent=2)) - print( - f" {out_path}: {manifest['total_files']} files, " - f"{manifest['total_size']} bytes, " - f"{manifest['total_omitted']} safely omitted" - ) - for plat in group_platforms if layouts else (): - print(f" {_write_standalone_layouts(args.output_dir, plat, layouts)}: " - f"{len(layouts)} standalone builds") - # Create aliases for grouped platforms (e.g., lakka -> retroarch) - for alias_plat in group_platforms: - if alias_plat != representative: - alias_path = os.path.join( - args.output_dir, - f"{alias_plat}{narrow_suffix}.json", - ) - alias_manifest = dict(manifest) - alias_manifest["platform"] = alias_plat - alias_cfg = load_platform_config(alias_plat, args.platforms_dir) - alias_manifest["display_name"] = alias_cfg.get( - "platform", alias_plat - ) - alias_manifest["version"] = platform_list_version( - alias_cfg, alias_plat - ) - alias_manifest["base_destination"] = alias_cfg.get( - "base_destination", "" - ) - alias_registry = platform_registry.get(alias_plat, {}) - alias_install = alias_registry.get("install", {}) - alias_manifest["detect"] = alias_install.get("detect", []) - # Placed and completed as the representative's are: - # copied raw, an alias's copies named no source. - alias_manifest["standalone_copies"] = standalone_copies( - alias_install.get("standalone_copies", []), - {name: emu_profiles[name] - for name in _platform_cores(alias_cfg, emu_profiles)}, - manifest["files"], - ) - write_if_changed(alias_path, json.dumps(alias_manifest, indent=2)) - print(f" {alias_path}: alias of {representative}") - except (FileNotFoundError, OSError, yaml.YAMLError) as e: - print(f" ERROR: {e}", file=sys.stderr) - failed.append(representative) - - # A platform whose manifest could not be built has none, and install.py - # serves whatever an older run left there: that is a failed run. - if failed: - print(f"ERROR: no manifest for {', '.join(sorted(set(failed)))}", file=sys.stderr) - sys.exit(1) - - -@contextlib.contextmanager -def _pack_output_lock(output_dir: str, exclusive: bool = True) -> Iterator[None]: - """Hold the output directory for the duration of a pack run, and the - repository's fixed outputs when it is one of them (install/).""" - try: - with artifact_lock(output_dir, exclusive=exclusive), \ - repository_output_lock(output_dir) if exclusive else contextlib.nullcontext(): - yield - except ArtifactLockBusy as exc: - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) - - -@dataclass(frozen=True) -class _PackCheck: - """What --verify-packs checks every pack against.""" - - db: dict - platforms_dir: str - emulators_dir: str - profiles: dict - regions: list[str] | None - data_registry: dict - no_game_data: bool - - -def _verify_packs_scope(args: argparse.Namespace) -> tuple[list[str], dict[str, set[str] | None]]: - """The platforms --verify-packs checks, and the cores of the target.""" - if args.platform: - platforms = [args.platform] - elif args.all: - # The packs --all builds: a platform without release_pack has no pack - # to check, and its absence from the directory is no failure. - platforms = list_release_pack_platforms(args.platforms_dir) - else: - raise ValueError("--verify-packs requires --platform or --all") - - # The target is checked as the build checks it: a mistyped one, or one - # the platform does not publish, was dropped and the full pack verified - # under it, `all OK` for a pack no build had made. - target_cores_cache, platforms = target_scope( - platforms, args.target, args.platforms_dir, is_all=args.all - ) - return platforms, target_cores_cache - - -def _run_verify_packs(args: argparse.Namespace) -> None: - """Verify each pack in the output directory against its platform. - - Delegates to verify_pack_against_platform so the command answers the same - question the pipeline asks: baseline files, core extras and structure. A - second implementation here answered a narrower one and reported OK while - the core extras went unchecked. - """ - verify_db = load_database(args.db) - platforms, target_cores_cache = _verify_packs_scope(args) - - all_ok = True - check = _PackCheck( - verify_db, args.platforms_dir, args.emulators_dir, - load_emulator_profiles(args.emulators_dir), getattr(args, "regions", None), - load_data_dir_registry(args.platforms_dir), getattr(args, "no_game_data", False), - ) - # After an --all-variants build every variant is named, so none of the - # six packs the run wrote passes unmentioned. - expected = expected_pack_names( - platforms, - args.platforms_dir, - check.regions, - args.target, - ALL_VARIANTS if args.all_variants else (("full", False),), - no_game_data=check.no_game_data, - ) - on_disk = ( - set(os.listdir(args.output_dir)) if os.path.isdir(args.output_dir) else set() - ) - - verified = 0 - failing: list[str] = [] - for platform_name in platforms: - found = sorted(expected[platform_name] & on_disk) - verified += len(found) - if not found: - # Naming a platform is asking about its pack: FAIL, with the - # command that builds it. With --all, a platform whose pack was - # not built is out of scope and skipped. - if args.platform: - print( - f" {platform_name}: FAIL (no pack in {args.output_dir}; build it with " - f"python scripts/generate_pack.py --platform {platform_name} " - f"--output-dir {args.output_dir})" - ) - all_ok = False - failing.append(f"{platform_name} (no pack)") - else: - print(f" {platform_name}: SKIP (no pack in {args.output_dir})") - continue - tc = target_cores_cache.get(platform_name) - # A group pack and a pack built for the platform alone can both be - # present, and each one is a pack of this platform. - for pack_name in found: - variant = pack_variant(pack_name) - if variant is None: - # One BIOS per slot: the slot choice is not replayed here. - print( - f" {platform_name} [{pack_name}]: hashes checked during the build; " - "one per slot by design, so not compared to the platform's full list" - ) - continue - source, required_only = variant - zip_path = os.path.join(args.output_dir, pack_name) - result = verify_pack_against_platform( - zip_path, - platform_name, - check.platforms_dir, - db=check.db, - emulators_dir=check.emulators_dir, - emu_profiles=check.profiles, - regions=check.regions, - data_registry=check.data_registry, - target_cores=tc, - source=source, - required_only=required_only, - no_game_data=check.no_game_data, - ) - (ok, _checked, _present, errors, bl_checked, bl_present, - core_checked, core_present, bl_excluded, bl_absent) = result - # These explain a baseline short of its total: a dump whose hash - # the frontend refuses is left out on purpose, and a file the - # collection does not hold cannot be packed (verify reports it). - shortfall = ", ".join(baseline_shortfall(bl_excluded, bl_absent)) - excluded = f" ({shortfall})" if shortfall else "" - counts = ( - f"{bl_present}/{bl_checked} baseline{excluded}, " - f"{core_present}/{core_checked} cores" - ) - if ok: - print(f" {platform_name} [{pack_name}]: OK ({counts})") - else: - print(f" {platform_name} [{pack_name}]: FAIL ({counts}, {len(errors)} errors)") - for err in errors: - print(f" {err}") - all_ok = False - failing.append(f"{platform_name} ({pack_name})") - - if not _verification_summary(failing, verified, args.output_dir) or not all_ok: - sys.exit(1) - - -def _verification_summary(failing: list[str], verified: int, output_dir: str) -> bool: - """Print how --verify-packs ended. False when nothing was verified.""" - if failing: - # Named at the end, where the log is read, and on stderr, as the - # build path does: a failing pack sat among its own error lines. - print( - f"ERROR: packs failed verification: {', '.join(failing)}", - file=sys.stderr, - ) - elif verified: - print(f"Verified {count_text(verified, 'pack')}: all OK") - if not verified: - # Every platform skipped is no check at all: a mistyped or purged - # output directory read as a passed integrity check. - print(f"ERROR: no pack to verify in {output_dir}", file=sys.stderr) - return False - return True - - -# The source x required combinations --all-variants builds, in build order. -ALL_VARIANTS: tuple[tuple[str, bool], ...] = ( - ("full", False), ("full", True), - ("platform", False), ("platform", True), - ("truth", False), ("truth", True), -) - - -def _pack_label(source: str, required_only: bool) -> str: - """The variant tag orchestrate.reports.parse_pack_counts reads after a pack name.""" - return f"[source={source}, required]" if required_only else f"[source={source}]" - - -def _truth_layer_is_empty( - platform: str, platforms_dir: str, emu_profiles: dict, target_cores: set[str] | None -) -> bool: - """Whether a platform runs no core a profile describes. - - MiSTer declares `cores: []`: its truth pack held nothing, passed its - check and was published under a name claiming a content. - """ - config = load_platform_config(platform, platforms_dir) - return not _platform_cores(config, emu_profiles or {}, target_cores=target_cores) - - -def _skip_empty_truth( - args: argparse.Namespace, - source: str, - representative: str, - emu_profiles: dict, - tc: set[str] | None, - failed: list[str], -) -> bool: - """Leave out a truth pack that would be empty, refuse it when asked for.""" - if source != "truth" or not _truth_layer_is_empty( - representative, args.platforms_dir, emu_profiles, tc - ): - return False - if args.all_variants: - print(f" {representative}: no core profile, no truth pack") - else: - print( - f"ERROR: {representative} runs no core a profile describes; " - "a truth pack would hold nothing", - file=sys.stderr, - ) - failed.append(representative) - return True - - -def _produced(split: bool, zip_path: str | None, zip_paths: list[str] | None) -> bool: - """Whether the build wrote what the run asked for.""" - return bool(zip_paths if split else zip_path) - - -def _run_platform_packs( - args: argparse.Namespace, - groups: list[tuple[list[str], str]], - db: dict, - zip_contents: dict, - data_registry: dict | None, - emu_profiles: dict, - target_cores_cache: dict[str, set[str] | None], - system_filter: list[str] | None, -) -> None: - """Generate ZIP packs for platform groups and verify.""" - variants = ALL_VARIANTS if args.all_variants else ((args.source, args.required_only),) - registry_path = os.path.join(args.platforms_dir, "_registry.yml") - # Per pack, the systems each of its files is for, written into its - # manifest.json once the pack is verified (pack_systems). - systems_for: dict[str, dict] = {} - # The packs this run writes, the only ones it verifies and rewrites. - built: set[str] = set() - - failed: list[str] = [] - for source, required_only in variants: - for group_platforms, representative in groups: - aliases = [p for p in group_platforms if p != representative] - if aliases: - all_names = [ - load_platform_config(p, args.platforms_dir).get("platform", p) - for p in group_platforms - ] - label = " / ".join(all_names) - print(f"\nGenerating pack for {label} {_pack_label(source, required_only)}...") - else: - print(f"\nGenerating pack for {representative} {_pack_label(source, required_only)}...") - - zip_path = None - zip_paths: list = [] - tc = target_cores_cache.get(representative) if args.target else None - named_target = platform_target(representative, args.target, args.platforms_dir) - if _skip_empty_truth(args, source, representative, emu_profiles, tc, failed): - continue - try: - if args.split: - zip_paths = generate_split_packs( - representative, - args.platforms_dir, - db, - args.bios_dir, - args.output_dir, - group_by=args.group_by, - emulators_dir=args.emulators_dir, - zip_contents=zip_contents, - data_registry=data_registry, - emu_profiles=emu_profiles, - target_cores=tc, - required_only=required_only, - source=source, - regions=getattr(args, "regions", None), - target_name=named_target, - one_per_slot=args.one_per_slot, - offline=args.offline, - no_game_data=getattr(args, "no_game_data", False), - ) - print(f" Split into {len(zip_paths)} packs") - else: - # A group's pack is written under the group's name from - # the start: built under the representative's and then - # renamed, it overwrote and carried away a - # `--platform retroarch` pack already in the directory, - # and os.rename refused an existing target on Windows. - group_name = ( - _group_pack_name( - args, group_platforms, representative, (source, required_only), - named_target, system_filter, - ) - if aliases else None - ) - zip_path = generate_pack( - representative, - args.platforms_dir, - db, - args.bios_dir, - args.output_dir, - emulators_dir=args.emulators_dir, - zip_contents=zip_contents, - data_registry=data_registry, - emu_profiles=emu_profiles, - target_cores=tc, - required_only=required_only, - system_filter=system_filter, - source=source, - regions=getattr(args, "regions", None), - target_name=named_target, - one_per_slot=args.one_per_slot, - offline=args.offline, - pack_name=group_name, - no_game_data=getattr(args, "no_game_data", False), - ) - except (FileNotFoundError, OSError, yaml.YAMLError) as e: - print(f" ERROR: {e}", file=sys.stderr) - failed.append(representative) - else: - # A builder that declined (no system left under the target) - # produced nothing: the run must say so, not verify whatever - # the output directory already held and exit 0. - if not _produced(args.split, zip_path, zip_paths): - failed.append(representative) - continue - built.update( - os.path.relpath(path, args.output_dir) - for path in ([zip_path] if zip_path else zip_paths) - ) - if zip_path and not system_filter: - # The install list of the same choices names each file's - # systems: the pack records them, so a pack alone (a - # handheld without Wi-Fi) can be narrowed by system. - board_list = Path(args.platforms_dir) / "targets" / f"{representative}.yml" - systems_for[os.path.basename(zip_path)] = pack_systems(generate_manifest( - representative, args.platforms_dir, db, args.bios_dir, - registry_path, emulators_dir=args.emulators_dir, - zip_contents=zip_contents, emu_profiles=emu_profiles, - target_cores=tc, source=source, - regions=getattr(args, "regions", None), target_name=named_target, - offline=args.offline, required_only=required_only, - data_registry=data_registry, - no_game_data=getattr(args, "no_game_data", False), - ), target_list(board_list) if board_list.is_file() else None) - - all_ok = _finalize_platform_packs(args, db, data_registry, built, systems_for, system_filter) - if failed: - # Verification only sees the ZIPs that exist, so a pack that was never - # written does not fail it. - print(f"ERROR: no pack for {', '.join(sorted(set(failed)))}", file=sys.stderr) - sys.exit(1) - if not all_ok: - sys.exit(1) - - -def _group_pack_name( - args: argparse.Namespace, - group_platforms: list[str], - representative: str, - variant: tuple[str, bool], - named_target: str | None, - system_filter: list[str] | None, -) -> str: - """The file name of a pack shared by a group of identical platforms.""" - source, required_only = variant - narrowings = pack_narrowings( - source, - getattr(args, "regions", None), - named_target, - args.one_per_slot, - required_only, - no_game_data=getattr(args, "no_game_data", False), - ) - return platform_pack_name( - representative, args.platforms_dir, narrowings, system_filter, group=group_platforms - ) - - -def _finalize_platform_packs( - args: argparse.Namespace, - db: dict, - data_registry: dict | None, - built: set[str], - systems_for: dict[str, dict], - system_filter: list[str] | None, -) -> bool: - """Verify the packs this run wrote and write their manifests.""" - print("\nVerifying packs and generating manifests...") - skip_conf = bool(system_filter or args.split) - all_ok = verify_and_finalize_packs( - args.output_dir, - db, - platforms_dir=args.platforms_dir, - emulators_dir=args.emulators_dir, - built=built, - pack_systems_by_name=systems_for, - skip_conformance=skip_conf, - data_registry=data_registry, - regions=getattr(args, "regions", None), - target_name=args.target, - no_game_data=getattr(args, "no_game_data", False), - ) - if args.split: - for entry in os.listdir(args.output_dir): - sub = os.path.join(args.output_dir, entry) - if os.path.isdir(sub) and entry.endswith("_Split"): - ok = verify_and_finalize_packs( - sub, - db, - platforms_dir=args.platforms_dir, - emulators_dir=args.emulators_dir, - built={ - os.path.basename(name) for name in built - if os.path.dirname(name) == entry - }, - skip_conformance=True, - data_registry=data_registry, - regions=getattr(args, "regions", None), - ) - all_ok = all_ok and ok - return all_ok - - def _refuse_for_all_variants(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: """Flags --all-variants would override, or modes that never read it.""" if not args.all_variants: @@ -896,9 +269,10 @@ def main() -> None: with contextlib.ExitStack() as held: try: _main(held) - except DamagedArchiveError as exc: + except (DamagedArchiveError, ArtifactLockBusy) as exc: # Emulator, system and hash modes have no per-platform loop to - # report it: the run stops with the file to restore. + # report a damaged archive: the run stops with the file to + # restore. A busy output directory refuses the run. print(f"ERROR: {exc}", file=sys.stderr) sys.exit(1) if MISSING_DATA_DIRS: @@ -1035,12 +409,14 @@ def _run_quick_mode( # The check resolves core files against data/ like the build did, # and a refresh swapping a tree mid-check would judge another tree. hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) - with _pack_output_lock(args.output_dir, exclusive=False): - _run_verify_packs(args) + with pack_output_lock(args.output_dir, exclusive=False): + if not run_verify_packs(args): + sys.exit(1) return True if args.manifest_targets: - _refuse_mixed_output(args.output_dir, "targets") - with _pack_output_lock(args.output_dir): + if holds_other_kind(args.output_dir, "targets"): + sys.exit(1) + with pack_output_lock(args.output_dir): generate_target_manifests( os.path.join(args.platforms_dir, "targets"), args.output_dir ) @@ -1077,7 +453,7 @@ def _run_hash_mode(args: argparse.Namespace) -> None: sys.exit(1) return zip_contents = build_zip_contents_index(db) - with _pack_output_lock(args.output_dir): + with pack_output_lock(args.output_dir): result = generate_md5_pack( hashes=hashes, db=db, @@ -1099,7 +475,7 @@ def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> # Emulator mode if args.emulator: names = comma_list(args.emulator) - with _pack_output_lock(args.output_dir): + with pack_output_lock(args.output_dir): built = generate_emulator_pack( names, args.emulators_dir, @@ -1119,7 +495,7 @@ def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> # System mode (standalone, without platform context) system_ids = comma_list(args.system) - with _pack_output_lock(args.output_dir): + with pack_output_lock(args.output_dir): built = generate_system_pack( system_ids, args.emulators_dir, @@ -1155,95 +531,6 @@ def _requested_platforms(args: argparse.Namespace, parser: argparse.ArgumentPars return [args.platform] -def _refresh_data_directories(args: argparse.Namespace, data_registry: dict) -> None: - """Bring the data directory caches up to date before a build reads them.""" - from packs.datadirs import refresh_all - - results = refresh_all(data_registry, force=args.refresh_data) - updated = sum(1 for v in results.values() if v) - if updated: - print(f"Refreshed {count_text(updated, 'data directory', 'data directories')}") - failed = sorted(k for k, v in results.items() if v is None) - if failed: - print(f"WARNING: data directory refresh failed: {', '.join(failed)}") - - -def _run_platform_mode( - args: argparse.Namespace, - parser: argparse.ArgumentParser, - held: contextlib.ExitStack, - db: dict, - zip_contents: dict, -) -> None: - """--platform or --all: packs or manifests in each platform's layout.""" - system_filter = getattr(args, "system_ids", None) - - # Platform mode - platforms = _requested_platforms(args, parser) - - # A mistyped target is refused before the output lock and the data - # directory refresh: checked after them, `--target swich` waited on a - # pipeline's caches before saying the target does not exist. - target_cores_cache, platforms = target_scope( - platforms, args.target, args.platforms_dir, is_all=args.all - ) - - emu_profiles = load_emulator_profiles(args.emulators_dir) - if system_filter: - platforms = platforms_with_systems( - platforms, system_filter, emu_profiles, target_cores_cache, - args.platforms_dir, args.target, args.all, - ) - platforms = without_profile_blind( - platforms, - [ - flag for flag, given in ( - ("--region", getattr(args, "regions", None)), - ("--one-per-slot", getattr(args, "one_per_slot", False)), - ("--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, - ) - - data_registry = load_data_dir_registry(args.platforms_dir) - # The output directory is claimed before the data directory refresh: a - # refresh waits for every run that holds a cache, so a second build - # during a pipeline sat silent for hours instead of being refused. - with _pack_output_lock(args.output_dir): - if data_registry and not args.offline and not args.no_refresh_data: - _refresh_data_directories(args, data_registry) - if data_registry: - hold_data_dirs(held, data_registry) - - groups = group_identical_platforms( - platforms, args.platforms_dir, target_cores_cache if args.target else None - ) - - if args.manifest: - _refuse_mixed_output(args.output_dir, "manifest") - _run_manifest_mode( - args, groups, db, zip_contents, emu_profiles, target_cores_cache - ) - else: - _run_platform_packs( - args, - groups, - db, - zip_contents, - data_registry, - emu_profiles, - target_cores_cache, - system_filter, - ) - if not args.manifest and args.verify_packs: - with _pack_output_lock(args.output_dir, exclusive=False): - _run_verify_packs(args) - - def _main(held: contextlib.ExitStack) -> None: parser = _build_parser() args = parser.parse_args() @@ -1283,18 +570,8 @@ def _main(held: contextlib.ExitStack) -> None: if args.emulator or (args.system and not args.platform and not args.all): _run_profile_mode(args, db, zip_contents) return - _run_platform_mode(args, parser, held, db, zip_contents) - - -def _write_standalone_layouts(output_dir: str, platform: str, layouts: dict) -> str: - """install/standalone/.json, what --standalone reads beside the - list. Its [dest, sha1] items take their download from that list.""" - path = os.path.join(output_dir, STANDALONE_DIR, f"{platform}.json") - os.makedirs(os.path.dirname(path), exist_ok=True) - write_if_changed(path, json.dumps({ - "schema": 1, "platform": platform, "standalone_layouts": layouts, - }, indent=2)) - return path + if not run_platform_mode(args, _requested_platforms(args, parser), held, db, zip_contents): + sys.exit(1) if __name__ == "__main__": diff --git a/scripts/packs/manifestrun.py b/scripts/packs/manifestrun.py new file mode 100644 index 000000000..5a716e5a0 --- /dev/null +++ b/scripts/packs/manifestrun.py @@ -0,0 +1,152 @@ +"""Install manifests written for platform groups, with their aliases and standalone layouts.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys + +from core.artifacts import write_if_changed +from model.platforms import load_platform_config +from model.registry import load_platform_registry +from model.safeparse import require_yaml +from packs.manifest import generate_install_list +from packs.naming import pack_narrowings, platform_target +from packs.scope import platform_list_version +from packs.standalone import STANDALONE_DIR, standalone_copies +from packs.variants import run_variants, skip_empty_truth +from resolve.cores import resolve_platform_cores + +yaml = require_yaml() + + +def write_standalone_layouts(output_dir: str, platform: str, layouts: dict) -> str: + """install/standalone/.json, what --standalone reads beside the + list. Its [dest, sha1] items take their download from that list.""" + path = os.path.join(output_dir, STANDALONE_DIR, f"{platform}.json") + os.makedirs(os.path.dirname(path), exist_ok=True) + write_if_changed(path, json.dumps({ + "schema": 1, "platform": platform, "standalone_layouts": layouts, + }, indent=2)) + return path + + +def _alias_manifest( + manifest: dict, + alias_plat: str, + platforms_dir: str, + platform_registry: dict, + emu_profiles: dict, +) -> dict: + """The representative's manifest under a grouped platform's own name.""" + alias_manifest = dict(manifest) + alias_manifest["platform"] = alias_plat + alias_cfg = load_platform_config(alias_plat, platforms_dir) + alias_manifest["display_name"] = alias_cfg.get("platform", alias_plat) + alias_manifest["version"] = platform_list_version(alias_cfg, alias_plat) + alias_manifest["base_destination"] = alias_cfg.get("base_destination", "") + alias_registry = platform_registry.get(alias_plat, {}) + alias_install = alias_registry.get("install", {}) + alias_manifest["detect"] = alias_install.get("detect", []) + # Placed and completed as the representative's are: + # copied raw, an alias's copies named no source. + alias_manifest["standalone_copies"] = standalone_copies( + alias_install.get("standalone_copies", []), + {name: emu_profiles[name] + for name in resolve_platform_cores(alias_cfg, emu_profiles)}, + manifest["files"], + ) + return alias_manifest + + +def run_manifest_mode( + args: argparse.Namespace, + groups: list[tuple[list[str], str]], + db: dict, + zip_contents: dict, + emu_profiles: dict, + target_cores_cache: dict[str, set[str] | None], +) -> bool: + """Generate JSON manifests instead of ZIP packs. False when a platform + has none.""" + registry_path = os.path.join(args.platforms_dir, "_registry.yml") + os.makedirs(args.output_dir, exist_ok=True) + platform_registry = load_platform_registry(args.platforms_dir) + + failed: list[str] = [] + for source, required_only in run_variants(args): + for group_platforms, representative in groups: + print(f"\nGenerating manifest for {representative} [source={source}]...") + tc = target_cores_cache.get(representative) if args.target else None + if skip_empty_truth(args, source, representative, emu_profiles, tc, failed): + continue + layouts: dict = {} + try: + manifest = generate_install_list( + representative, + args.platforms_dir, + db, + args.bios_dir, + registry_path, + emulators_dir=args.emulators_dir, + zip_contents=zip_contents, + emu_profiles=emu_profiles, + target_cores=tc, + source=source, + regions=getattr(args, "regions", None), + target_name=platform_target( + representative, args.target, args.platforms_dir + ), + offline=args.offline, + required_only=required_only, + no_game_data=getattr(args, "no_game_data", False), + standalone_out=layouts, + ) + narrow_suffix = "".join( + tag.lower() + for tag, _label in pack_narrowings( + source, + getattr(args, "regions", None), + platform_target(representative, args.target, args.platforms_dir), + False, + required_only, + no_game_data=getattr(args, "no_game_data", False), + ) + ) + out_path = os.path.join( + args.output_dir, + f"{representative}{narrow_suffix}.json", + ) + write_if_changed(out_path, json.dumps(manifest, indent=2)) + print( + f" {out_path}: {manifest['total_files']} files, " + f"{manifest['total_size']} bytes, " + f"{manifest['total_omitted']} safely omitted" + ) + for plat in group_platforms if layouts else (): + print(f" {write_standalone_layouts(args.output_dir, plat, layouts)}: " + f"{len(layouts)} standalone builds") + # Create aliases for grouped platforms (e.g., lakka -> retroarch) + for alias_plat in group_platforms: + if alias_plat != representative: + alias_path = os.path.join( + args.output_dir, + f"{alias_plat}{narrow_suffix}.json", + ) + alias_manifest = _alias_manifest( + manifest, alias_plat, args.platforms_dir, + platform_registry, emu_profiles, + ) + write_if_changed(alias_path, json.dumps(alias_manifest, indent=2)) + print(f" {alias_path}: alias of {representative}") + except (FileNotFoundError, OSError, yaml.YAMLError) as e: + print(f" ERROR: {e}", file=sys.stderr) + failed.append(representative) + + # A platform whose manifest could not be built has none, and install.py + # serves whatever an older run left there: that is a failed run. + if failed: + print(f"ERROR: no manifest for {', '.join(sorted(set(failed)))}", file=sys.stderr) + return False + return True diff --git a/scripts/packs/outputdir.py b/scripts/packs/outputdir.py new file mode 100644 index 000000000..20fff0a15 --- /dev/null +++ b/scripts/packs/outputdir.py @@ -0,0 +1,67 @@ +"""The output directory a pack run writes: its lock and the installer JSON it holds.""" + +from __future__ import annotations + +import contextlib +import json +import sys +from collections.abc import Iterator +from pathlib import Path + +from core.artifacts import artifact_lock, repository_output_lock + + +def json_artifact_kind(path: Path) -> str | None: + """"manifest" for an install manifest, "targets" for a per-target core + list, None for anything else. The two share their file names: install.py + fetches install/.json and install/targets/.json.""" + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + return None + if not isinstance(data, dict) or not data: + return None + if "manifest_version" in data: + return "manifest" + if all(v is None or isinstance(v, list) for v in data.values()): + return "targets" + return None + + +def holds_other_kind(output_dir: str, writing: str) -> bool: + """Say so when one kind of installer JSON would overwrite the other. + + Both are named .json, so --manifest-targets aimed at install/ + replaced install/retroarch.json, the file every installer downloads, with + a target table, and the reverse replaced a target list by a manifest. + """ + directory = Path(output_dir) + if not directory.is_dir(): + return False + other = "targets" if writing == "manifest" else "manifest" + held = sorted( + p.name for p in directory.glob("*.json") if json_artifact_kind(p) == other + ) + if not held: + return False + what = { + "manifest": "install manifests (install/ in the repository)", + "targets": "per-target core lists (install/targets/ in the repository)", + } + flag = "--manifest" if writing == "manifest" else "--manifest-targets" + print( + f"ERROR: {output_dir} holds {what[other]}: {', '.join(held[:3])}" + f"{', ...' if len(held) > 3 else ''}. {flag} writes {what[writing]} under the " + f"same file names; pass the --output-dir that holds those instead.", + file=sys.stderr, + ) + return True + + +@contextlib.contextmanager +def pack_output_lock(output_dir: str, exclusive: bool = True) -> Iterator[None]: + """Hold the output directory for the duration of a pack run, and the + repository's fixed outputs when it is one of them (install/).""" + with artifact_lock(output_dir, exclusive=exclusive), \ + repository_output_lock(output_dir) if exclusive else contextlib.nullcontext(): + yield diff --git a/scripts/packs/packcheck.py b/scripts/packs/packcheck.py new file mode 100644 index 000000000..1169c1ed7 --- /dev/null +++ b/scripts/packs/packcheck.py @@ -0,0 +1,182 @@ +"""--verify-packs: each pack in an output directory checked against its platform.""" + +from __future__ import annotations + +import argparse +import os +import sys +from dataclasses import dataclass + +from core.text import count_text +from model.database import load_database +from model.profiles import load_emulator_profiles +from model.registry import list_release_pack_platforms, load_data_dir_registry +from model.targets import target_scope +from packs.finalize import baseline_shortfall +from packs.integrity import verify_pack_against_platform +from packs.naming import expected_pack_names, pack_variant +from packs.variants import ALL_VARIANTS + + +@dataclass(frozen=True) +class PackCheck: + """What --verify-packs checks every pack against.""" + + db: dict + platforms_dir: str + emulators_dir: str + profiles: dict + regions: list[str] | None + data_registry: dict + no_game_data: bool + + +def verify_packs_scope(args: argparse.Namespace) -> tuple[list[str], dict[str, set[str] | None]]: + """The platforms --verify-packs checks, and the cores of the target.""" + if args.platform: + platforms = [args.platform] + elif args.all: + # The packs --all builds: a platform without release_pack has no pack + # to check, and its absence from the directory is no failure. + platforms = list_release_pack_platforms(args.platforms_dir) + else: + raise ValueError("--verify-packs requires --platform or --all") + + # The target is checked as the build checks it: a mistyped one, or one + # the platform does not publish, was dropped and the full pack verified + # under it, `all OK` for a pack no build had made. + target_cores_cache, platforms = target_scope( + platforms, args.target, args.platforms_dir, is_all=args.all + ) + return platforms, target_cores_cache + + +def _check_pack( + check: PackCheck, platform_name: str, pack_name: str, zip_path: str, + tc: set[str] | None, +) -> list[str] | None: + """Check one pack and print its line. Its errors, or None when it passed.""" + variant = pack_variant(pack_name) + if variant is None: + # One BIOS per slot: the slot choice is not replayed here. + print( + f" {platform_name} [{pack_name}]: hashes checked during the build; " + "one per slot by design, so not compared to the platform's full list" + ) + return None + source, required_only = variant + result = verify_pack_against_platform( + zip_path, + platform_name, + check.platforms_dir, + db=check.db, + emulators_dir=check.emulators_dir, + emu_profiles=check.profiles, + regions=check.regions, + data_registry=check.data_registry, + target_cores=tc, + source=source, + required_only=required_only, + no_game_data=check.no_game_data, + ) + (ok, _checked, _present, errors, bl_checked, bl_present, + core_checked, core_present, bl_excluded, bl_absent) = result + # These explain a baseline short of its total: a dump whose hash + # the frontend refuses is left out on purpose, and a file the + # collection does not hold cannot be packed (verify reports it). + shortfall = ", ".join(baseline_shortfall(bl_excluded, bl_absent)) + excluded = f" ({shortfall})" if shortfall else "" + counts = ( + f"{bl_present}/{bl_checked} baseline{excluded}, " + f"{core_present}/{core_checked} cores" + ) + if ok: + print(f" {platform_name} [{pack_name}]: OK ({counts})") + return None + print(f" {platform_name} [{pack_name}]: FAIL ({counts}, {len(errors)} errors)") + for err in errors: + print(f" {err}") + return errors + + +def run_verify_packs(args: argparse.Namespace) -> bool: + """Verify each pack in the output directory against its platform. False + when one failed or none was found. + + Delegates to verify_pack_against_platform so the command answers the same + question the pipeline asks: baseline files, core extras and structure. A + second implementation here answered a narrower one and reported OK while + the core extras went unchecked. + """ + verify_db = load_database(args.db) + platforms, target_cores_cache = verify_packs_scope(args) + + all_ok = True + check = PackCheck( + verify_db, args.platforms_dir, args.emulators_dir, + load_emulator_profiles(args.emulators_dir), getattr(args, "regions", None), + load_data_dir_registry(args.platforms_dir), getattr(args, "no_game_data", False), + ) + # After an --all-variants build every variant is named, so none of the + # six packs the run wrote passes unmentioned. + expected = expected_pack_names( + platforms, + args.platforms_dir, + check.regions, + args.target, + ALL_VARIANTS if args.all_variants else (("full", False),), + no_game_data=check.no_game_data, + ) + on_disk = ( + set(os.listdir(args.output_dir)) if os.path.isdir(args.output_dir) else set() + ) + + verified = 0 + failing: list[str] = [] + for platform_name in platforms: + found = sorted(expected[platform_name] & on_disk) + verified += len(found) + if not found: + # Naming a platform is asking about its pack: FAIL, with the + # command that builds it. With --all, a platform whose pack was + # not built is out of scope and skipped. + if args.platform: + print( + f" {platform_name}: FAIL (no pack in {args.output_dir}; build it with " + f"python scripts/generate_pack.py --platform {platform_name} " + f"--output-dir {args.output_dir})" + ) + all_ok = False + failing.append(f"{platform_name} (no pack)") + else: + print(f" {platform_name}: SKIP (no pack in {args.output_dir})") + continue + tc = target_cores_cache.get(platform_name) + # A group pack and a pack built for the platform alone can both be + # present, and each one is a pack of this platform. + for pack_name in found: + zip_path = os.path.join(args.output_dir, pack_name) + if _check_pack(check, platform_name, pack_name, zip_path, tc) is not None: + all_ok = False + failing.append(f"{platform_name} ({pack_name})") + + return verification_summary(failing, verified, args.output_dir) and all_ok + + +def verification_summary(failing: list[str], verified: int, output_dir: str) -> bool: + """Print how --verify-packs ended. False when nothing was verified.""" + if failing: + # Named at the end, where the log is read, and on stderr, as the + # build path does: a failing pack sat among its own error lines. + print( + f"ERROR: packs failed verification: {', '.join(failing)}", + file=sys.stderr, + ) + elif verified: + print(f"Verified {count_text(verified, 'pack')}: all OK") + if not verified: + # Every platform skipped is no check at all: a mistyped or purged + # output directory read as a passed integrity check. + print(f"ERROR: no pack to verify in {output_dir}", file=sys.stderr) + return False + return True diff --git a/scripts/packs/platformrun.py b/scripts/packs/platformrun.py new file mode 100644 index 000000000..e2dcf7c60 --- /dev/null +++ b/scripts/packs/platformrun.py @@ -0,0 +1,334 @@ +"""A platform run: packs or manifests built for each group of platforms, then checked.""" + +from __future__ import annotations + +import argparse +import contextlib +import os +import sys +from pathlib import Path + +from core.text import count_text +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from model.registry import load_data_dir_registry +from model.safeparse import require_yaml +from model.targets import target_scope +from packs.datadirs import hold_data_dirs +from packs.finalize import verify_and_finalize_packs +from packs.manifest import generate_manifest +from packs.manifestrun import run_manifest_mode +from packs.naming import pack_narrowings, platform_pack_name, platform_target +from packs.outputdir import holds_other_kind, pack_output_lock +from packs.packcheck import run_verify_packs +from packs.platformpack import generate_pack, generate_split_packs +from packs.scope import pack_systems +from packs.targets import target_list +from packs.variants import pack_label, run_variants, skip_empty_truth +from resolve.cores import platforms_with_systems, without_profile_blind +from resolve.grouping import group_identical_platforms + +yaml = require_yaml() + + +def produced(split: bool, zip_path: str | None, zip_paths: list[str] | None) -> bool: + """Whether the build wrote what the run asked for.""" + return bool(zip_paths if split else zip_path) + + +def run_platform_packs( + args: argparse.Namespace, + groups: list[tuple[list[str], str]], + db: dict, + zip_contents: dict, + data_registry: dict | None, + emu_profiles: dict, + target_cores_cache: dict[str, set[str] | None], + system_filter: list[str] | None, +) -> bool: + """Generate ZIP packs for platform groups and verify. False when a pack + was not written or failed its check.""" + registry_path = os.path.join(args.platforms_dir, "_registry.yml") + # Per pack, the systems each of its files is for, written into its + # manifest.json once the pack is verified (pack_systems). + systems_for: dict[str, dict] = {} + # The packs this run writes, the only ones it verifies and rewrites. + built: set[str] = set() + + failed: list[str] = [] + for source, required_only in run_variants(args): + for group_platforms, representative in groups: + aliases = [p for p in group_platforms if p != representative] + if aliases: + all_names = [ + load_platform_config(p, args.platforms_dir).get("platform", p) + for p in group_platforms + ] + label = " / ".join(all_names) + print(f"\nGenerating pack for {label} {pack_label(source, required_only)}...") + else: + print(f"\nGenerating pack for {representative} {pack_label(source, required_only)}...") + + zip_path = None + zip_paths: list = [] + tc = target_cores_cache.get(representative) if args.target else None + named_target = platform_target(representative, args.target, args.platforms_dir) + if skip_empty_truth(args, source, representative, emu_profiles, tc, failed): + continue + try: + if args.split: + zip_paths = generate_split_packs( + representative, + args.platforms_dir, + db, + args.bios_dir, + args.output_dir, + group_by=args.group_by, + emulators_dir=args.emulators_dir, + zip_contents=zip_contents, + data_registry=data_registry, + emu_profiles=emu_profiles, + target_cores=tc, + required_only=required_only, + source=source, + regions=getattr(args, "regions", None), + target_name=named_target, + one_per_slot=args.one_per_slot, + offline=args.offline, + no_game_data=getattr(args, "no_game_data", False), + ) + print(f" Split into {len(zip_paths)} packs") + else: + # A group's pack is written under the group's name from + # the start: built under the representative's and then + # renamed, it overwrote and carried away a + # `--platform retroarch` pack already in the directory, + # and os.rename refused an existing target on Windows. + group_name = ( + group_pack_name( + args, group_platforms, representative, (source, required_only), + named_target, system_filter, + ) + if aliases else None + ) + zip_path = generate_pack( + representative, + args.platforms_dir, + db, + args.bios_dir, + args.output_dir, + emulators_dir=args.emulators_dir, + zip_contents=zip_contents, + data_registry=data_registry, + emu_profiles=emu_profiles, + target_cores=tc, + required_only=required_only, + system_filter=system_filter, + source=source, + regions=getattr(args, "regions", None), + target_name=named_target, + one_per_slot=args.one_per_slot, + offline=args.offline, + pack_name=group_name, + no_game_data=getattr(args, "no_game_data", False), + ) + except (FileNotFoundError, OSError, yaml.YAMLError) as e: + print(f" ERROR: {e}", file=sys.stderr) + failed.append(representative) + else: + # A builder that declined (no system left under the target) + # produced nothing: the run must say so, not verify whatever + # the output directory already held and exit 0. + if not produced(args.split, zip_path, zip_paths): + failed.append(representative) + continue + built.update( + os.path.relpath(path, args.output_dir) + for path in ([zip_path] if zip_path else zip_paths) + ) + if zip_path and not system_filter: + # The install list of the same choices names each file's + # systems: the pack records them, so a pack alone (a + # handheld without Wi-Fi) can be narrowed by system. + board_list = Path(args.platforms_dir) / "targets" / f"{representative}.yml" + systems_for[os.path.basename(zip_path)] = pack_systems(generate_manifest( + representative, args.platforms_dir, db, args.bios_dir, + registry_path, emulators_dir=args.emulators_dir, + zip_contents=zip_contents, emu_profiles=emu_profiles, + target_cores=tc, source=source, + regions=getattr(args, "regions", None), target_name=named_target, + offline=args.offline, required_only=required_only, + data_registry=data_registry, + no_game_data=getattr(args, "no_game_data", False), + ), target_list(board_list) if board_list.is_file() else None) + + all_ok = finalize_platform_packs(args, db, data_registry, built, systems_for, system_filter) + if failed: + # Verification only sees the ZIPs that exist, so a pack that was never + # written does not fail it. + print(f"ERROR: no pack for {', '.join(sorted(set(failed)))}", file=sys.stderr) + return False + return all_ok + + +def group_pack_name( + args: argparse.Namespace, + group_platforms: list[str], + representative: str, + variant: tuple[str, bool], + named_target: str | None, + system_filter: list[str] | None, +) -> str: + """The file name of a pack shared by a group of identical platforms.""" + source, required_only = variant + narrowings = pack_narrowings( + source, + getattr(args, "regions", None), + named_target, + args.one_per_slot, + required_only, + no_game_data=getattr(args, "no_game_data", False), + ) + return platform_pack_name( + representative, args.platforms_dir, narrowings, system_filter, group=group_platforms + ) + + +def finalize_platform_packs( + args: argparse.Namespace, + db: dict, + data_registry: dict | None, + built: set[str], + systems_for: dict[str, dict], + system_filter: list[str] | None, +) -> bool: + """Verify the packs this run wrote and write their manifests.""" + print("\nVerifying packs and generating manifests...") + skip_conf = bool(system_filter or args.split) + all_ok = verify_and_finalize_packs( + args.output_dir, + db, + platforms_dir=args.platforms_dir, + emulators_dir=args.emulators_dir, + built=built, + pack_systems_by_name=systems_for, + skip_conformance=skip_conf, + data_registry=data_registry, + regions=getattr(args, "regions", None), + target_name=args.target, + no_game_data=getattr(args, "no_game_data", False), + ) + if args.split: + for entry in os.listdir(args.output_dir): + sub = os.path.join(args.output_dir, entry) + if os.path.isdir(sub) and entry.endswith("_Split"): + ok = verify_and_finalize_packs( + sub, + db, + platforms_dir=args.platforms_dir, + emulators_dir=args.emulators_dir, + built={ + os.path.basename(name) for name in built + if os.path.dirname(name) == entry + }, + skip_conformance=True, + data_registry=data_registry, + regions=getattr(args, "regions", None), + ) + all_ok = all_ok and ok + return all_ok + + +def refresh_data_directories(args: argparse.Namespace, data_registry: dict) -> None: + """Bring the data directory caches up to date before a build reads them.""" + from packs.datadirs import refresh_all + + results = refresh_all(data_registry, force=args.refresh_data) + updated = sum(1 for v in results.values() if v) + if updated: + print(f"Refreshed {count_text(updated, 'data directory', 'data directories')}") + failed = sorted(k for k, v in results.items() if v is None) + if failed: + print(f"WARNING: data directory refresh failed: {', '.join(failed)}") + + +def _narrowing_flags(args: argparse.Namespace) -> list[str]: + """The narrowing flags given that a profile-blind platform cannot apply.""" + return [ + flag for flag, given in ( + ("--region", getattr(args, "regions", None)), + ("--one-per-slot", getattr(args, "one_per_slot", False)), + ("--no-game-data", getattr(args, "no_game_data", False)), + ) if given + ] + + +def run_platform_mode( + args: argparse.Namespace, + platforms: list[str], + held: contextlib.ExitStack, + db: dict, + zip_contents: dict, +) -> bool: + """--platform or --all: packs or manifests in each platform's layout. + False when the run failed.""" + system_filter = getattr(args, "system_ids", None) + + # A mistyped target is refused before the output lock and the data + # directory refresh: checked after them, `--target swich` waited on a + # pipeline's caches before saying the target does not exist. + target_cores_cache, platforms = target_scope( + platforms, args.target, args.platforms_dir, is_all=args.all + ) + + emu_profiles = load_emulator_profiles(args.emulators_dir) + if system_filter: + platforms = platforms_with_systems( + platforms, system_filter, emu_profiles, target_cores_cache, + args.platforms_dir, args.target, args.all, + ) + platforms = without_profile_blind( + platforms, + _narrowing_flags(args), + args.platforms_dir, + emu_profiles, + target_cores_cache if args.target else None, + args.all, + ) + + data_registry = load_data_dir_registry(args.platforms_dir) + # The output directory is claimed before the data directory refresh: a + # refresh waits for every run that holds a cache, so a second build + # during a pipeline sat silent for hours instead of being refused. + with pack_output_lock(args.output_dir): + if data_registry and not args.offline and not args.no_refresh_data: + refresh_data_directories(args, data_registry) + if data_registry: + hold_data_dirs(held, data_registry) + + groups = group_identical_platforms( + platforms, args.platforms_dir, target_cores_cache if args.target else None + ) + + if args.manifest: + if holds_other_kind(args.output_dir, "manifest"): + return False + if not run_manifest_mode( + args, groups, db, zip_contents, emu_profiles, target_cores_cache + ): + return False + elif not run_platform_packs( + args, + groups, + db, + zip_contents, + data_registry, + emu_profiles, + target_cores_cache, + system_filter, + ): + return False + if not args.manifest and args.verify_packs: + with pack_output_lock(args.output_dir, exclusive=False): + return run_verify_packs(args) + return True diff --git a/scripts/packs/variants.py b/scripts/packs/variants.py new file mode 100644 index 000000000..8cb73c221 --- /dev/null +++ b/scripts/packs/variants.py @@ -0,0 +1,63 @@ +"""The source x required variants a run builds, and the truth pack nothing fills.""" + +from __future__ import annotations + +import argparse +import sys + +from model.platforms import load_platform_config +from resolve.cores import resolve_platform_cores + +# The source x required combinations --all-variants builds, in build order. +ALL_VARIANTS: tuple[tuple[str, bool], ...] = ( + ("full", False), ("full", True), + ("platform", False), ("platform", True), + ("truth", False), ("truth", True), +) + + +def run_variants(args: argparse.Namespace) -> tuple[tuple[str, bool], ...]: + """The variants a run builds: all six, or the one its flags name.""" + return ALL_VARIANTS if args.all_variants else ((args.source, args.required_only),) + + +def pack_label(source: str, required_only: bool) -> str: + """The variant tag orchestrate.reports.parse_pack_counts reads after a pack name.""" + return f"[source={source}, required]" if required_only else f"[source={source}]" + + +def truth_layer_is_empty( + platform: str, platforms_dir: str, emu_profiles: dict, target_cores: set[str] | None +) -> bool: + """Whether a platform runs no core a profile describes. + + MiSTer declares `cores: []`: its truth pack held nothing, passed its + check and was published under a name claiming a content. + """ + config = load_platform_config(platform, platforms_dir) + return not resolve_platform_cores(config, emu_profiles or {}, target_cores=target_cores) + + +def skip_empty_truth( + args: argparse.Namespace, + source: str, + representative: str, + emu_profiles: dict, + tc: set[str] | None, + failed: list[str], +) -> bool: + """Leave out a truth pack that would be empty, refuse it when asked for.""" + if source != "truth" or not truth_layer_is_empty( + representative, args.platforms_dir, emu_profiles, tc + ): + return False + if args.all_variants: + print(f" {representative}: no core profile, no truth pack") + else: + print( + f"ERROR: {representative} runs no core a profile describes; " + "a truth pack would hold nothing", + file=sys.stderr, + ) + failed.append(representative) + return True diff --git a/tests/sources.py b/tests/sources.py index d0c6040fd..30ef7bbb0 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -19,7 +19,8 @@ COMMANDS = { "packs/archive.py", "packs/naming.py", "packs/scope.py", "packs/datatrees.py", "packs/platformpack.py", "packs/emulatorpack.py", "packs/md5pack.py", "packs/targets.py", "packs/manifestentry.py", "packs/manifestcores.py", "packs/standalone.py", - "packs/manifest.py", "packs/finalize.py", + "packs/manifest.py", "packs/finalize.py", "packs/outputdir.py", "packs/variants.py", + "packs/manifestrun.py", "packs/packcheck.py", "packs/platformrun.py", ), "verify.py": ( "packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py", diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index e5c47a7b6..180fb4c18 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -4517,7 +4517,7 @@ class ADataDirectoryIsHeldWhileRead(unittest.TestCase): # against data/ while a refresh could swap a tree. pack = script_source("generate_pack.py") branch = pack.index("if args.verify_packs and not args.all_variants:") - run = pack.index("_run_verify_packs(args)", branch) + run = pack.index("run_verify_packs(args)", branch) self.assertIn("hold_data_dirs(held,", pack[branch:run]) @@ -4889,7 +4889,7 @@ class VerifyPacksSaysWhatItExcluded(unittest.TestCase): def test_the_result_is_unpacked_whole_and_every_error_printed(self): source = script_source("generate_pack.py") - body = source[source.index("def _run_verify_packs"):] + body = source[source.index("def _check_pack"):] body = body[:body.index("\ndef ")] self.assertIn("bl_excluded, bl_absent) = result", body) self.assertIn("baseline_shortfall(bl_excluded, bl_absent)", body) diff --git a/tests/test_pack_conformance_dirs.py b/tests/test_pack_conformance_dirs.py index 29c7d6e1d..2d7008b22 100644 --- a/tests/test_pack_conformance_dirs.py +++ b/tests/test_pack_conformance_dirs.py @@ -1,6 +1,6 @@ """The conformance stage reads the directories the run was given. -``_run_platform_packs`` called ``verify_and_finalize_packs`` without them, so +``run_platform_packs`` called ``verify_and_finalize_packs`` without them, so packs built from ``--platforms-dir`` and ``--emulators-dir`` were judged against ``platforms/`` and ``emulators/``, or not matched to any platform at all and never judged. @@ -16,7 +16,7 @@ import unittest from pathlib import Path from unittest import mock -import generate_pack as gp +from packs import platformrun from packs import finalize as packs_finalize from packs import integrity as packverify @@ -42,9 +42,9 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase): if split: Path(self.tmp.name, "X_Split").mkdir(exist_ok=True) with self.subTest(split=split), mock.patch.object( - gp, "verify_and_finalize_packs", return_value=True + platformrun, "verify_and_finalize_packs", return_value=True ) as finalize: - gp._run_platform_packs( + platformrun.run_platform_packs( self._args(split), [], {}, {}, {}, {}, {}, None ) self.assertTrue(finalize.call_args_list) diff --git a/tests/test_pack_failures.py b/tests/test_pack_failures.py index c989d92e4..d36e4372d 100644 --- a/tests/test_pack_failures.py +++ b/tests/test_pack_failures.py @@ -16,9 +16,10 @@ import unittest from pathlib import Path from unittest import mock -import generate_pack as gp from packs import manifest +from packs import manifestrun from packs import platformpack +from packs import platformrun REPO_ROOT = Path(__file__).resolve().parents[1] @@ -45,23 +46,20 @@ class FailedPlatformFailsTheRun(unittest.TestCase): ) def test_pack_mode(self): - with mock.patch.object(gp, "generate_pack", _boom), \ + with mock.patch.object(platformrun, "generate_pack", _boom), \ mock.patch.object(platformpack, "generate_pack", _boom), \ - mock.patch.object(gp, "verify_and_finalize_packs", return_value=True), \ - self.assertRaises(SystemExit) as ctx: - gp._run_platform_packs( + mock.patch.object(platformrun, "verify_and_finalize_packs", return_value=True): + ok = platformrun.run_platform_packs( self._args(), [(["retropie"], "retropie")], {}, {}, {}, {}, {}, None ) - self.assertEqual(ctx.exception.code, 1) + self.assertFalse(ok) def test_manifest_mode(self): - with mock.patch.object(gp, "generate_manifest", _boom), \ - mock.patch.object(manifest, "generate_manifest", _boom), \ - self.assertRaises(SystemExit) as ctx: - gp._run_manifest_mode( + with mock.patch.object(manifest, "generate_manifest", _boom): + ok = manifestrun.run_manifest_mode( self._args(), [(["retropie"], "retropie")], {}, {}, {}, {} ) - self.assertEqual(ctx.exception.code, 1) + self.assertFalse(ok) if __name__ == "__main__": diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index 694b0e5bc..c1dbabfbc 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -127,16 +127,18 @@ class NoPlatformIsSetApart(unittest.TestCase): class TheBuildReadsTheField(unittest.TestCase): def _groups(self, *argv: str) -> list[str]: import generate_pack + from packs import platformrun built: list[str] = [] def capture(args, groups, *rest, **kw): built.extend(name for group, _rep in groups for name in group) + return True with tempfile.TemporaryDirectory() as out, \ contextlib.chdir(REPO_ROOT), \ - mock.patch.object(generate_pack, "_run_platform_packs", capture), \ - mock.patch.object(generate_pack, "_run_manifest_mode", capture), \ + mock.patch.object(platformrun, "run_platform_packs", capture), \ + mock.patch.object(platformrun, "run_manifest_mode", capture), \ mock.patch.object(sys, "argv", ["generate_pack.py", *argv, "--output-dir", out]), \ contextlib.redirect_stdout(io.StringIO()): generate_pack.main() diff --git a/tests/test_target_verify.py b/tests/test_target_verify.py index d47b1325f..c49074a53 100644 --- a/tests/test_target_verify.py +++ b/tests/test_target_verify.py @@ -68,6 +68,7 @@ class AMistypedTargetIsRefusedFirst(unittest.TestCase): from unittest import mock import generate_pack + from packs import platformrun def touched(*_a, **_kw): raise AssertionError("lock or refresh taken before the target check") @@ -76,8 +77,10 @@ class AMistypedTargetIsRefusedFirst(unittest.TestCase): "--output-dir", str(REPO_ROOT / "tmp" / "never-written")] err = io.StringIO() with mock.patch.object(sys, "argv", argv), \ - mock.patch.object(generate_pack, "_pack_output_lock", touched), \ + mock.patch.object(generate_pack, "pack_output_lock", touched), \ mock.patch.object(generate_pack, "hold_data_dirs", touched), \ + mock.patch.object(platformrun, "pack_output_lock", touched), \ + mock.patch.object(platformrun, "hold_data_dirs", touched), \ contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(err), \ self.assertRaises(SystemExit) as ctx: diff --git a/tests/test_verify_pack_choice.py b/tests/test_verify_pack_choice.py index 386c7d4cf..190234b15 100644 --- a/tests/test_verify_pack_choice.py +++ b/tests/test_verify_pack_choice.py @@ -15,8 +15,9 @@ import json import os import tempfile import unittest -import generate_pack from packs import naming +from packs import packcheck +from packs import variants from pathlib import Path from unittest import mock @@ -69,8 +70,8 @@ class VerifyPackChoice(unittest.TestCase): self.variants: list[tuple[str, bool]] = [] - with mock.patch.object(generate_pack, "verify_pack_against_platform", record): - generate_pack._run_verify_packs(args) + with mock.patch.object(packcheck, "verify_pack_against_platform", record): + self.ok = packcheck.run_verify_packs(args) return checked def _touch(self, name: str) -> None: @@ -94,9 +95,8 @@ class VerifyPackChoice(unittest.TestCase): def test_named_platform_with_only_a_narrowed_pack_fails(self): self._touch(f"{self.stem}_Truth_BIOS_Pack.zip") - with self.assertRaises(SystemExit) as ctx: - self._run(self._args()) - self.assertEqual(ctx.exception.code, 1) + self._run(self._args()) + self.assertFalse(self.ok) def test_all_variants_checks_every_variant_as_it_was_built(self): """After --all-variants the check opened the full pack only, and then @@ -104,7 +104,7 @@ class VerifyPackChoice(unittest.TestCase): one missing a file its narrowed list requires passed. Each is now held to the platform's list narrowed the same way.""" names = {} - for source, required in generate_pack.ALL_VARIANTS: + for source, required in variants.ALL_VARIANTS: tags = "".join( tag for tag, _ in naming.pack_narrowings(source, None, None, False, required) ) @@ -143,11 +143,10 @@ class VerifyPackChoice(unittest.TestCase): self._touch(pack) out, err = io.StringIO(), io.StringIO() failed = (False, 0, 0, ["x: missing"], 1, 0, 1, 1, 0, 0) - with mock.patch.object(generate_pack, "verify_pack_against_platform", + with mock.patch.object(packcheck, "verify_pack_against_platform", return_value=failed), \ - contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \ - self.assertRaises(SystemExit): - generate_pack._run_verify_packs(self._args()) + contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + self.assertFalse(packcheck.run_verify_packs(self._args())) self.assertEqual( err.getvalue().strip().splitlines()[-1], f"ERROR: packs failed verification: retroarch ({pack})", @@ -175,9 +174,9 @@ class VerifyPackChoice(unittest.TestCase): class GroupRenameKeepsSystemTag(unittest.TestCase): def test_single_system_pack_does_not_take_the_full_name(self): - import generate_pack as gp from packs import naming from packs import platformpack + from packs import platformrun previous = os.getcwd() os.chdir(REPO_ROOT) @@ -198,10 +197,10 @@ class GroupRenameKeepsSystemTag(unittest.TestCase): one_per_slot=False, offline=True, bios_dir="bios", output_dir=tmp, ) - with mock.patch.object(gp, "generate_pack", fake_generate), \ + with mock.patch.object(platformrun, "generate_pack", fake_generate), \ mock.patch.object(platformpack, "generate_pack", fake_generate), \ - mock.patch.object(gp, "verify_and_finalize_packs", return_value=True): - gp._run_platform_packs( + mock.patch.object(platformrun, "verify_and_finalize_packs", return_value=True): + platformrun.run_platform_packs( args, [(["retroarch", "lakka"], "retroarch")], {}, {}, {}, {}, {}, ["atari-lynx"], )