refactor: move generate_pack modes into packs

Option checks go to packs/packoptions.py, the run modes to
packs/packmodes.py and the platform choice to packs/platformrun.py.
generate_pack.py keeps main() and build_parser(). Tests patch the
package modules instead of command attributes.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 15:47:20 +01:00
1 parent ac06822d2e
commit 37ec04aed1
7 files changed
+436 -415

No files matched your search

+5 -409
View File
@@ -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