diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 162100bd5..8e4232a8d 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -28,29 +28,28 @@ from core.artifacts import ArtifactLockBusy from core.cli import add_emulator_selection, add_repo_inputs from model.cliargs import platform_arg from packs.archive import DamagedArchiveError -from packs.datatrees import MISSING_DATA_DIRS from packs import packmodes DEFAULT_OUTPUT_DIR = "dist" 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: - packmodes.run_pack_command(build_parser(), held) + args = 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 # restore. A busy output directory refuses the run. print(f"ERROR: {exc}", file=sys.stderr) sys.exit(1) - if MISSING_DATA_DIRS: + # A refresh refused by a quota left the PPSSPP pack with 2 files, exit 0: + # a run written without a tree it carries is not complete. + if args.uncached_trees: + written = "manifests" if args.manifest else "packs" print( - "ERROR: packs written without data directories that are not cached: " - f"{', '.join(sorted(MISSING_DATA_DIRS))} (run refresh_data_dirs.py)", + f"ERROR: {written} written without data directories that are not cached: " + f"{', '.join(sorted(args.uncached_trees))} (run refresh_data_dirs.py)", file=sys.stderr, ) sys.exit(1) diff --git a/scripts/orchestrate/compare.py b/scripts/orchestrate/compare.py index 3a13e2021..7accb6f96 100644 --- a/scripts/orchestrate/compare.py +++ b/scripts/orchestrate/compare.py @@ -2,8 +2,6 @@ from __future__ import annotations -import contextlib -import io import os import re @@ -36,13 +34,12 @@ def tree_members( config, load_emulator_profiles(emulators_dir), platform, registry, ) members: dict[str, int] = {} - with contextlib.redirect_stdout(io.StringIO()): - for src, full in datatrees.data_directory_members( - config.get("systems", {}), registry, - platform, base_dest, Placed(False), - core_trees=core_trees, - ): - members[flat_arcname(full, base_dest, True)] = os.path.getsize(src) + for src, full in datatrees.data_directory_members( + config.get("systems", {}), registry, + platform, base_dest, Placed(False), + core_trees=core_trees, + ): + members[flat_arcname(full, base_dest, True)] = os.path.getsize(src) return members diff --git a/scripts/packs/datatrees.py b/scripts/packs/datatrees.py index c093bea07..6590e1119 100644 --- a/scripts/packs/datatrees.py +++ b/scripts/packs/datatrees.py @@ -142,13 +142,15 @@ class _TreeWalkOptions(TypedDict, total=False): """The keyword options of data_directory_members.""" refs_out: dict | None + uncached_out: list[tuple[str, str]] | None required_only: bool core_trees: Iterable[dict] reclaim: dict[str, str] | None def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> str | None: - """The cache folder of a tree reference the pack carries, or None.""" + """The cache folder of a tree reference the pack carries ("" when the + cache does not hold it), or None for a tree the pack does not carry.""" ref_key = dd.get("ref", "") if not ref_key or not data_registry or ref_key not in data_registry: return None @@ -158,14 +160,12 @@ def _carried_tree(dd: dict, data_registry: dict | None, platform_name: str) -> s allowed = entry.get("for_platforms") if allowed and platform_name not in allowed: return None - local_path = entry.get("local_cache", "") - if not local_path or not os.path.isdir(local_path): - print( - f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)" - ) - MISSING_DATA_DIRS.add(ref_key) - return None - return local_path + return entry.get("local_cache", "") + + +def uncached_warning(ref_key: str, local_path: str) -> str: + """The line a build prints for a tree it carries and the cache does not hold.""" + return f" WARNING: data directory '{ref_key}' not cached at {local_path} (run refresh_data_dirs.py)" def _tree_files(local_path: str, dd_prefix: str) -> Iterator[tuple[str, str]]: @@ -198,6 +198,10 @@ def data_directory_members( (registry key, system ids, directory destination, whether the core needs the tree), for the manifest. + ``uncached_out``, when given, receives (registry key, cache folder) for + each tree the pack carries and the cache does not hold: the caller + reports it and counts its run incomplete. + These are not BIOS and carry no hash of their own: they are whole trees an emulator reads, refreshed from upstream, so what ships is whatever the cache holds. The pack and the install manifest both read @@ -207,6 +211,7 @@ def data_directory_members( """ reject_unknown("data_directory_members", options, _TreeWalkOptions.__optional_keys__) refs_out = options.get("refs_out") + uncached_out = options.get("uncached_out") reclaim = options.get("reclaim") required_only = options.get("required_only", False) core_trees = options.get("core_trees", ()) @@ -219,6 +224,10 @@ def data_directory_members( if local_path is None: continue ref_key = dd.get("ref", "") + if not local_path or not os.path.isdir(local_path): + if uncached_out is not None: + uncached_out.append((ref_key, local_path)) + continue dd_dest = dd.get("destination", "") dd_prefix = f"{base_dest}/{dd_dest}" if base_dest and dd_dest else base_dest or dd_dest # Held while the caller writes what is yielded: a refresh swapping @@ -269,12 +278,6 @@ def pack_data_tree( return added -# Data directories a pack needed and the cache did not hold. The pack is -# written without them, so the run cannot exit as if it were complete: a -# refresh refused by a quota left the PPSSPP pack with 2 files, exit 0. -MISSING_DATA_DIRS: set[str] = set() - - def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, list[str]]: """The cores that read each tree, for a tree only cores read. A tree a platform system declares is the system's, whatever core runs it, and diff --git a/scripts/packs/manifest.py b/scripts/packs/manifest.py index 15b5e6502..55c92e578 100644 --- a/scripts/packs/manifest.py +++ b/scripts/packs/manifest.py @@ -26,6 +26,7 @@ from packs.datatrees import ( core_data_trees, pack_markers, tree_readers, + uncached_warning, ) from packs.extras import ( collect_emulator_extras, @@ -95,6 +96,7 @@ class InstallListOptions(TypedDict, total=False): fold_case: bool | None no_game_data: bool one_per_slot: bool + uncached_out: set[str] | None class ManifestOptions(InstallListOptions, total=False): @@ -123,6 +125,7 @@ class _ManifestSettings: one_per_slot: bool = False known_slot_choices: dict | None = None build_out: dict | None = None + uncached_out: set[str] | None = None @dataclass @@ -469,12 +472,17 @@ class _ManifestBuild: core_trees = ([] if opts.source == "platform" else core_data_trees(self.config, self.emu_profiles, self.platform_name, self.data_registry, opts.target_cores)) + uncached: list[tuple[str, str]] = [] self.data_members = list(data_directory_members( self.pack_systems, self.data_registry, self.platform_name, self.base_dest, self.placed, refs_out=data_refs, required_only=required_only, core_trees=core_trees, - reclaim=reclaim, + reclaim=reclaim, uncached_out=uncached, )) + for ref_key, local_path in uncached: + print(uncached_warning(ref_key, local_path)) + if opts.uncached_out is not None: + opts.uncached_out.update(ref_key for ref_key, _path in uncached) # A platform entry found in a tree the pack carries is that tree's member: # the installer rebuilds it from the tree's archive. One found in a tree # the pack does not carry stays omitted, held by the pack alone. @@ -705,6 +713,8 @@ def generate_manifest( One build: generate_install_list adds what --source truth and --standalone read. `build_out` receives the slot choices and the profiles this build read, which that second build takes over. + `uncached_out` receives the data directories the list carries and the + cache does not hold. """ reject_unknown("generate_manifest", options, ManifestOptions.__optional_keys__) opts = _ManifestSettings(**options) diff --git a/scripts/packs/manifestrun.py b/scripts/packs/manifestrun.py index 5a716e5a0..5652d999e 100644 --- a/scripts/packs/manifestrun.py +++ b/scripts/packs/manifestrun.py @@ -102,6 +102,7 @@ def run_manifest_mode( required_only=required_only, no_game_data=getattr(args, "no_game_data", False), standalone_out=layouts, + uncached_out=getattr(args, "uncached_trees", None), ) narrow_suffix = "".join( tag.lower() diff --git a/scripts/packs/packmodes.py b/scripts/packs/packmodes.py index 98ee7fc1a..95ddd2e6a 100644 --- a/scripts/packs/packmodes.py +++ b/scripts/packs/packmodes.py @@ -19,7 +19,6 @@ from model.cliargs import ( from model.database import load_database from model.registry import load_data_dir_registry from packs.datadirs import hold_data_dirs -from packs.datatrees import MISSING_DATA_DIRS from packs.emulatorpack import ( EmulatorPackOutcome, build_emulator_pack, @@ -133,7 +132,7 @@ def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> platforms_dir=args.platforms_dir, progress=print, ) - _account(outcome) + _account(outcome, args.uncached_trees) return # System mode (standalone, without platform context) @@ -153,20 +152,27 @@ def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> platforms_dir=args.platforms_dir, progress=print, ) - _account(outcome) + _account(outcome, args.uncached_trees) -def _account(outcome: EmulatorPackOutcome) -> None: +def _account(outcome: EmulatorPackOutcome, uncached: set[str]) -> None: """Print a profile pack, add its data directory notices to the run, stop on failure.""" built = print_emulator_pack(outcome) - MISSING_DATA_DIRS.update(outcome.data_dir_notices) + uncached.update(outcome.data_dir_notices) 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.""" +def run_pack_command( + parser: argparse.ArgumentParser, held: contextlib.ExitStack, +) -> argparse.Namespace: + """One run of generate_pack.py, from its command line to the mode it names. + + Returns its arguments, with ``uncached_trees``: the data directories the + run's packs or manifests carry and the cache does not hold. + """ args = parser.parse_args() + args.uncached_trees = set() work_from_repo_root( args, parser, ["db", "platforms_dir", "bios_dir", "output_dir", "emulators_dir", "from_md5_file"], @@ -179,7 +185,7 @@ def run_pack_command(parser: argparse.ArgumentParser, held: contextlib.ExitStack refuse_unapplied_flags(args, parser) refuse_for_verify_packs(args, parser) if _run_quick_mode(args, parser, held): - return + return args validate_args(args, parser) args.system_ids = resolve_system_ids(args, parser) @@ -194,12 +200,13 @@ def run_pack_command(parser: argparse.ArgumentParser, held: contextlib.ExitStack 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 + return args 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 + return args if not run_platform_mode(args, requested_platforms(args, parser), held, db, zip_contents): sys.exit(1) + return args diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index f4a0a2f73..543534218 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -33,7 +33,12 @@ from packs.archive import ( write_generated_member, writing_pack, ) -from packs.datatrees import data_directory_members, core_data_trees, pack_markers +from packs.datatrees import ( + core_data_trees, + data_directory_members, + pack_markers, + uncached_warning, +) from packs.naming import system_display_name from packs.extras import ( ExtraResolver, @@ -310,6 +315,7 @@ class PackOptions(PackNarrowing, _PartScope, total=False): pack_name: str | None record: PackRecord | None within: dict[str, str] | None + uncached_out: set[str] | None @dataclass(frozen=True) @@ -335,6 +341,7 @@ class _PackSettings: no_game_data: bool = False record: PackRecord | None = None within: dict[str, str] | None = None + uncached_out: set[str] | None = None @dataclass @@ -954,15 +961,20 @@ class _PlatformPackBuild: plan = self.plan required_only = plan.opts.required_only added = 0 + uncached: list[tuple[str, str]] = [] for src, full in data_directory_members( pack_systems, plan.opts.data_registry, plan.platform_name, plan.base_dest, self.placed, required_only=required_only, - core_trees=core_trees, + core_trees=core_trees, uncached_out=uncached, ): add_pack_member(self.zf, src, self._flat(full)) if isinstance(self.zf, PackRecord): self.zf.trees.append(self._flat(full)) added += 1 + for ref_key, local_path in uncached: + print(uncached_warning(ref_key, local_path)) + if plan.opts.uncached_out is not None: + plan.opts.uncached_out.update(ref_key for ref_key, _path in uncached) return added def _unfolded_twins(self) -> None: @@ -1090,6 +1102,9 @@ def generate_pack( their extras, so a path the full pack settles (a file/directory conflict, a case twin, a path another system's file takes) was written again. + ``uncached_out`` receives the data directories the pack carries and the + cache does not hold: the pack is written without them. + Returns the path to the generated ZIP, or None on failure. """ reject_unknown("generate_pack", options, PackOptions.__optional_keys__) @@ -1158,6 +1173,7 @@ class SplitOptions(PackNarrowing, total=False): """The keyword options of generate_split_packs.""" records: dict[str, PackRecord] | None + uncached_out: set[str] | None def _split_extras(config: dict, db: dict, narrowing: PackNarrowing) -> list[dict]: @@ -1250,10 +1266,11 @@ def generate_split_packs( emu_profiles = load_emulator_profiles(narrowing["emulators_dir"]) narrowing["emu_profiles"] = emu_profiles full = PackRecord() + # The parts add up to the full pack: its trees are the run's account. with contextlib.redirect_stdout(io.StringIO()): generate_pack( platform_name, platforms_dir, db, bios_dir, split_dir, - record=full, **narrowing, + record=full, uncached_out=options.get("uncached_out"), **narrowing, ) def part(pack_name: str, scope: _PartScope) -> str | None: diff --git a/scripts/packs/platformrun.py b/scripts/packs/platformrun.py index 8818dcb58..8d170d44a 100644 --- a/scripts/packs/platformrun.py +++ b/scripts/packs/platformrun.py @@ -101,6 +101,7 @@ def run_platform_packs( one_per_slot=args.one_per_slot, offline=args.offline, no_game_data=getattr(args, "no_game_data", False), + uncached_out=getattr(args, "uncached_trees", None), ) print(f" Split into {len(zip_paths)} packs") else: @@ -136,6 +137,7 @@ def run_platform_packs( offline=args.offline, pack_name=group_name, no_game_data=getattr(args, "no_game_data", False), + uncached_out=getattr(args, "uncached_trees", None), ) except (FileNotFoundError, OSError, yaml.YAMLError) as e: print(f" ERROR: {e}", file=sys.stderr) @@ -165,6 +167,7 @@ def run_platform_packs( offline=args.offline, required_only=required_only, data_registry=data_registry, no_game_data=getattr(args, "no_game_data", False), + uncached_out=getattr(args, "uncached_trees", None), ), 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) diff --git a/tests/test_core_file_fills_declaration.py b/tests/test_core_file_fills_declaration.py index efce43215..5e600c8bf 100644 --- a/tests/test_core_file_fills_declaration.py +++ b/tests/test_core_file_fills_declaration.py @@ -149,11 +149,7 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): """A refresh refused by a quota left the PPSSPP pack with 2 files and the run exited 0: nothing downstream checks data directories.""" - def test_the_pack_records_it_and_main_exits_non_zero(self): - import generate_pack as gp - from packs import datatrees, packmodes - from packs import platformpack - + def _platform(self) -> tuple[Path, dict, dict]: root = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, root, True) (root / "platforms").mkdir() @@ -166,26 +162,88 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase): {"ref": "assets", "destination": "assets"}, ]}}, })) - db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {}, - "by_path_suffix": {}}} - datatrees.MISSING_DATA_DIRS.clear() - self.addCleanup(datatrees.MISSING_DATA_DIRS.clear) - with redirect_stdout(io.StringIO()): + db: dict = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {}, + "by_path_suffix": {}}} + return root, db, {"assets": {"local_cache": str(root / "absent")}} + + def test_the_pack_records_it(self): + from packs import platformpack + + root, db, registry = self._platform() + uncached: set[str] = set() + out = io.StringIO() + with redirect_stdout(out): platformpack.generate_pack( "fakeplat", str(root / "platforms"), db, str(root / "bios"), str(root / "out"), emulators_dir=str(root / "emulators"), - data_registry={"assets": {"local_cache": str(root / "absent")}}, - offline=True, + data_registry=registry, offline=True, uncached_out=uncached, ) - self.assertEqual(datatrees.MISSING_DATA_DIRS, {"assets"}) - # main() starts each run with no notices, so the run itself records it. - with mock.patch.object(packmodes, "run_pack_command", - lambda parser, held: datatrees.MISSING_DATA_DIRS.add("assets")), \ - contextlib.redirect_stderr(io.StringIO()), \ + self.assertEqual(uncached, {"assets"}) + self.assertIn( + f" WARNING: data directory 'assets' not cached at {root / 'absent'}" + " (run refresh_data_dirs.py)\n", + out.getvalue(), + ) + + def test_the_manifest_records_it(self): + from packs.manifest import generate_manifest + + root, db, registry = self._platform() + uncached: set[str] = set() + out = io.StringIO() + with redirect_stdout(out): + generate_manifest( + "fakeplat", str(root / "platforms"), db, str(root / "bios"), + str(root / "platforms" / "_registry.yml"), + emulators_dir=str(root / "emulators"), + data_registry=registry, offline=True, uncached_out=uncached, + ) + self.assertEqual(uncached, {"assets"}) + self.assertIn("WARNING: data directory 'assets' not cached", out.getvalue()) + + def test_the_shared_walk_prints_nothing_and_keeps_no_state(self): + from packs import datatrees + from packs.archive import Placed + + root, _db, registry = self._platform() + systems = {"s": {"files": [], "data_directories": [ + {"ref": "assets", "destination": "a"}]}} + uncached: list[tuple[str, str]] = [] + out = io.StringIO() + with redirect_stdout(out): + members = list(datatrees.data_directory_members( + systems, registry, "x", "", Placed(False), uncached_out=uncached, + )) + again = list(datatrees.data_directory_members( + systems, registry, "x", "", Placed(False), + )) + self.assertEqual((members, again, out.getvalue()), ([], [], "")) + self.assertEqual(uncached, [("assets", str(root / "absent"))]) + self.assertFalse(hasattr(datatrees, "MISSING_DATA_DIRS")) + + def _main_stderr(self, manifest: bool) -> tuple[object, str]: + import argparse + import generate_pack as gp + from packs import packmodes + + args = argparse.Namespace(manifest=manifest, uncached_trees={"assets"}) + err = io.StringIO() + with mock.patch.object(packmodes, "run_pack_command", lambda parser, held: args), \ + contextlib.redirect_stderr(err), \ self.assertRaises(SystemExit) as stop: gp.main() - self.assertEqual(stop.exception.code, 1) + return stop.exception.code, err.getvalue() + def test_main_exits_non_zero_naming_what_it_wrote(self): + self.assertEqual(self._main_stderr(False), (1, ( + "ERROR: packs written without data directories that are not cached: " + "assets (run refresh_data_dirs.py)\n" + ))) + # A manifest run writes no pack. + self.assertEqual(self._main_stderr(True), (1, ( + "ERROR: manifests written without data directories that are not cached: " + "assets (run refresh_data_dirs.py)\n" + ))) class AFileNobodyHoldsIsAnOmission(unittest.TestCase):