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,