diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 4bc18221a..162100bd5 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -25,250 +25,22 @@ import os sys.path.insert(0, os.path.dirname(__file__)) 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, - mode_conflicts, - platform_arg, - refuse_beside_mode, - requested_regions, - require_platform, - resolve_system_ids, - run_listing, -) -from model.database import load_database -from model.registry import ( - list_registered_platforms, - list_release_pack_platforms, - load_data_dir_registry, -) +from core.cli import add_emulator_selection, add_repo_inputs +from model.cliargs import platform_arg from packs.archive import DamagedArchiveError -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.md5pack import generate_md5_pack -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 import packmodes DEFAULT_OUTPUT_DIR = "dist" -def _refuse_for_verify_packs(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: - """What --verify-packs cannot be combined with, refused before any lock. - - These lived in the --all-variants checks, which return at once without - that flag: --verify-packs --manifest or --split went through, and a run - with neither --platform nor --all failed after locking the directory. - """ - if not args.verify_packs: - return - if args.manifest: - parser.error("--verify-packs is incompatible with --manifest") - if not (args.platform or args.all): - parser.error("--verify-packs requires --platform or --all") - # The check that follows the build reads the full pack's name. - for flag, given in ( - ("--system", args.system), - ("--one-per-slot", args.one_per_slot), - ("--split", args.split), - ): - if given: - parser.error(f"{flag} is incompatible with --verify-packs") - - -def _argument_conflicts(args: argparse.Namespace) -> list[tuple[bool, str]]: - """Each refused combination of arguments with its message, in the order - they are checked: the first one that applies is the error reported.""" - has_platform = bool(args.platform) - has_all = args.all - has_emulator = bool(args.emulator) - has_system = bool(args.system) - md5_file = getattr(args, "from_md5_file", None) - has_from_md5 = bool(args.from_md5 or md5_file) - # A mode either applies a narrowing flag or refuses it. Swallowing one - # answers about an artifact the caller did not ask for, and the name on - # disk then asserts a narrowing the contents do not carry. - # --source and --group-by default to None so a typed default value is - # seen: compared with "full", `--emulator X --source full` went through. - source_given = getattr(args, "source", None) is not None - with_platform = has_system and (has_platform or has_all) - no_game_data = getattr(args, "no_game_data", False) - one_per_slot = getattr(args, "one_per_slot", False) - return [ - (bool(args.from_md5 and md5_file), "--from-md5 and --from-md5-file are mutually exclusive"), - (has_from_md5 and has_all, "--from-md5 requires --platform or --emulator, not --all"), - (has_from_md5 and has_system, "--from-md5 and --system are mutually exclusive"), - (has_from_md5 and args.split, "--split and --from-md5 are mutually exclusive"), - *mode_conflicts(args, (("--from-md5", has_from_md5),)), - (args.split and not (has_platform or has_all), "--split requires --platform or --all"), - (args.split and has_emulator, "--split is incompatible with --emulator"), - (args.group_by is not None and not args.split, "--group-by requires --split"), - (args.manifest and not (has_platform or has_all), - "--manifest requires --platform or --all"), - (args.manifest and has_emulator, "--manifest is incompatible with --emulator"), - (args.manifest and args.split, "--manifest is incompatible with --split"), - (getattr(args, "region", None) and has_from_md5, - "--region and --from-md5 are mutually exclusive"), - (source_given and (has_emulator or (has_system and not has_platform)), - "--source requires --platform or --all"), - (has_from_md5 and args.manifest, "--manifest is incompatible with --from-md5"), - (has_from_md5 and args.target, "--target is incompatible with --from-md5"), - (has_from_md5 and args.required_only, "--required-only is incompatible with --from-md5"), - (has_from_md5 and source_given, "--source is incompatible with --from-md5"), - (with_platform and args.manifest, "--system is incompatible with --manifest"), - (with_platform and args.split, "--system is incompatible with --split"), - (no_game_data and has_from_md5, "--no-game-data is incompatible with --from-md5"), - (one_per_slot and has_from_md5, "--one-per-slot and --from-md5 are mutually exclusive"), - (one_per_slot and args.manifest, "--one-per-slot is incompatible with --manifest"), - (one_per_slot and has_emulator, "--one-per-slot is incompatible with --emulator"), - (one_per_slot and has_system, "--one-per-slot is incompatible with --system"), - ] - - -def _validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: - """Validate argument combinations and mutual exclusion rules. The - --verify-packs refusals ran before the quick-exit modes.""" - for refused, message in _argument_conflicts(args): - if refused: - parser.error(message) - - -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: - return - # It builds the six source x required combinations itself: a --source - # or --required-only beside it would be overridden, and the modes that - # build one pack (emulator, system, hashes) never read it. - for flag, given in ( - ("--source", args.source is not None), - ("--required-only", args.required_only), - ("--no-game-data", getattr(args, "no_game_data", False)), - ("--emulator", args.emulator), - ("--from-md5", args.from_md5 or args.from_md5_file), - ): - if given: - parser.error(f"{flag} is incompatible with --all-variants") - if args.system and not (args.platform or args.all): - parser.error("--all-variants requires --platform or --all") - - -def _refuse_refresh_data(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: - """Only the platform pack path refreshes the data directories. - - Elsewhere the cache on disk was packed as it stood, and --offline wins - over the refresh without a word. - """ - if args.refresh_data and args.no_refresh_data: - parser.error("--refresh-data is incompatible with --no-refresh-data") - for name, given in (("--refresh-data", args.refresh_data), - ("--no-refresh-data", args.no_refresh_data)): - if not given: - continue - for flag, on in ( - ("--offline", args.offline), - ("--emulator", args.emulator), - ("--system", args.system and not (args.platform or args.all)), - ("--from-md5", args.from_md5 or args.from_md5_file), - ): - if on: - parser.error(f"{name} is incompatible with {flag}") - - -def _refuse_unapplied_flags(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: - """Refuse every flag the requested mode would not apply. - - A mode applies a narrowing flag or refuses it: a swallowed flag answers - about an artifact the caller did not name. Run before any quick-exit - mode, since --verify-packs and --manifest-targets return early. - """ - # Parsed before the quick-exit modes: --verify-packs returns early and - # still needs the region priority list to narrow its expectation. - args.regions = requested_regions(args.region, parser) - if args.region and args.manifest_targets: - parser.error("--region is incompatible with --manifest-targets") - if args.one_per_slot and args.manifest_targets: - parser.error("--one-per-slot is incompatible with --manifest-targets") - _refuse_refresh_data(args, parser) - - _refuse_for_all_variants(args, parser) - refuse_beside_mode( - ( - ("--manifest-targets", args.manifest_targets), - ("--verify-packs", args.verify_packs and not args.all_variants), - ("--list-platforms", args.list), - ("--list-emulators", args.list_emulators), - ("--list-systems", args.list_systems), - ("--list-targets", args.list_targets), - ), - _given_flags(args), QUICK_MODE_FLAGS, parser, - ) - - -# What each mode that returns early reads. Anything else given beside it is -# refused: the mode would answer about an artifact the caller did not name. -QUICK_MODE_FLAGS: dict[str, set[str]] = { - # Checks packs already on disk against the platform's own list, narrowed - # by region and target and by nothing else. - "--verify-packs": { - "--platform", "--all", "--target", "--region", "--no-game-data", - }, - # One manifest per hardware target, from the target files themselves. - "--manifest-targets": set(), - **LISTING_FLAGS, -} - - -def _given_flags(args: argparse.Namespace) -> set[str]: - """Flags that select or narrow what a run produces, as typed.""" - flags = { - "--platform": args.platform, - "--all": args.all, - "--emulator": args.emulator, - "--system": args.system, - "--standalone": args.standalone, - "--split": args.split, - "--group-by": args.group_by is not None, - "--manifest": args.manifest, - "--manifest-targets": args.manifest_targets, - "--verify-packs": args.verify_packs, - "--all-variants": args.all_variants, - "--from-md5": args.from_md5, - "--from-md5-file": args.from_md5_file, - "--required-only": args.required_only, - "--no-game-data": getattr(args, "no_game_data", False), - "--source": args.source is not None, - "--target": args.target, - "--region": args.region, - "--one-per-slot": args.one_per_slot, - "--list-platforms": args.list, - "--list-emulators": args.list_emulators, - "--list-systems": args.list_systems, - "--list-targets": args.list_targets, - "--refresh-data": args.refresh_data, - "--no-refresh-data": args.no_refresh_data, - } - return {flag for flag, on in flags.items() if on} - - def main() -> None: # One run's account: tests call main() repeatedly in one process, and a # notice left by an earlier run failed a later one that missed nothing. MISSING_DATA_DIRS.clear() with contextlib.ExitStack() as held: try: - _main(held) + packmodes.run_pack_command(build_parser(), held) except (DamagedArchiveError, ArtifactLockBusy) as exc: # Emulator, system and hash modes have no per-platform loop to # report a damaged archive: the run stops with the file to @@ -284,7 +56,7 @@ def main() -> None: sys.exit(1) -def _build_parser() -> argparse.ArgumentParser: +def build_parser() -> argparse.ArgumentParser: """The command line of generate_pack.py.""" parser = argparse.ArgumentParser(allow_abbrev=False, description="Generate platform BIOS ZIP packs") parser.add_argument( @@ -398,182 +170,6 @@ def _build_parser() -> argparse.ArgumentParser: return parser -def _run_quick_mode( - args: argparse.Namespace, parser: argparse.ArgumentParser, held: contextlib.ExitStack, -) -> bool: - """Run a mode that builds nothing (a check of existing packs, the target - lists, a listing). True when one ran.""" - # Quick-exit modes: --verify-packs alone = verify existing packs only - # Combined with --all-variants, generation runs first then verify - if args.verify_packs and not args.all_variants: - # 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): - if not run_verify_packs(args): - sys.exit(1) - return True - if args.manifest_targets: - 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 - ) - return True - return run_listing(args, parser, args.list) - - -def _run_hash_mode(args: argparse.Namespace) -> None: - """--from-md5 and --from-md5-file: look the hashes up, or pack them.""" - try: - hashes = ( - parse_hash_input(args.from_md5) - if args.from_md5 - else parse_hash_file(args.from_md5_file) - ) - except ValueError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) - except OSError as exc: - print(f"ERROR: --from-md5-file {args.from_md5_file}: {exc.strerror}", file=sys.stderr) - sys.exit(1) - if not hashes: - print( - f"ERROR: no hash in the input. Accepted: {ACCEPTED_HASHES}", - file=sys.stderr, - ) - sys.exit(1) - db = load_database(args.db) - if not args.platform and not args.emulator: - # A lookup that found nothing is an answer a script must see. - if lookup_hashes( - hashes, db, args.bios_dir, args.emulators_dir, args.platforms_dir - ): - sys.exit(1) - return - zip_contents = build_zip_contents_index(db) - with pack_output_lock(args.output_dir): - result = generate_md5_pack( - hashes=hashes, - db=db, - bios_dir=args.bios_dir, - output_dir=args.output_dir, - zip_contents=zip_contents, - platform_name=args.platform, - platforms_dir=args.platforms_dir, - emulator_name=args.emulator, - emulators_dir=args.emulators_dir, - standalone=getattr(args, "standalone", False), - ) - if not result: - sys.exit(1) - - -def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> None: - """--emulator, or --system without a platform: the emulators' own layout.""" - # Emulator mode - if args.emulator: - names = comma_list(args.emulator) - with pack_output_lock(args.output_dir): - built = generate_emulator_pack( - names, - args.emulators_dir, - db, - args.bios_dir, - args.output_dir, - args.standalone, - zip_contents=zip_contents, - required_only=args.required_only, - regions=getattr(args, "regions", None), - offline=args.offline, - platforms_dir=args.platforms_dir, - ) - if built is None: - sys.exit(1) - return - - # System mode (standalone, without platform context) - system_ids = comma_list(args.system) - with pack_output_lock(args.output_dir): - built = generate_system_pack( - system_ids, - args.emulators_dir, - db, - args.bios_dir, - args.output_dir, - args.standalone, - zip_contents=zip_contents, - required_only=args.required_only, - regions=getattr(args, "regions", None), - offline=args.offline, - platforms_dir=args.platforms_dir, - ) - if built is None: - sys.exit(1) - - -def _requested_platforms(args: argparse.Namespace, parser: argparse.ArgumentParser) -> list[str]: - """The platforms a platform run builds for.""" - if args.all and args.manifest: - # Install manifests cover every registered platform: the installer - # serves each one, with or without a release pack. - return list_registered_platforms(args.platforms_dir) - if args.all: - # A release publishes the packs the registry marks release_pack and - # nothing else: a pack built for another platform is one nobody uploads. - platforms = list_release_pack_platforms(args.platforms_dir) - if not platforms: - parser.error("no registered platform has release_pack: true") - return platforms - if not args.platform: - parser.error("Specify --platform or --all") - return [args.platform] - - -def _main(held: contextlib.ExitStack) -> None: - parser = _build_parser() - args = parser.parse_args() - from model.cliargs import work_from_repo_root - - work_from_repo_root( - args, parser, - ["db", "platforms_dir", "bios_dir", "output_dir", "emulators_dir", "from_md5_file"], - ) - packresolve.set_offline(bool(args.offline)) - if args.platform: - require_platform(args.platform, args.platforms_dir) - require_directory(args.bios_dir) - - _refuse_unapplied_flags(args, parser) - _refuse_for_verify_packs(args, parser) - if _run_quick_mode(args, parser, held): - return - - _validate_args(args, parser) - args.system_ids = resolve_system_ids(args, parser) - # Unset until every refusal has run, so a typed default value is seen. - args.source = args.source or "full" - args.group_by = args.group_by or "system" - - # Hash lookup / pack mode - # A platform run may refresh the trees below, under the exclusive lock: - # it takes the shared ones after that. Every other mode reads them now. - if not (args.platform or args.all) or args.offline or args.no_refresh_data: - hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) - if args.from_md5 or getattr(args, "from_md5_file", None): - _run_hash_mode(args) - return - - db = load_database(args.db) - zip_contents = build_zip_contents_index(db) - if args.emulator or (args.system and not args.platform and not args.all): - _run_profile_mode(args, db, zip_contents) - return - if not run_platform_mode(args, _requested_platforms(args, parser), held, db, zip_contents): - sys.exit(1) - - if __name__ == "__main__": from core.cli import run_cli diff --git a/scripts/packs/packmodes.py b/scripts/packs/packmodes.py new file mode 100644 index 000000000..9616da24a --- /dev/null +++ b/scripts/packs/packmodes.py @@ -0,0 +1,191 @@ +"""Run modes of generate_pack.py: checks, listings, hash and profile packs, platform runs.""" + +from __future__ import annotations + +import argparse +import contextlib +import os +import sys + +from core.cli import require_directory +from core.ziptools import build_zip_contents_index +from model.cliargs import ( + comma_list, + require_platform, + resolve_system_ids, + run_listing, + work_from_repo_root, +) +from model.database import load_database +from model.registry import load_data_dir_registry +from packs.datadirs import hold_data_dirs +from packs.emulatorpack import generate_emulator_pack, generate_system_pack +from packs.md5pack import generate_md5_pack +from packs.outputdir import holds_other_kind, pack_output_lock +from packs.packcheck import run_verify_packs +from packs.packoptions import refuse_for_verify_packs, refuse_unapplied_flags, validate_args +from packs.platformrun import requested_platforms, 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, +) + + +def _run_quick_mode( + args: argparse.Namespace, parser: argparse.ArgumentParser, held: contextlib.ExitStack, +) -> bool: + """Run a mode that builds nothing (a check of existing packs, the target + lists, a listing). True when one ran.""" + # Quick-exit modes: --verify-packs alone = verify existing packs only + # Combined with --all-variants, generation runs first then verify + if args.verify_packs and not args.all_variants: + # 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): + if not run_verify_packs(args): + sys.exit(1) + return True + if args.manifest_targets: + 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 + ) + return True + return run_listing(args, parser, args.list) + + +def _run_hash_mode(args: argparse.Namespace) -> None: + """--from-md5 and --from-md5-file: look the hashes up, or pack them.""" + try: + hashes = ( + parse_hash_input(args.from_md5) + if args.from_md5 + else parse_hash_file(args.from_md5_file) + ) + except ValueError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + except OSError as exc: + print(f"ERROR: --from-md5-file {args.from_md5_file}: {exc.strerror}", file=sys.stderr) + sys.exit(1) + if not hashes: + print( + f"ERROR: no hash in the input. Accepted: {ACCEPTED_HASHES}", + file=sys.stderr, + ) + sys.exit(1) + db = load_database(args.db) + if not args.platform and not args.emulator: + # A lookup that found nothing is an answer a script must see. + if lookup_hashes( + hashes, db, args.bios_dir, args.emulators_dir, args.platforms_dir + ): + sys.exit(1) + return + zip_contents = build_zip_contents_index(db) + with pack_output_lock(args.output_dir): + result = generate_md5_pack( + hashes=hashes, + db=db, + bios_dir=args.bios_dir, + output_dir=args.output_dir, + zip_contents=zip_contents, + platform_name=args.platform, + platforms_dir=args.platforms_dir, + emulator_name=args.emulator, + emulators_dir=args.emulators_dir, + standalone=getattr(args, "standalone", False), + ) + if not result: + sys.exit(1) + + +def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> None: + """--emulator, or --system without a platform: the emulators' own layout.""" + # Emulator mode + if args.emulator: + names = comma_list(args.emulator) + with pack_output_lock(args.output_dir): + built = generate_emulator_pack( + names, + args.emulators_dir, + db, + args.bios_dir, + args.output_dir, + args.standalone, + zip_contents=zip_contents, + required_only=args.required_only, + regions=getattr(args, "regions", None), + offline=args.offline, + platforms_dir=args.platforms_dir, + ) + if built is None: + sys.exit(1) + return + + # System mode (standalone, without platform context) + system_ids = comma_list(args.system) + with pack_output_lock(args.output_dir): + built = generate_system_pack( + system_ids, + args.emulators_dir, + db, + args.bios_dir, + args.output_dir, + args.standalone, + zip_contents=zip_contents, + required_only=args.required_only, + regions=getattr(args, "regions", None), + offline=args.offline, + platforms_dir=args.platforms_dir, + ) + if built is None: + sys.exit(1) + + +def run_pack_command(parser: argparse.ArgumentParser, held: contextlib.ExitStack) -> None: + """One run of generate_pack.py, from its command line to the mode it names.""" + args = parser.parse_args() + work_from_repo_root( + args, parser, + ["db", "platforms_dir", "bios_dir", "output_dir", "emulators_dir", "from_md5_file"], + ) + packresolve.set_offline(bool(args.offline)) + if args.platform: + require_platform(args.platform, args.platforms_dir) + require_directory(args.bios_dir) + + refuse_unapplied_flags(args, parser) + refuse_for_verify_packs(args, parser) + if _run_quick_mode(args, parser, held): + return + + validate_args(args, parser) + args.system_ids = resolve_system_ids(args, parser) + # Unset until every refusal has run, so a typed default value is seen. + args.source = args.source or "full" + args.group_by = args.group_by or "system" + + # Hash lookup / pack mode + # A platform run may refresh the trees below, under the exclusive lock: + # it takes the shared ones after that. Every other mode reads them now. + if not (args.platform or args.all) or args.offline or args.no_refresh_data: + hold_data_dirs(held, load_data_dir_registry(args.platforms_dir)) + if args.from_md5 or getattr(args, "from_md5_file", None): + _run_hash_mode(args) + return + + db = load_database(args.db) + zip_contents = build_zip_contents_index(db) + if args.emulator or (args.system and not args.platform and not args.all): + _run_profile_mode(args, db, zip_contents) + return + if not run_platform_mode(args, requested_platforms(args, parser), held, db, zip_contents): + sys.exit(1) diff --git a/scripts/packs/packoptions.py b/scripts/packs/packoptions.py new file mode 100644 index 000000000..142a93b92 --- /dev/null +++ b/scripts/packs/packoptions.py @@ -0,0 +1,210 @@ +"""Option checks of generate_pack.py: the combinations each mode refuses.""" + +from __future__ import annotations + +import argparse + +from model.cliargs import ( + LISTING_FLAGS, + mode_conflicts, + refuse_beside_mode, + requested_regions, +) + + +def refuse_for_verify_packs(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + """What --verify-packs cannot be combined with, refused before any lock. + + These lived in the --all-variants checks, which return at once without + that flag: --verify-packs --manifest or --split went through, and a run + with neither --platform nor --all failed after locking the directory. + """ + if not args.verify_packs: + return + if args.manifest: + parser.error("--verify-packs is incompatible with --manifest") + if not (args.platform or args.all): + parser.error("--verify-packs requires --platform or --all") + # The check that follows the build reads the full pack's name. + for flag, given in ( + ("--system", args.system), + ("--one-per-slot", args.one_per_slot), + ("--split", args.split), + ): + if given: + parser.error(f"{flag} is incompatible with --verify-packs") + + +def _argument_conflicts(args: argparse.Namespace) -> list[tuple[bool, str]]: + """Each refused combination of arguments with its message, in the order + they are checked: the first one that applies is the error reported.""" + has_platform = bool(args.platform) + has_all = args.all + has_emulator = bool(args.emulator) + has_system = bool(args.system) + md5_file = getattr(args, "from_md5_file", None) + has_from_md5 = bool(args.from_md5 or md5_file) + # A mode either applies a narrowing flag or refuses it. Swallowing one + # answers about an artifact the caller did not ask for, and the name on + # disk then asserts a narrowing the contents do not carry. + # --source and --group-by default to None so a typed default value is + # seen: compared with "full", `--emulator X --source full` went through. + source_given = getattr(args, "source", None) is not None + with_platform = has_system and (has_platform or has_all) + no_game_data = getattr(args, "no_game_data", False) + one_per_slot = getattr(args, "one_per_slot", False) + return [ + (bool(args.from_md5 and md5_file), "--from-md5 and --from-md5-file are mutually exclusive"), + (has_from_md5 and has_all, "--from-md5 requires --platform or --emulator, not --all"), + (has_from_md5 and has_system, "--from-md5 and --system are mutually exclusive"), + (has_from_md5 and args.split, "--split and --from-md5 are mutually exclusive"), + *mode_conflicts(args, (("--from-md5", has_from_md5),)), + (args.split and not (has_platform or has_all), "--split requires --platform or --all"), + (args.split and has_emulator, "--split is incompatible with --emulator"), + (args.group_by is not None and not args.split, "--group-by requires --split"), + (args.manifest and not (has_platform or has_all), + "--manifest requires --platform or --all"), + (args.manifest and has_emulator, "--manifest is incompatible with --emulator"), + (args.manifest and args.split, "--manifest is incompatible with --split"), + (getattr(args, "region", None) and has_from_md5, + "--region and --from-md5 are mutually exclusive"), + (source_given and (has_emulator or (has_system and not has_platform)), + "--source requires --platform or --all"), + (has_from_md5 and args.manifest, "--manifest is incompatible with --from-md5"), + (has_from_md5 and args.target, "--target is incompatible with --from-md5"), + (has_from_md5 and args.required_only, "--required-only is incompatible with --from-md5"), + (has_from_md5 and source_given, "--source is incompatible with --from-md5"), + (with_platform and args.manifest, "--system is incompatible with --manifest"), + (with_platform and args.split, "--system is incompatible with --split"), + (no_game_data and has_from_md5, "--no-game-data is incompatible with --from-md5"), + (one_per_slot and has_from_md5, "--one-per-slot and --from-md5 are mutually exclusive"), + (one_per_slot and args.manifest, "--one-per-slot is incompatible with --manifest"), + (one_per_slot and has_emulator, "--one-per-slot is incompatible with --emulator"), + (one_per_slot and has_system, "--one-per-slot is incompatible with --system"), + ] + + +def validate_args(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + """Validate argument combinations and mutual exclusion rules. The + --verify-packs refusals ran before the quick-exit modes.""" + for refused, message in _argument_conflicts(args): + if refused: + parser.error(message) + + +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: + return + # It builds the six source x required combinations itself: a --source + # or --required-only beside it would be overridden, and the modes that + # build one pack (emulator, system, hashes) never read it. + for flag, given in ( + ("--source", args.source is not None), + ("--required-only", args.required_only), + ("--no-game-data", getattr(args, "no_game_data", False)), + ("--emulator", args.emulator), + ("--from-md5", args.from_md5 or args.from_md5_file), + ): + if given: + parser.error(f"{flag} is incompatible with --all-variants") + if args.system and not (args.platform or args.all): + parser.error("--all-variants requires --platform or --all") + + +def _refuse_refresh_data(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + """Only the platform pack path refreshes the data directories. + + Elsewhere the cache on disk was packed as it stood, and --offline wins + over the refresh without a word. + """ + if args.refresh_data and args.no_refresh_data: + parser.error("--refresh-data is incompatible with --no-refresh-data") + for name, given in (("--refresh-data", args.refresh_data), + ("--no-refresh-data", args.no_refresh_data)): + if not given: + continue + for flag, on in ( + ("--offline", args.offline), + ("--emulator", args.emulator), + ("--system", args.system and not (args.platform or args.all)), + ("--from-md5", args.from_md5 or args.from_md5_file), + ): + if on: + parser.error(f"{name} is incompatible with {flag}") + + +def refuse_unapplied_flags(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + """Refuse every flag the requested mode would not apply. + + A mode applies a narrowing flag or refuses it: a swallowed flag answers + about an artifact the caller did not name. Run before any quick-exit + mode, since --verify-packs and --manifest-targets return early. + """ + # Parsed before the quick-exit modes: --verify-packs returns early and + # still needs the region priority list to narrow its expectation. + args.regions = requested_regions(args.region, parser) + if args.region and args.manifest_targets: + parser.error("--region is incompatible with --manifest-targets") + if args.one_per_slot and args.manifest_targets: + parser.error("--one-per-slot is incompatible with --manifest-targets") + _refuse_refresh_data(args, parser) + + _refuse_for_all_variants(args, parser) + refuse_beside_mode( + ( + ("--manifest-targets", args.manifest_targets), + ("--verify-packs", args.verify_packs and not args.all_variants), + ("--list-platforms", args.list), + ("--list-emulators", args.list_emulators), + ("--list-systems", args.list_systems), + ("--list-targets", args.list_targets), + ), + _given_flags(args), QUICK_MODE_FLAGS, parser, + ) + + +# What each mode that returns early reads. Anything else given beside it is +# refused: the mode would answer about an artifact the caller did not name. +QUICK_MODE_FLAGS: dict[str, set[str]] = { + # Checks packs already on disk against the platform's own list, narrowed + # by region and target and by nothing else. + "--verify-packs": { + "--platform", "--all", "--target", "--region", "--no-game-data", + }, + # One manifest per hardware target, from the target files themselves. + "--manifest-targets": set(), + **LISTING_FLAGS, +} + + +def _given_flags(args: argparse.Namespace) -> set[str]: + """Flags that select or narrow what a run produces, as typed.""" + flags = { + "--platform": args.platform, + "--all": args.all, + "--emulator": args.emulator, + "--system": args.system, + "--standalone": args.standalone, + "--split": args.split, + "--group-by": args.group_by is not None, + "--manifest": args.manifest, + "--manifest-targets": args.manifest_targets, + "--verify-packs": args.verify_packs, + "--all-variants": args.all_variants, + "--from-md5": args.from_md5, + "--from-md5-file": args.from_md5_file, + "--required-only": args.required_only, + "--no-game-data": getattr(args, "no_game_data", False), + "--source": args.source is not None, + "--target": args.target, + "--region": args.region, + "--one-per-slot": args.one_per_slot, + "--list-platforms": args.list, + "--list-emulators": args.list_emulators, + "--list-systems": args.list_systems, + "--list-targets": args.list_targets, + "--refresh-data": args.refresh_data, + "--no-refresh-data": args.no_refresh_data, + } + return {flag for flag, on in flags.items() if on} diff --git a/scripts/packs/platformrun.py b/scripts/packs/platformrun.py index e2dcf7c60..940a652c5 100644 --- a/scripts/packs/platformrun.py +++ b/scripts/packs/platformrun.py @@ -11,7 +11,11 @@ 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.registry import ( + list_registered_platforms, + list_release_pack_platforms, + load_data_dir_registry, +) from model.safeparse import require_yaml from model.targets import target_scope from packs.datadirs import hold_data_dirs @@ -332,3 +336,21 @@ def run_platform_mode( with pack_output_lock(args.output_dir, exclusive=False): return run_verify_packs(args) return True + + +def requested_platforms(args: argparse.Namespace, parser: argparse.ArgumentParser) -> list[str]: + """The platforms a platform run builds for.""" + if args.all and args.manifest: + # Install manifests cover every registered platform: the installer + # serves each one, with or without a release pack. + return list_registered_platforms(args.platforms_dir) + if args.all: + # A release publishes the packs the registry marks release_pack and + # nothing else: a pack built for another platform is one nobody uploads. + platforms = list_release_pack_platforms(args.platforms_dir) + if not platforms: + parser.error("no registered platform has release_pack: true") + return platforms + if not args.platform: + parser.error("Specify --platform or --all") + return [args.platform] diff --git a/tests/sources.py b/tests/sources.py index 2d48b58a2..5ec85fc0d 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -21,6 +21,7 @@ COMMANDS = { "packs/manifestentry.py", "packs/manifestcores.py", "packs/standalone.py", "packs/manifest.py", "packs/finalize.py", "packs/outputdir.py", "packs/variants.py", "packs/manifestrun.py", "packs/packcheck.py", "packs/platformrun.py", + "packs/packoptions.py", "packs/packmodes.py", ), "verify.py": ( "packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py", diff --git a/tests/test_core_file_fills_declaration.py b/tests/test_core_file_fills_declaration.py index 4bc02d485..efce43215 100644 --- a/tests/test_core_file_fills_declaration.py +++ b/tests/test_core_file_fills_declaration.py @@ -151,7 +151,7 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): def test_the_pack_records_it_and_main_exits_non_zero(self): import generate_pack as gp - from packs import datatrees + from packs import datatrees, packmodes from packs import platformpack root = Path(tempfile.mkdtemp()) @@ -179,7 +179,8 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): ) self.assertEqual(datatrees.MISSING_DATA_DIRS, {"assets"}) # main() starts each run with no notices, so the run itself records it. - with mock.patch.object(gp, "_main", lambda held: datatrees.MISSING_DATA_DIRS.add("assets")), \ + with mock.patch.object(packmodes, "run_pack_command", + lambda parser, held: datatrees.MISSING_DATA_DIRS.add("assets")), \ contextlib.redirect_stderr(io.StringIO()), \ self.assertRaises(SystemExit) as stop: gp.main() diff --git a/tests/test_target_verify.py b/tests/test_target_verify.py index 1b3eaaf67..bcfe13b1e 100644 --- a/tests/test_target_verify.py +++ b/tests/test_target_verify.py @@ -68,7 +68,7 @@ class AMistypedTargetIsRefusedFirst(unittest.TestCase): from unittest import mock import generate_pack - from packs import platformrun + from packs import packmodes, platformrun def touched(*_a, **_kw): raise AssertionError("lock or refresh taken before the target check") @@ -77,8 +77,8 @@ 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, "hold_data_dirs", touched), \ + mock.patch.object(packmodes, "pack_output_lock", touched), \ + mock.patch.object(packmodes, "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()), \