refactor: print the hash lookup from packs

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 21:42:19 +01:00
1 parent 3df143cbe1
commit e36516f3b0
7 files changed
+177 -137

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
"""The hashes --from-md5 and --from-md5-file name, read and checked."""
from __future__ import annotations
import re
# Digest length in hex digits -> kind. A 29-digit MD5 is a value cut short,
# looked up as the resolver looks one up (cut_md5_owner).
_HASH_KINDS = {8: "crc32", 29: "md5", 32: "md5", 40: "sha1", 64: "sha256"}
_HEX_DIGITS = re.compile(r"[0-9a-f]+")
_WORD = re.compile(r"[0-9A-Za-z]+")
ACCEPTED_HASHES = (
"CRC32 (8 hex digits), MD5 (32, or the 29 Batocera writes), "
"SHA-1 (40) or SHA-256 (64)"
)
def _detect_hash_type(h: str) -> str | None:
"""The digest a hex string is, by its length, or None."""
return _HASH_KINDS.get(len(h))
def _hash_token(token: str) -> tuple[str, str] | None:
"""(kind, value) when a token is a whole digest of a known length."""
value = token.strip().lower().removeprefix("*").removeprefix("0x")
kind = _detect_hash_type(value)
if kind and _HEX_DIGITS.fullmatch(value):
return kind, value
return None
def _refuse(rejected: list[str]) -> None:
shown = ", ".join(rejected[:5]) + (", ..." if len(rejected) > 5 else "")
raise ValueError(f"not a hash: {shown}. Accepted: {ACCEPTED_HASHES}")
def parse_hash_input(raw: str) -> list[tuple[str, str]]:
"""Parse a comma-separated hash string into (type, hash) tuples.
A part that is no digest is refused rather than dropped: a 12-digit
value was looked up as an MD5 and reported NOT FOUND, and a SHA-256
vanished without a word.
"""
results: list[tuple[str, str]] = []
rejected: list[str] = []
for part in raw.split(","):
if not part.strip():
continue
parsed = _hash_token(part)
if parsed:
results.append(parsed)
else:
rejected.append(part.strip())
if rejected:
_refuse(rejected)
return results
def parse_hash_file(path: str) -> list[tuple[str, str]]:
"""Parse a hash file: one hash per line, alone or beside a file name as
md5sum writes it, ``#`` for comments. A line holding no digest is
refused with its line number."""
results: list[tuple[str, str]] = []
rejected: list[str] = []
with open(path) as f:
for number, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith("#"):
continue
parsed = next(
(h for h in map(_hash_token, _WORD.findall(line)) if h), None
)
if parsed:
results.append(parsed)
else:
rejected.append(f"line {number} ({line[:40]})")
if rejected:
_refuse(rejected)
return results
+24
View File
@@ -0,0 +1,24 @@
"""The --from-md5 lookup report, printed for a person."""
from __future__ import annotations
from resolve.packfiles import HashLookup
def print_hash_lookup(records: list[HashLookup]) -> int:
"""Print each looked-up hash and return how many the database lacks."""
for record in records:
print(f"\n{record.kind.upper()}: {record.value}")
if not record.found:
print(" NOT FOUND in database")
continue
print(f" SHA1: {record.sha1}")
print(f" MD5: {record.md5}")
print(f" Name: {record.name}")
if record.path:
print(f" Path: {record.path}")
print(f" In repo: {'YES' if record.in_repo else 'NO'}")
missing = sum(not record.found for record in records)
if missing:
print(f"\n{missing} of {len(records)} hash(es) not in the database")
return missing
+4 -9
View File
@@ -25,6 +25,8 @@ from packs.emulatorpack import (
build_system_pack,
print_emulator_pack,
)
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.outputdir import holds_other_kind, pack_output_lock
from packs.packcheck import run_verify_packs
@@ -32,12 +34,7 @@ from packs.packoptions import refuse_for_verify_packs, refuse_unapplied_flags, v
from packs.platformrun import requested_platforms, run_platform_mode
from packs.targets import generate_target_manifests
from resolve import packfiles as packresolve
from resolve.packfiles import (
ACCEPTED_HASHES,
lookup_hashes,
parse_hash_file,
parse_hash_input,
)
from resolve.packfiles import lookup_hashes
def _run_quick_mode(
@@ -96,9 +93,7 @@ def _run_hash_mode(args: argparse.Namespace) -> None:
db = load_database(args.db)
if not args.platform and not args.emulator:
# A lookup that found nothing is an answer a script must see.
if lookup_hashes(
hashes, db, args.bios_dir, args.emulators_dir, args.platforms_dir
):
if print_hash_lookup(lookup_hashes(hashes, db, args.bios_dir)):
sys.exit(1)
return
zip_contents = build_zip_contents_index(db)
+31 -105
View File
@@ -9,9 +9,9 @@ from __future__ import annotations
import contextlib
import http.client
import os
import re
import urllib.error
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from core import upstream
@@ -176,130 +176,56 @@ def pending_release_asset(
return None
# Digest length in hex digits -> kind. A 29-digit MD5 is a value cut short,
# looked up as the resolver looks one up (cut_md5_owner).
_HASH_KINDS = {8: "crc32", 29: "md5", 32: "md5", 40: "sha1", 64: "sha256"}
_HEX_DIGITS = re.compile(r"[0-9a-f]+")
_WORD = re.compile(r"[0-9A-Za-z]+")
ACCEPTED_HASHES = (
"CRC32 (8 hex digits), MD5 (32, or the 29 Batocera writes), "
"SHA-1 (40) or SHA-256 (64)"
)
def _detect_hash_type(h: str) -> str | None:
"""The digest a hex string is, by its length, or None."""
return _HASH_KINDS.get(len(h))
def _hash_token(token: str) -> tuple[str, str] | None:
"""(kind, value) when a token is a whole digest of a known length."""
value = token.strip().lower().removeprefix("*").removeprefix("0x")
kind = _detect_hash_type(value)
if kind and _HEX_DIGITS.fullmatch(value):
return kind, value
return None
def _refuse(rejected: list[str]) -> None:
shown = ", ".join(rejected[:5]) + (", ..." if len(rejected) > 5 else "")
raise ValueError(f"not a hash: {shown}. Accepted: {ACCEPTED_HASHES}")
def parse_hash_input(raw: str) -> list[tuple[str, str]]:
"""Parse a comma-separated hash string into (type, hash) tuples.
A part that is no digest is refused rather than dropped: a 12-digit
value was looked up as an MD5 and reported NOT FOUND, and a SHA-256
vanished without a word.
"""
results: list[tuple[str, str]] = []
rejected: list[str] = []
for part in raw.split(","):
if not part.strip():
continue
parsed = _hash_token(part)
if parsed:
results.append(parsed)
else:
rejected.append(part.strip())
if rejected:
_refuse(rejected)
return results
def parse_hash_file(path: str) -> list[tuple[str, str]]:
"""Parse a hash file: one hash per line, alone or beside a file name as
md5sum writes it, ``#`` for comments. A line holding no digest is
refused with its line number."""
results: list[tuple[str, str]] = []
rejected: list[str] = []
with open(path) as f:
for number, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith("#"):
continue
parsed = next(
(h for h in map(_hash_token, _WORD.findall(line)) if h), None
)
if parsed:
results.append(parsed)
else:
rejected.append(f"line {number} ({line[:40]})")
if rejected:
_refuse(rejected)
return results
def sha1_for_hash(hash_type: str, hash_val: str, db: dict) -> str | None:
"""The database key a looked-up hash names, or None."""
return record_for_hash(db, hash_type, hash_val)
def lookup_hashes(
hashes: list[tuple[str, str]],
db: dict,
bios_dir: str,
emulators_dir: str,
platforms_dir: str,
) -> int:
"""Print diagnostic info for each hash and return how many were not found."""
missing = 0
files_db = db.get("files", {})
@dataclass(frozen=True)
class HashLookup:
"""What the database and the disk say about one looked-up hash.
``sha1`` is empty when the database holds no file under the hash."""
kind: str
value: str
sha1: str = ""
md5: str = ""
name: str = ""
path: str = ""
in_repo: bool = False
@property
def found(self) -> bool:
return bool(self.sha1)
def lookup_hashes(
hashes: list[tuple[str, str]], db: dict, bios_dir: str,
) -> list[HashLookup]:
"""One record per hash: the file the database names, and whether the
repository holds its bytes (at its path, or wherever resolution finds them)."""
files_db = db.get("files", {})
records: list[HashLookup] = []
for hash_type, hash_val in hashes:
sha1 = sha1_for_hash(hash_type, hash_val, db)
if not sha1:
print(f"\n{hash_type.upper()}: {hash_val}")
print(" NOT FOUND in database")
missing += 1
records.append(HashLookup(hash_type, hash_val))
continue
entry = files_db[sha1]
name = entry.get("name", "?")
md5 = entry.get("md5", "?")
path = entry.get("path", "")
print(f"\n{hash_type.upper()}: {hash_val}")
print(f" SHA1: {sha1}")
print(f" MD5: {md5}")
print(f" Name: {name}")
if path:
print(f" Path: {path}")
# Check if file exists in repo (by path or by resolve_local_file)
in_repo = bool(path) and os.path.exists(path)
if not in_repo:
try:
fe_check = {"name": name, "sha1": sha1, "md5": md5}
local, status = resolve_file(fe_check, db, bios_dir, {})
if local and status != "not_found":
in_repo = True
in_repo = bool(local) and status != "not_found"
except (KeyError, OSError):
pass
print(f" In repo: {'YES' if in_repo else 'NO'}")
if missing:
print(f"\n{missing} of {len(hashes)} hash(es) not in the database")
return missing
records.append(HashLookup(hash_type, hash_val, sha1, md5, name, path, in_repo))
return records
def resolve_file(
file_entry: dict,
+1
View File
@@ -23,6 +23,7 @@ COMMANDS = {
"packs/manifestrun.py", "packs/packcheck.py", "packs/runscope.py", "packs/platformrun.py",
"packs/packoptions.py", "packs/packmodes.py", "packs/packcounts.py",
"packs/emulatorentries.py", "packs/integrity.py",
"packs/hashinput.py", "packs/hashlookup.py",
),
"verify.py": (
"packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py",
+2 -2
View File
@@ -7421,7 +7421,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
found in input"."""
def test_digests_are_read_by_length(self):
from scripts.resolve.packfiles import parse_hash_input
from scripts.packs.hashinput import parse_hash_input
sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
self.assertEqual(parse_hash_input(f"0x1A2B3C4D,{sha256}"), [
@@ -7430,7 +7430,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
self.assertEqual(parse_hash_input("a" * 29), [("md5", "a" * 29)])
def test_anything_else_is_refused_with_the_formats(self):
from scripts.resolve.packfiles import parse_hash_file, parse_hash_input
from scripts.packs.hashinput import parse_hash_file, parse_hash_input
for raw in ("1234567890ab", "zz", "490f666e1afb15b7362b406ed1cea246,zz"):
with self.subTest(raw=raw), self.assertRaises(ValueError) as ctx:
+36 -21
View File
@@ -2692,7 +2692,7 @@ class TestE2E(unittest.TestCase):
def test_138_parse_hash_input(self):
"""parse_hash_input handles various formats."""
from resolve.packfiles import parse_hash_input
from packs.hashinput import parse_hash_input
# Plain MD5
result = parse_hash_input("d8f1206299c48946e6ec5ef96d014eaa")
@@ -2712,7 +2712,7 @@ class TestE2E(unittest.TestCase):
def test_139_parse_hash_file(self):
"""parse_hash_file handles comments, empty lines, various formats."""
from resolve.packfiles import parse_hash_file
from packs.hashinput import parse_hash_file
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
f.write("# PS1 BIOS files\n")
@@ -2729,11 +2729,8 @@ class TestE2E(unittest.TestCase):
os.unlink(tmp_path)
def test_140_lookup_hashes_found(self):
"""lookup_hashes returns file info for known hashes."""
import contextlib
import io
from resolve.packfiles import lookup_hashes
"""lookup_hashes returns the record of a known hash."""
from resolve.packfiles import HashLookup, lookup_hashes
db = {
"files": {
@@ -2750,35 +2747,53 @@ class TestE2E(unittest.TestCase):
"by_crc32": {},
},
}
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
missing = lookup_hashes([("md5", "md5abc")], db, "bios", "emulators", "platforms")
output = buf.getvalue()
self.assertIn("test.bin", output)
self.assertIn("sha1abc", output)
records = lookup_hashes([("md5", "md5abc")], db, "bios")
# The record's path, the one field the schema gives it. A read of
# "paths" printed nothing.
self.assertIn("Path: bios/Mfr/Console/test.bin", output)
self.assertEqual(missing, 0)
self.assertEqual(records, [HashLookup(
"md5", "md5abc", "sha1abc", "md5abc", "test.bin",
"bios/Mfr/Console/test.bin", False,
)])
self.assertTrue(records[0].found)
def test_141_lookup_hashes_not_found(self):
"""lookup_hashes reports unknown hashes."""
"""lookup_hashes reports unknown hashes, and the report counts them."""
import contextlib
import io
from packs.hashlookup import print_hash_lookup
from resolve.packfiles import lookup_hashes
db = {"files": {}, "indexes": {"by_md5": {}, "by_crc32": {}}}
unknown = "unknown123" + "0" * 22
records = lookup_hashes([("md5", unknown)], db, "bios")
self.assertEqual([r.found for r in records], [False])
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
missing = lookup_hashes(
[("md5", "unknown123" + "0" * 22)], db, "bios", "emulators", "platforms"
)
output = buf.getvalue()
self.assertIn("NOT FOUND", output)
missing = print_hash_lookup(records)
self.assertIn("NOT FOUND", buf.getvalue())
# The CLI exited 0 on this, so a script read "found".
self.assertEqual(missing, 1)
def test_141b_lookup_report_names_the_file(self):
"""The printed report gives the file's hashes, name, path and presence."""
import contextlib
import io
from packs.hashlookup import print_hash_lookup
from resolve.packfiles import HashLookup
record = HashLookup("md5", "md5abc", "sha1abc", "md5abc", "test.bin",
"bios/Mfr/Console/test.bin", True)
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
missing = print_hash_lookup([record])
self.assertEqual(buf.getvalue(), (
"\nMD5: md5abc\n SHA1: sha1abc\n MD5: md5abc\n Name: test.bin\n"
" Path: bios/Mfr/Console/test.bin\n In repo: YES\n"
))
self.assertEqual(missing, 0)
def test_142_from_md5_platform_pack(self):
"""--from-md5 with --platform generates correctly laid out ZIP."""
import tempfile