From d87993129a23915283ff1b308ea27470d457a97f Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:30:08 +0100 Subject: [PATCH] refactor: move the bundled-only listing into packs --- scripts/bundled_only.py | 86 +----------------------------- scripts/packs/bundledonly.py | 92 +++++++++++++++++++++++++++++++++ tests/sources.py | 3 ++ tests/test_audit_regressions.py | 16 +++--- 4 files changed, 104 insertions(+), 93 deletions(-) create mode 100644 scripts/packs/bundledonly.py diff --git a/scripts/bundled_only.py b/scripts/bundled_only.py index 310f839a0..c149ce964 100644 --- a/scripts/bundled_only.py +++ b/scripts/bundled_only.py @@ -19,94 +19,10 @@ import json from pathlib import Path from core.cli import add_repo_inputs -from core.hashing import compute_hashes from core.sizes import size_text -from resolve.directories import expand_directory_entries -from model.registry import list_registered_platforms from model.database import load_database from model.profiles import load_emulator_profiles -from model.platforms import load_platform_config -from packs.crossref import FileConsumers - - -def _entries(profile: dict, db: dict) -> list[dict]: - files = [f for f in profile.get("files") or [] if isinstance(f, dict)] - return expand_directory_entries(files, db, False) + [ - f for f in expand_directory_entries(files, db, True) if f not in files - ] - - -def shipped_by_manifests(install_dir: Path) -> set[str]: - """Every sha1 an install manifest places, alternatives included.""" - shipped: set[str] = set() - for path in sorted(install_dir.glob("*.json")): - manifest = json.loads(path.read_text(encoding="utf-8")) - for entry in manifest.get("files") or []: - shipped.add(str(entry.get("sha1") or "")) - shipped.update(str(a.get("sha1") or "") for a in entry.get("alternatives") or []) - return shipped - {""} - - -def bundled_only(db: dict, profiles: dict, platforms_dir: str, install_dir: Path) -> list[dict]: - """Collected files a bundled entry resolves to and nothing else needs.""" - consumers = FileConsumers(db) - needed: set[str] = set(shipped_by_manifests(install_dir)) - for name in list_registered_platforms(platforms_dir): - config = load_platform_config(name, platforms_dir) - for system in config.get("systems", {}).values(): - for entry in system.get("files", []): - sha1 = consumers.sha1_of(entry, entry.get("destination", "")) - if sha1: - needed.add(sha1) - bundled: dict[str, set[str]] = {} - for emulator, profile in profiles.items(): - if profile.get("type") == "alias": - continue - for entry in _entries(profile, db): - sha1 = consumers.sha1_of(entry, entry.get("path") or "", owner=emulator) - if not sha1: - continue - # A platform whose package leaves the file out (not_bundled_on: - # AmberELEC's amiberry 7.1.1 has no AROS ROMs) brings it from - # the collection. - if entry.get("bundled") and not entry.get("not_bundled_on"): - bundled.setdefault(sha1, set()).add(emulator) - else: - needed.add(sha1) - files = db.get("files", {}) - rows = [ - {"sha1": sha1, "path": files[sha1]["path"], "size": files[sha1].get("size", 0), - "emulators": sorted(emulators)} - for sha1, emulators in sorted(bundled.items(), key=lambda kv: files[kv[0]]["path"]) - if sha1 not in needed and sha1 in files - ] - return rows + other_copies(rows, Path(db.get("bios_dir") or "bios")) - - -def other_copies(rows: list[dict], bios_dir: Path) -> list[dict]: - """The same bytes under other paths of the collection. - - The database keeps one path per sha1, and the trees kept whole - (NODEDUP: splitwolf's sprite directories, c64-emu's machine folders) - hold the same file several times. Listing only the indexed path took - five passes to empty splitwolf. A file is hashed only when its size is - one a listed file has. - """ - by_size: dict[int, dict[str, dict]] = {} - for row in rows: - by_size.setdefault(int(row["size"]), {})[row["sha1"]] = row - listed = {row["path"] for row in rows} - found = [] - for path in sorted(bios_dir.rglob("*")): - if not path.is_file() or path.is_symlink() or path.as_posix() in listed: - continue - same_size = by_size.get(path.stat().st_size) - if not same_size: - continue - sha1 = compute_hashes(path, frozenset({"sha1"}))["sha1"] - if sha1 in same_size: - found.append({**same_size[sha1], "path": path.as_posix()}) - return found +from packs.bundledonly import bundled_only def main() -> int: diff --git a/scripts/packs/bundledonly.py b/scripts/packs/bundledonly.py new file mode 100644 index 000000000..d5e89abd1 --- /dev/null +++ b/scripts/packs/bundledonly.py @@ -0,0 +1,92 @@ +"""Collected files that only an emulator's own install provides.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from core.hashing import compute_hashes +from model.platforms import load_platform_config +from model.registry import list_registered_platforms +from packs.crossref import FileConsumers +from resolve.directories import expand_directory_entries + + +def _entries(profile: dict, db: dict) -> list[dict]: + files = [f for f in profile.get("files") or [] if isinstance(f, dict)] + return expand_directory_entries(files, db, False) + [ + f for f in expand_directory_entries(files, db, True) if f not in files + ] + + +def shipped_by_manifests(install_dir: Path) -> set[str]: + """Every sha1 an install manifest places, alternatives included.""" + shipped: set[str] = set() + for path in sorted(install_dir.glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + for entry in manifest.get("files") or []: + shipped.add(str(entry.get("sha1") or "")) + shipped.update(str(a.get("sha1") or "") for a in entry.get("alternatives") or []) + return shipped - {""} + + +def bundled_only(db: dict, profiles: dict, platforms_dir: str, install_dir: Path) -> list[dict]: + """Collected files a bundled entry resolves to and nothing else needs.""" + consumers = FileConsumers(db) + needed: set[str] = set(shipped_by_manifests(install_dir)) + for name in list_registered_platforms(platforms_dir): + config = load_platform_config(name, platforms_dir) + for system in config.get("systems", {}).values(): + for entry in system.get("files", []): + sha1 = consumers.sha1_of(entry, entry.get("destination", "")) + if sha1: + needed.add(sha1) + bundled: dict[str, set[str]] = {} + for emulator, profile in profiles.items(): + if profile.get("type") == "alias": + continue + for entry in _entries(profile, db): + sha1 = consumers.sha1_of(entry, entry.get("path") or "", owner=emulator) + if not sha1: + continue + # A platform whose package leaves the file out (not_bundled_on: + # AmberELEC's amiberry 7.1.1 has no AROS ROMs) brings it from + # the collection. + if entry.get("bundled") and not entry.get("not_bundled_on"): + bundled.setdefault(sha1, set()).add(emulator) + else: + needed.add(sha1) + files = db.get("files", {}) + rows = [ + {"sha1": sha1, "path": files[sha1]["path"], "size": files[sha1].get("size", 0), + "emulators": sorted(emulators)} + for sha1, emulators in sorted(bundled.items(), key=lambda kv: files[kv[0]]["path"]) + if sha1 not in needed and sha1 in files + ] + return rows + other_copies(rows, Path(db.get("bios_dir") or "bios")) + + +def other_copies(rows: list[dict], bios_dir: Path) -> list[dict]: + """The same bytes under other paths of the collection. + + The database keeps one path per sha1, and the trees kept whole + (NODEDUP: splitwolf's sprite directories, c64-emu's machine folders) + hold the same file several times. Listing only the indexed path took + five passes to empty splitwolf. A file is hashed only when its size is + one a listed file has. + """ + by_size: dict[int, dict[str, dict]] = {} + for row in rows: + by_size.setdefault(int(row["size"]), {})[row["sha1"]] = row + listed = {row["path"] for row in rows} + found = [] + for path in sorted(bios_dir.rglob("*")): + if not path.is_file() or path.is_symlink() or path.as_posix() in listed: + continue + same_size = by_size.get(path.stat().st_size) + if not same_size: + continue + sha1 = compute_hashes(path, frozenset({"sha1"}))["sha1"] + if sha1 in same_size: + found.append({**same_size[sha1], "path": path.as_posix()}) + return found diff --git a/tests/sources.py b/tests/sources.py index 84914790d..1b285585c 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -37,6 +37,9 @@ COMMANDS = { "validate_pr.py": ("resolve/review.py", "core/gitclone.py"), "mame_ref_audit.py": ("profiling/mamerefs.py",), "fileless_audit.py": ("profiling/fileless.py",), + "bundled_only.py": ("packs/bundledonly.py",), + "mame_ref_audit.py": ("profiling/mamerefs.py",), + "fileless_audit.py": ("profiling/fileless.py",), "mame_ref_audit.py": ("profiling/mamerefs.py",), "refresh_data_dirs.py": ("packs/datadirs.py",), "split_pack.py": ("packs/parts.py",), diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 02ef9e239..eb222147f 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -7124,10 +7124,10 @@ class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase): def test_only_the_bundled_only_copy_is_listed(self): import tempfile - import bundled_only + from packs import bundledonly with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(bundled_only, "list_registered_platforms", return_value=[]): + mock.patch.object(bundledonly, "list_registered_platforms", return_value=[]): def entry(sha1, name): path = Path(tmp, name) path.write_bytes(name.encode()) @@ -7145,12 +7145,12 @@ class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase): {"name": "bios.rom", "sha1": "b" * 40, "bundled": True}]}, "core": {"files": [{"name": "bios.rom", "sha1": "b" * 40}]}, } - rows = bundled_only.bundled_only(db, profiles, tmp, Path(tmp)) + rows = bundledonly.bundled_only(db, profiles, tmp, Path(tmp)) self.assertEqual([row["path"] for row in rows], [str(Path(tmp, "icon.png"))]) # A platform whose package leaves the file out brings it from the # collection: the copy stays. profiles["app"]["files"][0]["not_bundled_on"] = ["someplatform"] - self.assertEqual(bundled_only.bundled_only(db, profiles, tmp, Path(tmp)), []) + self.assertEqual(bundledonly.bundled_only(db, profiles, tmp, Path(tmp)), []) def test_every_copy_of_the_listed_bytes_is_listed(self): """The database keeps one path per content: splitwolf's sprite @@ -7158,7 +7158,7 @@ class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase): import hashlib import tempfile - import bundled_only + from packs import bundledonly with tempfile.TemporaryDirectory() as tmp: for name in ("dir1/a.bmp", "dir2/a.bmp", "dir2/b.bmp"): @@ -7167,17 +7167,17 @@ class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase): sha1 = hashlib.sha1(b"same").hexdigest() row = {"sha1": sha1, "path": Path(tmp, "dir1/a.bmp").as_posix(), "size": 4, "emulators": ["splitwolf"]} - copies = bundled_only.other_copies([row], Path(tmp)) + copies = bundledonly.other_copies([row], Path(tmp)) self.assertEqual([c["path"] for c in copies], [Path(tmp, "dir2/a.bmp").as_posix()]) def test_the_collection_holds_no_copy_only_an_install_provides(self): """The pull request checks run this suite, not the pipeline: without this, a copy only a bundled entry reaches merges green.""" - import bundled_only + from packs import bundledonly from model.database import load_database from model.profiles import load_emulator_profiles - rows = bundled_only.bundled_only( + rows = bundledonly.bundled_only( load_database(str(ROOT / "database.json")), load_emulator_profiles(str(ROOT / "emulators")), str(ROOT / "platforms"), ROOT / "install",