From 41da5922912016926ba8c0ba6f513792e1cc7c8b Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:58:21 +0100 Subject: [PATCH] refactor: hash fields and pins read one way --- scripts/acquire/fetch.py | 31 ++++++++++--------------------- scripts/acquire/provenance.py | 16 +++++----------- scripts/recipes/build.py | 12 ++---------- scripts/recipes/capture.py | 31 ++++++++----------------------- scripts/recipes/identify.py | 34 ++++++++++------------------------ scripts/recipes/pins.py | 24 ++++++++++++++++++++++++ 6 files changed, 59 insertions(+), 89 deletions(-) create mode 100644 scripts/recipes/pins.py diff --git a/scripts/acquire/fetch.py b/scripts/acquire/fetch.py index a5272efef..5a0acca6b 100644 --- a/scripts/acquire/fetch.py +++ b/scripts/acquire/fetch.py @@ -14,6 +14,7 @@ import urllib.parse import urllib.request from pathlib import Path +from core.hashing import parse_hash_list MAX_DOWNLOAD = 100 * 1024 * 1024 # 100MB per file @@ -104,20 +105,8 @@ def find_missing(config: dict, db: dict) -> list[dict]: return missing -def _accepted(entry: dict, field: str) -> set[str]: - """Every value an entry accepts for a hash field. - - A profile lists several revisions as a YAML list (daedalusx64's - n64.psh), a platform as a comma-separated string. Read as one value, - the list stopped the run with an unhashable-type error. - """ - value = entry.get(field) - values = value if isinstance(value, list) else str(value or "").split(",") - return {str(v).strip().lower() for v in values if str(v).strip()} - - def _crc32s(entry: dict) -> set[str]: - return {value.removeprefix("0x").zfill(8) for value in _accepted(entry, "crc32")} + return {value.zfill(8) for value in parse_hash_list(entry.get("crc32"))} def _size(entry: dict) -> int | None: @@ -141,7 +130,7 @@ def verifiable(entry: dict) -> bool: crafted bytes, so they identify a file the database already holds (step 1) and never accept one a remote source serves. """ - return any(_accepted(entry, field) for field, _digest in CRYPTO_HASHES) + return any(parse_hash_list(entry.get(field)) for field, _digest in CRYPTO_HASHES) def verify_content(data: bytes, expected: dict) -> bool: @@ -153,7 +142,7 @@ def verify_content(data: bytes, expected: dict) -> bool: declared = [ (accepted, digest) for field, digest in CRYPTO_HASHES - for accepted in [_accepted(expected, field)] + for accepted in [parse_hash_list(expected.get(field))] if accepted ] return bool(declared) and all( @@ -174,13 +163,13 @@ def _read_limited( def step1_crossref_db(entry: dict, db: dict) -> str | None: """Check if file exists under different name/path in database.""" files = db.get("files", {}) - for sha1 in sorted(_accepted(entry, "sha1")): + for sha1 in sorted(parse_hash_list(entry.get("sha1"))): if sha1 in files: return files[sha1]["path"] indexes = db.get("indexes", {}) for field, index in (("sha256", "by_sha256"), ("md5", "by_md5")): by_hash = indexes.get(index, {}) - for value in sorted(_accepted(entry, field)): + for value in sorted(parse_hash_list(entry.get(field))): sha1_match = by_hash.get(value) if sha1_match and sha1_match in files: return files[sha1_match]["path"] @@ -288,7 +277,7 @@ def step3b_software_heritage(entry: dict) -> bytes | None: """Ask Software Heritage for the file by each accepted sha1, then sha256: its archive answers by content, whatever the file was named.""" for field in ("sha1", "sha256"): - for value in sorted(_accepted(entry, field)): + for value in sorted(parse_hash_list(entry.get(field))): url = f"{SOFTWARE_HERITAGE}/{field}:{value}/raw/" try: req = urllib.request.Request( @@ -325,7 +314,7 @@ def step4_search_archive_org(entry: dict) -> bytes | None: _unanswered(url, exc) continue - sha1s = sorted(_accepted(entry, "sha1")) + sha1s = sorted(parse_hash_list(entry.get("sha1"))) if not sha1s: return None # Each accepted revision is a query of its own: archive.org matches one. @@ -566,8 +555,8 @@ def generate_issue_body(missing: list[dict], platform: str) -> str: "|------|--------|------|-----|", ] for entry in missing: - sha1 = ", ".join(f"`{h}`" for h in sorted(_accepted(entry, "sha1"))) or "none declared" - md5 = ", ".join(f"`{h}`" for h in sorted(_accepted(entry, "md5"))) or "none declared" + sha1 = ", ".join(f"`{h}`" for h in sorted(parse_hash_list(entry.get("sha1")))) or "none declared" + md5 = ", ".join(f"`{h}`" for h in sorted(parse_hash_list(entry.get("md5")))) or "none declared" lines.append(f"| `{entry['name']}` | {entry['system']} | {sha1} | {md5} |") lines += [ "", diff --git a/scripts/acquire/provenance.py b/scripts/acquire/provenance.py index 5c5b3101d..08f39d70d 100644 --- a/scripts/acquire/provenance.py +++ b/scripts/acquire/provenance.py @@ -9,19 +9,13 @@ import sys import zipfile from pathlib import Path +from core.hashing import parse_hash_list from core.paths import REPO_ROOT HASH_FIELDS = ("sha1", "md5", "sha256") -def _values(entry: dict, field: str) -> set[str]: - """Every value a profile or catalog entry gives for a hash field.""" - value = entry.get(field) - values = value if isinstance(value, list) else str(value or "").split(",") - return {str(v).strip().lower() for v in values if str(v).strip()} - - def _crc_key(value: str) -> str: return value.removeprefix("0x").zfill(8) @@ -82,8 +76,8 @@ def profile_needs(profiles: dict, db: dict) -> dict: continue need = {"emulator": emulator, "name": name, "required": bool(entry.get("required"))} - hashes = {(field, v) for field in HASH_FIELDS for v in _values(entry, field)} - crcs = {_crc_key(v) for v in _values(entry, "crc32")} + hashes = {(field, v) for field in HASH_FIELDS for v in parse_hash_list(entry.get(field))} + crcs = {_crc_key(v) for v in parse_hash_list(entry.get("crc32"))} declared = entry.get("size") sizes = [] if declared is None else ( declared if isinstance(declared, list) else [declared] @@ -117,10 +111,10 @@ def needs_filled(entry: dict, needs: dict) -> list[dict]: """The profile needs a catalog dump answers, required ones first.""" found: dict[tuple[str, str], dict] = {} keys: list[tuple[object, ...]] = [ - (field, v) for field in HASH_FIELDS for v in _values(entry, field) + (field, v) for field in HASH_FIELDS for v in parse_hash_list(entry.get(field)) ] if entry.get("size") is not None: - keys += [("crc32", _crc_key(v), entry["size"]) for v in _values(entry, "crc32")] + keys += [("crc32", _crc_key(v), entry["size"]) for v in parse_hash_list(entry.get("crc32"))] for key in keys: for need in needs["by_hash"].get(key, []): found.setdefault((need["emulator"], need["name"]), {**need, "by": key[0]}) diff --git a/scripts/recipes/build.py b/scripts/recipes/build.py index 8a4713aa7..e2b864736 100644 --- a/scripts/recipes/build.py +++ b/scripts/recipes/build.py @@ -2,12 +2,12 @@ from __future__ import annotations -import hashlib import os import zipfile from dataclasses import dataclass, field from pathlib import Path +from core.hashing import compute_hashes from core.paths import REPO_ROOT from core.torrentzip import write_torrentzip, zlib_ng_version from recipes.ledger import is_archive_path @@ -88,14 +88,6 @@ def _members_match(built: Path, members: list[dict]) -> str: return f"members differ: expected {missing[:3]}, built {extra[:3]}" -def _file_sha1(path: Path) -> str: - digest = hashlib.sha1() - with path.open("rb") as handle: - while chunk := handle.read(16 * 1024 * 1024): - digest.update(chunk) - return digest.hexdigest() - - def destination(record_path: str, output_dir: Path) -> Path: """Where a build lands: the archive's path below ``bios/``, under *output_dir*.""" parts = Path(record_path).parts @@ -145,7 +137,7 @@ def build_archive( [(name, _opener(source.path, source.member)) for name, source in sources], ) if exact: - written = _file_sha1(scratch) + written = compute_hashes(scratch, frozenset({"sha1"}), cache=False)["sha1"] detail = "" if written == record["sha1"] else ( f"sha1 {written} is not the recorded {record['sha1']}" ) diff --git a/scripts/recipes/capture.py b/scripts/recipes/capture.py index 36e4d134c..abb636782 100644 --- a/scripts/recipes/capture.py +++ b/scripts/recipes/capture.py @@ -10,9 +10,11 @@ from concurrent.futures import ProcessPoolExecutor from pathlib import Path from typing import BinaryIO +from core.hashing import parse_hash_list from core.torrentzip import write_torrentzip, zlib_ng_version from recipes.ledger import database_archives from recipes.members import _member_sha1, _opener +from recipes.pins import container_entries from recipes.romsets import collect_recipes, load_dat_recipes _TORRENTZIP_COMMENT = b"TORRENTZIPPED-" @@ -96,36 +98,19 @@ def _read_job(job: tuple[str, str]) -> tuple[str, dict | str]: return path, f"{type(exc).__name__}: {exc}" -def _hash_values(value: object) -> set[str]: - raw = value if isinstance(value, list) else str(value or "").split(",") - return {str(item).strip().lower() for item in raw if str(item).strip()} - - def container_pins(platforms_dir: str, emulators_dir: str) -> dict[str, set[str]]: - """Container hash -> who pins it: ``platform:`` or ``profile:``. - - A ``zipped_file`` entry pins a ROM inside the archive, and a Recalbox - archive md5 is the composite of its members (``zip_digest: composite``, - Bios.cpp:64-68): neither pins the container bytes. - """ - from model.registry import list_registered_platforms + """Container hash -> who pins it: ``platform:`` or ``profile:``.""" from model.profiles import load_emulator_profiles - from model.platforms import load_platform_config pins: dict[str, set[str]] = defaultdict(set) - for platform in list_registered_platforms(platforms_dir): - config = load_platform_config(platform, platforms_dir) - for system in config.get("systems", {}).values(): - for entry in system.get("files", []) or []: - if entry.get("zipped_file") or entry.get("zip_digest") == "composite": - continue - for key in ("md5", "sha1", "alt_md5"): - for value in _hash_values(entry.get(key)): - pins[value].add(f"platform:{platform}") + for platform, entry in container_entries(platforms_dir): + for key in ("md5", "sha1", "alt_md5"): + for value in parse_hash_list(entry.get(key)): + pins[value].add(f"platform:{platform}") for name, profile in load_emulator_profiles(emulators_dir, skip_aliases=False).items(): for entry in profile.get("files", []) or []: for key in ("md5", "sha1", "sha256"): - for value in _hash_values(entry.get(key)): + for value in parse_hash_list(entry.get(key)): pins[value].add(f"profile:{name}") return dict(pins) diff --git a/scripts/recipes/identify.py b/scripts/recipes/identify.py index f73690744..f24134495 100644 --- a/scripts/recipes/identify.py +++ b/scripts/recipes/identify.py @@ -9,8 +9,7 @@ from collections import defaultdict from pathlib import Path from core.torrentzip import is_torrentzip -from model.platforms import load_platform_config -from model.registry import list_registered_platforms +from recipes.pins import container_entries from recipes.pool import AtomPool from recipes.romsets import Recipe @@ -65,29 +64,16 @@ def reconstruct( def platform_targets(platforms_dir: str) -> dict[str, set[str]]: - """Container MD5s the platforms pin, per archive name. - - ``zipped_file`` entries pin an inner ROM instead of the container, so - their MD5 is not an archive hash and is skipped. So is a Recalbox md5, - the composite of the members (``zip_digest: composite``, Bios.cpp:64-68): - no container build can ever give it. - """ + """Container MD5s the platforms pin, per archive name.""" targets: dict[str, set[str]] = defaultdict(set) - 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", []) or []: - archive = entry.get("name", "") - if ( - not archive.endswith(".zip") - or entry.get("zipped_file") - or entry.get("zip_digest") == "composite" - ): - continue - for value in str(entry.get("md5") or "").split(","): - value = value.strip().lower() - if len(value) == 32: - targets[archive].add(value) + for _platform, entry in container_entries(platforms_dir): + archive = entry.get("name", "") + if not archive.endswith(".zip"): + continue + for value in str(entry.get("md5") or "").split(","): + value = value.strip().lower() + if len(value) == 32: + targets[archive].add(value) return dict(targets) diff --git a/scripts/recipes/pins.py b/scripts/recipes/pins.py new file mode 100644 index 000000000..cfe77f3ec --- /dev/null +++ b/scripts/recipes/pins.py @@ -0,0 +1,24 @@ +"""The platform entries whose hash pins an archive's container bytes.""" + +from __future__ import annotations + +from collections.abc import Iterator + +from model.platforms import load_platform_config +from model.registry import list_registered_platforms + + +def container_entries(platforms_dir: str) -> Iterator[tuple[str, dict]]: + """(platform, entry) for each platform entry whose hash is the container's. + + A ``zipped_file`` entry pins a ROM inside the archive, and a Recalbox + archive md5 is the composite of its members (``zip_digest: composite``, + Bios.cpp:64-68): neither pins the container bytes, and no container + build can ever give them. + """ + for platform in list_registered_platforms(platforms_dir): + config = load_platform_config(platform, platforms_dir) + for system in config.get("systems", {}).values(): + for entry in system.get("files", []) or []: + if not (entry.get("zipped_file") or entry.get("zip_digest") == "composite"): + yield platform, entry