From 2b5955e8a58a9547816d0d58875cec5332c6bcac Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:46:27 +0100 Subject: [PATCH] refactor: return the md5 pack outcome as data --- scripts/packs/md5pack.py | 64 ++++++++++++++++++---------------- scripts/packs/packmodes.py | 47 +++++++++++++++++-------- tests/test_e2e.py | 17 +++++---- tests/test_system_selection.py | 18 ++++++---- 4 files changed, 88 insertions(+), 58 deletions(-) diff --git a/scripts/packs/md5pack.py b/scripts/packs/md5pack.py index 560735adc..9421ed598 100644 --- a/scripts/packs/md5pack.py +++ b/scripts/packs/md5pack.py @@ -3,14 +3,13 @@ from __future__ import annotations import os -import sys -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict from core.hashing import parse_hash_list from core.options import reject_unknown from model.platforms import load_platform_config -from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles +from model.profiles import load_emulator_profiles, select_emulator_profiles from model.releaserecord import PACK_SUFFIX from packs.archive import add_pack_member, writing_pack from packs.naming import file_name_part, pack_narrowings, selection_digest @@ -77,9 +76,24 @@ class _Md5Layout: context_name: str -def _md5_layout(opts: _Md5Settings) -> _Md5Layout | None: - """The platform or emulator layout a hash list is packed in, or None - when the emulator named is refused.""" +@dataclass +class Md5PackOutcome: + """What a hash-selected pack holds: the archive (None when nothing was + packed), the (name, hash) packed and held nowhere, and the hashes the + database does not know.""" + + requested: int + zip_path: str | None = None + packed: list[tuple[str, str]] = field(default_factory=list) + not_in_repo: list[tuple[str, str]] = field(default_factory=list) + not_in_db: list[str] = field(default_factory=list) + + +def _md5_layout(opts: _Md5Settings) -> _Md5Layout: + """The platform or emulator layout a hash list is packed in. + + Raises ProfileSelectionError when the emulator named is refused. + """ platform_name = opts.platform_name platforms_dir = opts.platforms_dir emulator_name = opts.emulator_name @@ -101,13 +115,9 @@ def _md5_layout(opts: _Md5Settings) -> _Md5Layout | None: # The same gate as --emulator, unknown names included: a typo or a # buildbot name gave a generic pack in the layout of no emulator. A # core with no standalone build has no standalone layout either. - try: - (_name, profile), = select_emulator_profiles( - [emulator_name], profiles, opts.standalone - ) - except ProfileSelectionError as exc: - print(f"Error: {exc}", file=sys.stderr) - return None + (_name, profile), = select_emulator_profiles( + [emulator_name], profiles, opts.standalone + ) emu_display = profile.get("emulator", emulator_name) for fe in profile.get("files", []): plat_file_index.setdefault(fe.get("name", "").lower(), []).append(fe) @@ -172,22 +182,22 @@ def generate_md5_pack( output_dir: str, zip_contents: dict | None = None, **options: Unpack[Md5PackOptions], -) -> str | None: - """Build a pack from an explicit list of hashes with layout context.""" +) -> Md5PackOutcome: + """Build a pack from an explicit list of hashes with layout context. + + Raises ProfileSelectionError when the emulator named is refused. + """ files_db = db.get("files", {}) if zip_contents is None: zip_contents = {} reject_unknown("generate_md5_pack", options, Md5PackOptions.__optional_keys__) opts = _Md5Settings(**options) layout = _md5_layout(opts) - if layout is None: - return None zip_path = os.path.join(output_dir, _md5_pack_name(layout.context_name, hashes, opts)) os.makedirs(output_dir, exist_ok=True) - packed: list[tuple[str, str]] = [] - not_in_repo: list[tuple[str, str]] = [] - not_in_db: list[str] = [] + outcome = Md5PackOutcome(len(hashes)) + packed, not_in_repo, not_in_db = outcome.packed, outcome.not_in_repo, outcome.not_in_db seen: set[str] = set() with writing_pack(zip_path) as zf: @@ -216,17 +226,9 @@ def generate_md5_pack( add_pack_member(zf, local_path, full_dest) packed.append((name, hash_val)) - total = len(hashes) - print(f"\nPacked {len(packed)}/{total} requested files") - for name, h in packed: - print(f" PACKED: {name} ({h[:16]}...)") - for name, h in not_in_repo: - print(f" NOT IN REPO: {name} ({h[:16]}...)") - for h in not_in_db: - print(f" NOT IN DB: {h}") - if not packed: if os.path.exists(zip_path): os.unlink(zip_path) - return None - return zip_path + else: + outcome.zip_path = zip_path + return outcome diff --git a/scripts/packs/packmodes.py b/scripts/packs/packmodes.py index 981c13dbe..7c786570e 100644 --- a/scripts/packs/packmodes.py +++ b/scripts/packs/packmodes.py @@ -17,6 +17,7 @@ from model.cliargs import ( work_from_repo_root, ) from model.database import load_database +from model.profiles import ProfileSelectionError from model.registry import load_data_dir_registry from packs.datadirs import hold_data_dirs from packs.emulatorpack import ( @@ -27,7 +28,7 @@ from packs.emulatorpack import ( ) from packs.hashinput import ACCEPTED_HASHES, parse_hash_file, parse_hash_input from packs.hashlookup import print_hash_lookup -from packs.md5pack import generate_md5_pack +from packs.md5pack import Md5PackOutcome, 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 @@ -97,21 +98,37 @@ 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): - 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: + try: + with pack_output_lock(args.output_dir): + outcome = 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), + ) + except ProfileSelectionError as exc: + print(f"Error: {exc}", file=sys.stderr) sys.exit(1) + print_hash_pack(outcome) + if not outcome.zip_path: + sys.exit(1) + + +def print_hash_pack(outcome: Md5PackOutcome) -> None: + """The lines a hash-selected pack ends on: what went in, what did not.""" + print(f"\nPacked {len(outcome.packed)}/{outcome.requested} requested files") + for name, h in outcome.packed: + print(f" PACKED: {name} ({h[:16]}...)") + for name, h in outcome.not_in_repo: + print(f" NOT IN REPO: {name} ({h[:16]}...)") + for h in outcome.not_in_db: + print(f" NOT IN DB: {h}") def _run_profile_mode(args: argparse.Namespace, db: dict, zip_contents: dict) -> None: diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 0e6f42940..f0a6f4bc7 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -2871,7 +2871,7 @@ class TestE2E(unittest.TestCase): zip_contents=zip_contents, platform_name="testplat", platforms_dir=plat_dir, - ) + ).zip_path self.assertIsNotNone(zip_path) with zipfile.ZipFile(zip_path) as zf: names = zf.namelist() @@ -2896,7 +2896,7 @@ class TestE2E(unittest.TestCase): zip_contents=zip_contents, emulator_name="testplat", emulators_dir=emu_dir, - ) + ).zip_path self.assertIsNotNone(emu_zip) self.assertNotEqual(os.path.basename(emu_zip), os.path.basename(zip_path)) self.assertTrue(os.path.exists(zip_path)) @@ -2933,16 +2933,21 @@ class TestE2E(unittest.TestCase): os.makedirs(bios_dir) buf = io.StringIO() with contextlib.redirect_stdout(buf): - result = generate_md5_pack( + outcome = generate_md5_pack( hashes=[("md5", "md5known" + "0" * 25)], db=db, bios_dir=bios_dir, output_dir=out_dir, zip_contents={}, ) - output = buf.getvalue() - self.assertIn("NOT IN REPO", output) - self.assertIsNone(result) + self.assertEqual(buf.getvalue(), "") + self.assertEqual(outcome.not_in_repo, [("missing.bin", "md5known" + "0" * 25)]) + self.assertEqual((outcome.packed, outcome.not_in_db), ([], [])) + self.assertIsNone(outcome.zip_path) + from packs.packmodes import print_hash_pack + with contextlib.redirect_stdout(buf): + print_hash_pack(outcome) + self.assertIn("NOT IN REPO: missing.bin", buf.getvalue()) def test_144_invalid_split_emulator(self): """--split + --emulator is rejected.""" diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index 0ad6e54bb..750b3c4be 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -24,7 +24,12 @@ from core.cli import suggest_names from model.cliargs import list_system_ids from model.database import load_database from model.platforms import load_platform_config -from model.profiles import emulator_profiles_cache, load_emulator_profiles, profiles_for_systems +from model.profiles import ( + ProfileSelectionError, + emulator_profiles_cache, + load_emulator_profiles, + profiles_for_systems, +) from packs import archive from packs import emulatorpack from packs import md5pack @@ -77,11 +82,12 @@ class StandaloneNeedsAStandaloneBuild(unittest.TestCase): emulator_profiles_cache.clear() self.addCleanup(emulator_profiles_cache.clear) db = {"files": {}, "indexes": {"by_md5": {}, "by_crc32": {}, "by_name": {}}} - result = md5pack.generate_md5_pack( - [("md5", "d8f1206299c48946e6ec5ef96d014eaa")], db, tmp, tmp, - emulator_name="handy", emulators_dir=str(Path(tmp, "emulators")), standalone=True, - ) - self.assertIsNone(result) + with self.assertRaisesRegex(ProfileSelectionError, "does not support --standalone"): + md5pack.generate_md5_pack( + [("md5", "d8f1206299c48946e6ec5ef96d014eaa")], db, tmp, tmp, + emulator_name="handy", emulators_dir=str(Path(tmp, "emulators")), + standalone=True, + ) self.assertEqual([p for p in os.listdir(tmp) if p.endswith(".zip")], [])