From 2c8a9cfad882b01bca374d8eb527e6be919299b2 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:42:28 +0100 Subject: [PATCH] refactor: one digest loop for files and streams --- scripts/bios_integrity.py | 11 ++------- scripts/core/hashing.py | 44 ++++++++++++++++++---------------- scripts/packs/integrity.py | 32 ++++--------------------- scripts/release/sync.py | 6 +---- scripts/resolve/identity.py | 14 +++-------- scripts/resolve/review.py | 10 +++----- scripts/romrecipes/members.py | 7 ++---- scripts/sitegen/dataexports.py | 12 ++-------- tests/test_autorun.py | 5 ++-- tests/test_hashing.py | 43 ++++++++++++++++++++++++++++++++- tests/test_identity.py | 2 +- 11 files changed, 88 insertions(+), 98 deletions(-) diff --git a/scripts/bios_integrity.py b/scripts/bios_integrity.py index fa4f01704..8904ce735 100644 --- a/scripts/bios_integrity.py +++ b/scripts/bios_integrity.py @@ -43,6 +43,7 @@ from dataclasses import dataclass, field from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from core.hashing import file_digest from model.largefiles import load_registered_paths MISREAD = "misread" @@ -83,14 +84,6 @@ class Report: return all(f.verdict in (MISREAD, RESTORED) for f in self.findings) -def sha1_of(path: Path) -> str: - digest = hashlib.sha1() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - class GitFailed(RuntimeError): """A git command failed: its empty output says nothing about the file.""" @@ -143,7 +136,7 @@ def check( root: Path, db: dict, apply: bool, - hasher: Callable[[Path], str] = sha1_of, + hasher: Callable[[Path], str] = file_digest, ) -> Report: """Hash every database path, confirm each mismatch, repair what may be.""" ignored = set(load_registered_paths(root / ".gitignore")) diff --git a/scripts/core/hashing.py b/scripts/core/hashing.py index b636b13aa..4dd6f523c 100644 --- a/scripts/core/hashing.py +++ b/scripts/core/hashing.py @@ -10,7 +10,7 @@ import os import zipfile import zlib from pathlib import Path -from typing import IO, BinaryIO +from typing import IO, BinaryIO, Protocol from collections.abc import Iterable @@ -53,6 +53,16 @@ def compute_hashes( def _compute_hashes(filepath: str | Path, algos: frozenset[str]) -> dict[str, str]: """Read the file once and compute the requested digests.""" + with open(filepath, "rb") as f: + return stream_hashes(f, algos) + + +class Readable(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + + +def stream_hashes(stream: Readable, algos: frozenset[str]) -> dict[str, str]: + """The requested digests of a stream (a file, a ZIP member), read once to its end.""" sha1 = hashlib.sha1() if "sha1" in algos else None md5 = hashlib.md5() if "md5" in algos else None sha256 = hashlib.sha256() if "sha256" in algos else None @@ -60,18 +70,17 @@ def _compute_hashes(filepath: str | Path, algos: frozenset[str]) -> dict[str, st do_adler = "adler32" in algos crc = 0 adler = 1 # zlib.adler32 initial value - with open(filepath, "rb") as f: - for chunk in iter(lambda: f.read(65536), b""): - if sha1: - sha1.update(chunk) - if md5: - md5.update(chunk) - if sha256: - sha256.update(chunk) - if do_crc: - crc = zlib.crc32(chunk, crc) - if do_adler: - adler = zlib.adler32(chunk, adler) + for chunk in iter(lambda: stream.read(65536), b""): + if sha1: + sha1.update(chunk) + if md5: + md5.update(chunk) + if sha256: + sha256.update(chunk) + if do_crc: + crc = zlib.crc32(chunk, crc) + if do_adler: + adler = zlib.adler32(chunk, adler) result: dict[str, str] = {} if sha1: result["sha1"] = sha1.hexdigest() @@ -96,15 +105,10 @@ def file_digest(path: Path, algorithm: str = "sha1") -> str: def md5sum(source: str | os.PathLike[str] | IO[bytes]) -> str: """Compute MD5 of a file path or file-like object - matches Batocera's md5sum().""" - h = hashlib.md5() if isinstance(source, (str, os.PathLike)): with open(source, "rb") as f: - for chunk in iter(lambda: f.read(65536), b""): - h.update(chunk) - else: - for chunk in iter(lambda: source.read(65536), b""): - h.update(chunk) - return h.hexdigest() + return stream_hashes(f, frozenset({"md5"}))["md5"] + return stream_hashes(source, frozenset({"md5"}))["md5"] _md5_composite_cache: dict[str, str] = {} diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index ccab9daa1..6b5cf1be8 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -18,12 +18,10 @@ from core.ziptools import check_inside_zip from resolve.nativemode import digest_algorithm from resolve.validation import baseline_verdict, digest_verdict from resolve.nativemode import hash_mismatch_excludes_file -import functools import hashlib -import zlib import sys from resolve.cores import filter_systems_by_target -from core.hashing import md5_composite_of, parse_md5_list +from core.hashing import compute_hashes, file_digest, md5_composite_of, parse_md5_list, stream_hashes from core.options import reject_unknown import io from model.profiles import load_emulator_profiles @@ -41,6 +39,7 @@ from resolve.cores import resolve_platform_cores from core.paths import declared_destination import zipfile from collections.abc import Callable +from pathlib import Path # Imported at run time where typing has it: a test reads the signature of # verify_pack_against_platform with its annotations evaluated. @@ -50,16 +49,6 @@ elif TYPE_CHECKING: from typing_extensions import Unpack -@functools.cache -def _file_sha1(path: str) -> str: - """SHA-1 of a cached data-directory file, read once per run.""" - digest = hashlib.sha1() - with open(path, "rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - def _members_are_held(data: bytes, by_md5: dict, held_inside: dict) -> bool: """Whether every member of an archive is a dump the collection holds.""" try: @@ -215,7 +204,7 @@ def _cached_as( # The content, not the size: a member written corrupt # keeps its length, and a same-sized homonym from another # cache is another file. - if os.path.getsize(_dp) == size and _file_sha1(_dp) == sha1: + if os.path.getsize(_dp) == size and compute_hashes(_dp, frozenset({"sha1"}))["sha1"] == sha1: return _bn if ( name.endswith(".zip") and _dp.endswith(".zip") @@ -337,11 +326,7 @@ def generate_sha256sums(output_dir: str) -> str | None: if not name.endswith(".zip"): continue path = os.path.join(output_dir, name) - sha256 = hashlib.sha256() - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(65536), b""): - sha256.update(chunk) - entries.append(f"{sha256.hexdigest()} {name}") + entries.append(f"{file_digest(Path(path), 'sha256')} {name}") if not entries: return None with open(sums_path, "w") as f: @@ -406,15 +391,8 @@ def _check_member_hash( # The frontend's own rule, as the builder and verify apply it: RomM's # size-then-any-hash included, which a bare md5 comparison refused. - digests = {"md5": hashlib.md5(), "sha1": hashlib.sha1()} - crc = 0 with zf.open(member) as f: - for chunk in iter(lambda: f.read(65536), b""): - for h in digests.values(): - h.update(chunk) - crc = zlib.crc32(chunk, crc) - computed = {name: h.hexdigest() for name, h in digests.items()} - computed["crc32"] = format(crc & 0xFFFFFFFF, "08x") + computed = stream_hashes(f, frozenset({"md5", "sha1", "crc32"})) def composite() -> str | None: # Recalbox's Md5Composite, over the sorted members of a ZIP. diff --git a/scripts/release/sync.py b/scripts/release/sync.py index 5c8ad762b..aea9e55b3 100644 --- a/scripts/release/sync.py +++ b/scripts/release/sync.py @@ -27,10 +27,6 @@ class Upload: reason: str = "" -def sha1_of(path: Path) -> str: - return file_digest(path) - - def database_sha1(db: dict) -> dict[str, str]: return { entry["path"]: str(entry.get("sha1") or key).lower() @@ -44,7 +40,7 @@ def plan_uploads( db: dict, gitignore_text: str, findings: list, - hasher: Callable[[Path], str] = sha1_of, + hasher: Callable[[Path], str] = file_digest, ) -> list[Upload]: """Each out-of-date asset, cleared for upload or refused with its reason.""" names = asset_names([*registered_paths(gitignore_text), diff --git a/scripts/resolve/identity.py b/scripts/resolve/identity.py index d33526ecc..73d8e17a1 100644 --- a/scripts/resolve/identity.py +++ b/scripts/resolve/identity.py @@ -15,10 +15,11 @@ almost never is. from __future__ import annotations -import hashlib from dataclasses import dataclass from pathlib import Path +from core.hashing import file_digest + # A manufacturer directory holding files that genuinely belong to several # machines, where a shared dump says nothing about a misfiling. @@ -40,7 +41,6 @@ KNOWN_SHARED: dict[str, tuple[frozenset[str], str]] = { ), } -CHUNK = 1 << 20 @dataclass @@ -63,14 +63,6 @@ def _manufacturer(path: Path, root: Path) -> str: return parts[0] if len(parts) > 1 else "" -def _sha1(path: Path) -> str: - digest = hashlib.sha1() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(CHUNK), b""): - digest.update(chunk) - return digest.hexdigest() - - def scan(bios_dir: str = "bios") -> list[Duplicate]: """Group the tree by content and keep the groups that cross makers. @@ -87,7 +79,7 @@ def scan(bios_dir: str = "bios") -> list[Duplicate]: if len(paths) < 2: continue for path in paths: - by_content.setdefault(_sha1(path), []).append(path) + by_content.setdefault(file_digest(path), []).append(path) found: list[Duplicate] = [] for sha1, paths in by_content.items(): diff --git a/scripts/resolve/review.py b/scripts/resolve/review.py index a7e32a7c5..3979bd6df 100644 --- a/scripts/resolve/review.py +++ b/scripts/resolve/review.py @@ -2,7 +2,6 @@ from __future__ import annotations -import hashlib import os import sys import urllib.parse @@ -16,7 +15,7 @@ try: except ImportError: yaml = None -from core.hashing import compute_hashes, parse_hash_list, parse_md5_list +from core.hashing import compute_hashes, parse_hash_list, parse_md5_list, stream_hashes from model.nodedup import _in_nodedup_dir from model.platforms import load_platform_config from model.profiles import load_emulator_profiles @@ -355,12 +354,9 @@ def _archive_members( if info.file_size > MAX_FILE_SIZE: described.append(f"`{info.filename}` too large to read here") continue - sha1, md5 = hashlib.sha1(), hashlib.md5() with archive.open(info) as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - sha1.update(chunk) - md5.update(chunk) - sha1_hex, md5_hex = sha1.hexdigest(), md5.hexdigest() + digests = stream_hashes(handle, frozenset({"sha1", "md5"})) + sha1_hex, md5_hex = digests["sha1"], digests["md5"] crc = f"{info.CRC:08x}" if sha1_hex in held: state = f"already held at `{held[sha1_hex]['path']}`" diff --git a/scripts/romrecipes/members.py b/scripts/romrecipes/members.py index 035c00b03..8b8280b6e 100644 --- a/scripts/romrecipes/members.py +++ b/scripts/romrecipes/members.py @@ -2,12 +2,12 @@ from __future__ import annotations -import hashlib import io import zipfile from collections.abc import Callable from pathlib import Path +from core.hashing import stream_hashes from core.torrentzip import Source as Readable @@ -39,8 +39,5 @@ def _opener(source: Path, member: str | None) -> Callable[[], Readable]: def _member_sha1(path: Path, name: str) -> str: - digest = hashlib.sha1() with _Member(path, name) as stream: - while chunk := stream.read(16 * 1024 * 1024): - digest.update(chunk) - return digest.hexdigest() + return stream_hashes(stream, frozenset({"sha1"}))["sha1"] diff --git a/scripts/sitegen/dataexports.py b/scripts/sitegen/dataexports.py index 931a85fe6..f6243c42c 100644 --- a/scripts/sitegen/dataexports.py +++ b/scripts/sitegen/dataexports.py @@ -4,7 +4,6 @@ from __future__ import annotations import csv import functools -import hashlib import io import json import os @@ -16,6 +15,7 @@ from collections.abc import Callable from pathlib import Path from core.artifacts import json_text as _json_text +from core.hashing import file_digest from model import retired as model_retired from model.dumpcatalog import load_provenance_snapshots from packs.crossref import FileConsumers @@ -90,14 +90,6 @@ def _csv_document(fieldnames: list[str], rows: list[dict]) -> str: return stream.getvalue() -def _sha256_path(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - def _verify_outcomes( coverage: dict, sha1_by_path: dict[str, str] ) -> Callable[[str, str], dict]: @@ -880,7 +872,7 @@ def generate_data_exports( "url": relative, "media_type": media_type, "bytes": path.stat().st_size, - "sha256": _sha256_path(path), + "sha256": file_digest(path, "sha256"), } if schema: item["schema"] = schema diff --git a/tests/test_autorun.py b/tests/test_autorun.py index 6237d5225..22e364916 100644 --- a/tests/test_autorun.py +++ b/tests/test_autorun.py @@ -29,6 +29,7 @@ from unattended import runner from unattended import timers as unattended_timers from unattended import worktree as unattended_worktree from core import childenv +from core.hashing import file_digest from core import hostguard from core import statefile import bios_integrity as bib @@ -789,7 +790,7 @@ class AssetSync(Scratch): (self.root / rel).parent.mkdir(parents=True, exist_ok=True) (self.root / rel).write_bytes(data) self.db = {"files": { - sync.sha1_of(self.root / "bios/A/big.bin"): {"path": "bios/A/big.bin", "size": 1}, + file_digest(self.root / "bios/A/big.bin"): {"path": "bios/A/big.bin", "size": 1}, "0" * 40: {"path": "bios/C/solo.iso", "size": 1}, }} @@ -853,7 +854,7 @@ class BiosIntegrity(Scratch): path.write_bytes(data) # An old mtime keeps git from re-reading the file as racily clean. os.utime(path, (self.OLD, self.OLD)) - sha1 = bib.sha1_of(path) + sha1 = file_digest(path) self.db["files"][sha1] = {"path": rel, "sha1": sha1} run_git(self.repo, "add", ".gitignore", *[r for r in files if "Big" not in r]) run_git(self.repo, "commit", "--quiet", "-m", "chore: start") diff --git a/tests/test_hashing.py b/tests/test_hashing.py index c33ae09e8..bb24c77ab 100644 --- a/tests/test_hashing.py +++ b/tests/test_hashing.py @@ -1,12 +1,16 @@ -"""compute_hashes reads a file once per process and change.""" +"""compute_hashes reads a file once per process and change, and one loop digests files and streams.""" from __future__ import annotations import tests +import hashlib +import io import shutil import tempfile import unittest +import zipfile +import zlib from pathlib import Path from unittest import mock @@ -41,5 +45,42 @@ class HashesAreReadOncePerContent(unittest.TestCase): self.assertNotEqual(hashing.compute_hashes(self.file)["sha1"], first["sha1"]) +class OneDigestLoopForFilesAndStreams(unittest.TestCase): + """A ZIP member, a file and an open stream are hashed by the same loop, + so the pack check, the PR review and the recipes agree with the resolver.""" + + DATA = bytes(range(256)) * 600 # over two 64 KiB reads + + def setUp(self): + self.dir = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) + self.addCleanup(shutil.rmtree, self.dir, True) + self.file = self.dir / "rom.bin" + self.file.write_bytes(self.DATA) + + def test_a_stream_gives_the_file_digests(self): + expected = { + "sha1": hashlib.sha1(self.DATA).hexdigest(), + "md5": hashlib.md5(self.DATA).hexdigest(), + "sha256": hashlib.sha256(self.DATA).hexdigest(), + "crc32": format(zlib.crc32(self.DATA) & 0xFFFFFFFF, "08x"), + "adler32": format(zlib.adler32(self.DATA) & 0xFFFFFFFF, "08x"), + } + self.assertEqual(hashing.compute_hashes(self.file, cache=False), expected) + with open(self.file, "rb") as handle: + self.assertEqual(hashing.stream_hashes(handle, frozenset(expected)), expected) + self.assertEqual(hashing.stream_hashes(io.BytesIO(self.DATA), frozenset({"crc32"})), + {"crc32": expected["crc32"]}) + + def test_a_zip_member_and_md5sum(self): + archive = self.dir / "set.zip" + with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zf: + zf.writestr("rom.bin", self.DATA) + with zipfile.ZipFile(archive) as zf, zf.open("rom.bin") as member: + sha1 = hashing.stream_hashes(member, frozenset({"sha1"}))["sha1"] + self.assertEqual(sha1, hashing.file_digest(self.file)) + self.assertEqual(hashing.md5sum(self.file), hashlib.md5(self.DATA).hexdigest()) + self.assertEqual(hashing.md5sum(io.BytesIO(self.DATA)), hashlib.md5(self.DATA).hexdigest()) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_identity.py b/tests/test_identity.py index 14d0e8dce..b006e421d 100644 --- a/tests/test_identity.py +++ b/tests/test_identity.py @@ -99,7 +99,7 @@ class TestCrossVendorDuplicates(unittest.TestCase): self._write("Sega/Saturn/cartridge.bin", b"kick") self._write("Sony/PlayStation/scph5501.bin", b"a longer dump") self._write("Sega/Saturn/other.bin", b"same") - with mock.patch.object(identity, "_sha1", wraps=identity._sha1) as hashed: + with mock.patch.object(identity, "file_digest", wraps=identity.file_digest) as hashed: found = self._scan() read = sorted(Path(call.args[0]).name for call in hashed.call_args_list) self.assertEqual(read, ["cartridge.bin", "kickstart.rom", "other.bin"])