refactor: type and split the build helpers

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:52:20 +01:00
1 parent 9ac7b848a4
commit aab606f496
8 files changed
+174 -127

No files matched your search

+74 -36
View File
@@ -16,7 +16,7 @@ import hashlib
import os
import zipfile
from collections import defaultdict
from collections.abc import Callable, Iterable
from collections.abc import Callable, Iterable, Sequence
# A held file larger than this is not read: no chip image is near it.
MAX_SOURCE_SIZE = 64 * 1024 * 1024
@@ -61,7 +61,7 @@ TRANSFORMS: tuple[tuple[str, Callable[[int], int | None], Callable[[bytes], byte
)
def _gf2_times(matrix: list[int], vector: int) -> int:
def _gf2_times(matrix: Sequence[int], vector: int) -> int:
total, row = 0, 0
while vector:
if vector & 1:
@@ -71,7 +71,7 @@ def _gf2_times(matrix: list[int], vector: int) -> int:
return total
def _gf2_square(matrix: list[int]) -> list[int]:
def _gf2_square(matrix: Sequence[int]) -> list[int]:
return [_gf2_times(matrix, matrix[n]) for n in range(32)]
@@ -127,10 +127,10 @@ def _read(held: dict, archives: dict[str, zipfile.ZipFile] | None = None) -> byt
if archives is None:
with zipfile.ZipFile(held["archive"]) as zf:
return zf.read(held["member"])
zf = archives.get(held["archive"])
if zf is None:
zf = archives[held["archive"]] = zipfile.ZipFile(held["archive"])
return zf.read(held["member"])
opened = archives.get(held["archive"])
if opened is None:
opened = archives[held["archive"]] = zipfile.ZipFile(held["archive"])
return opened.read(held["member"])
with open(held["path"], "rb") as handle:
return handle.read()
except (OSError, KeyError, zipfile.BadZipFile):
@@ -160,13 +160,15 @@ def _held_sources(db: dict) -> list[dict]:
infos = [i for i in zf.infolist() if not i.is_dir()]
except (OSError, zipfile.BadZipFile):
continue
for info in infos:
if 0 < info.file_size <= MAX_SOURCE_SIZE:
sources.append({
"path": f"{path}/{info.filename}", "archive": path,
"member": info.filename, "size": info.file_size,
"crc32": f"{info.CRC:08x}", "group": path,
})
sources.extend(
{
"path": f"{path}/{info.filename}", "archive": path,
"member": info.filename, "size": info.file_size,
"crc32": f"{info.CRC:08x}", "group": path,
}
for info in infos
if 0 < info.file_size <= MAX_SOURCE_SIZE
)
return sources
@@ -201,13 +203,29 @@ def _derivable(
found: dict[str, dict] = {}
files = _held_sources(db)
_find_transformed(files, wanted, sizes, archives, found)
_find_concatenated(files, by_size_crc, sizes, archives, found)
return found
def _find_transformed(
files: list[dict],
wanted: dict[tuple[int, str], str],
sizes: set[int],
archives: dict[str, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record each wanted sha1 one transform of a held file produces."""
# The same chip sits in many archives. Its transforms are a function of
# its bytes alone, and the first path read keeps the match, so a content
# already transformed has nothing left to find.
transformed: set[str] = set()
for held in files:
n = held["size"]
useful = [t for t in TRANSFORMS if t[1](n) in sizes]
useful = [
(name, size_out, transform) for name, out_size, transform in TRANSFORMS
if (size_out := out_size(n)) is not None and size_out in sizes
]
if not useful:
continue
data = _read(held, archives)
@@ -217,12 +235,21 @@ def _derivable(
if content in transformed:
continue
transformed.add(content)
for name, out_size, transform in useful:
for name, size_out, transform in useful:
out = transform(data)
sha1 = wanted.get((out_size(n), hashlib.sha1(out).hexdigest()))
sha1 = wanted.get((size_out, hashlib.sha1(out).hexdigest()))
if sha1 and sha1 not in found:
found[sha1] = {"from": [held["path"]], "transform": name}
def _find_concatenated(
files: list[dict],
by_size_crc: dict[tuple[int, int], list[str]],
sizes: set[int],
archives: dict[str, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record each wanted sha1 two held files of one group make end to end."""
# Romsets repeat the same chip pairs: a combined crc is computed once.
combined: dict[tuple[str, str, int], int] = {}
by_dir: dict[str, list[dict]] = defaultdict(list)
@@ -242,22 +269,33 @@ def _derivable(
if total not in sizes:
continue
for second in seconds:
if first is second:
continue
key = (first["crc32"], second["crc32"], second["size"])
crc = combined.get(key)
if crc is None:
crc = combined[key] = crc32_combine(
int(first["crc32"], 16), int(second["crc32"], 16), second["size"])
candidates = [s for s in by_size_crc.get((total, crc), [])
if s not in found]
if not candidates:
continue
a, b = _read(first, archives), _read(second, archives)
if a is None or b is None:
continue
sha1 = hashlib.sha1(a + b).hexdigest()
if sha1 in candidates:
found[sha1] = {"from": [first["path"], second["path"]],
"transform": "concatenated"}
return found
if first is not second:
_try_pair(first, second, total, combined, by_size_crc, archives, found)
def _try_pair(
first: dict,
second: dict,
total: int,
combined: dict[tuple[str, str, int], int],
by_size_crc: dict[tuple[int, int], list[str]],
archives: dict[str, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record the wanted sha1 first + second makes, if their crc names one."""
key = (first["crc32"], second["crc32"], second["size"])
crc = combined.get(key)
if crc is None:
crc = combined[key] = crc32_combine(
int(first["crc32"], 16), int(second["crc32"], 16), second["size"])
candidates = [s for s in by_size_crc.get((total, crc), [])
if s not in found]
if not candidates:
return
a, b = _read(first, archives), _read(second, archives)
if a is None or b is None:
return
sha1 = hashlib.sha1(a + b).hexdigest()
if sha1 in candidates:
found[sha1] = {"from": [first["path"], second["path"]],
"transform": "concatenated"}
+1 -1
View File
@@ -20,7 +20,7 @@ def load_provenance_snapshots(provenance_dir: str = DEFAULT_PROVENANCE_DIR) -> d
entries written by the redump scraper or the pack importer. Missing
directory means no snapshots: returns an empty dict.
"""
snapshots = {}
snapshots: dict[str, dict] = {}
prov_path = Path(provenance_dir)
if not prov_path.is_dir():
return snapshots
+6 -6
View File
@@ -10,7 +10,7 @@ import os
import zipfile
import zlib
from pathlib import Path
from typing import BinaryIO
from typing import IO, BinaryIO
from collections.abc import Iterable
@@ -85,16 +85,16 @@ def _compute_hashes(filepath: str | Path, algos: frozenset[str]) -> dict[str, st
result["adler32"] = format(adler & 0xFFFFFFFF, "08x")
return result
def md5sum(source: str | Path | object) -> 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 hasattr(source, "read"):
for chunk in iter(lambda: source.read(65536), b""):
h.update(chunk)
else:
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()
_md5_composite_cache: dict[str, str] = {}
+25 -22
View File
@@ -159,6 +159,30 @@ def fetch_large_file(
return None
def _download(name: str, tmp_path: str) -> bool:
"""Stream the first release URL of *name* that answers into *tmp_path*."""
# Only a name no candidate answers is reported: a spaced name is
# published dotted, and logging its first 404 read as a missing asset.
failures: list[str] = []
for candidate, url in _asset_urls(name):
try:
req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"})
with urllib.request.urlopen(req, timeout=300) as resp, open(tmp_path, "wb") as f:
while True:
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
return True
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
# A stalled or cut stream is a timeout or IncompleteRead, not
# a URLError: it escaped this handler and left its scratch.
failures.append(f" large file {candidate}: {exc}")
for failure in failures:
print(failure, file=sys.stderr)
return False
def _fetch_asset(
name: str,
dest_dir: str,
@@ -209,28 +233,7 @@ def _fetch_asset(
)
os.close(tmp_fd)
try:
downloaded = False
# Only a name no candidate answers is reported: a spaced name is
# published dotted, and logging its first 404 read as a missing asset.
failures: list[str] = []
for candidate, url in _asset_urls(name):
try:
req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"})
with urllib.request.urlopen(req, timeout=300) as resp, open(tmp_path, "wb") as f:
while True:
chunk = resp.read(65536)
if not chunk:
break
f.write(chunk)
downloaded = True
break
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
# A stalled or cut stream is a timeout or IncompleteRead, not
# a URLError: it escaped this handler and left its scratch.
failures.append(f" large file {candidate}: {exc}")
if not downloaded:
for failure in failures:
print(failure, file=sys.stderr)
if not _download(name, tmp_path):
return None
snapshot = _read_once(tmp_path)
if snapshot is None or not _matches(snapshot[0], expected_sha1, expected_md5):
+26 -20
View File
@@ -139,7 +139,9 @@ def profile_needs(profiles: dict, db: dict) -> dict:
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 = [(field, v) for field in HASH_FIELDS for v in _values(entry, field)]
keys: list[tuple[object, ...]] = [
(field, v) for field in HASH_FIELDS for v in _values(entry, field)
]
if entry.get("size") is not None:
keys += [("crc32", _crc_key(v), entry["size"]) for v in _values(entry, "crc32")]
for key in keys:
@@ -344,12 +346,11 @@ def build_report(
out_of_scope = len({
dump_identity(e) for e in unmatched if e.get("dat", "") not in covered_dats
})
matched = len(matched)
report[source] = {
"imported_at": snapshot.get("imported_at", ""),
"dats": snapshot.get("dats", {}),
"total": len(snapshot["entries"]),
"matched": matched,
"matched": len(matched),
"covered_dats": sorted(covered_dats),
"missing": missing,
"out_of_scope": out_of_scope,
@@ -357,6 +358,27 @@ def build_report(
return report
def _print_missing(entry: dict, derived: dict[str, dict]) -> None:
"""One missing dump, with what derives it, reads it and holds it."""
label = entry.get("description") or entry["name"]
source = derived.get(entry.get("sha1", ""))
if source:
print(f" DERIVABLE {entry['name']} ({label}): {source['transform']} "
f"of {' + '.join(source['from'])}")
else:
print(f" MISSING {entry['name']} ({label}) sha1={entry.get('sha1')}")
for need in entry.get("needed_by", []):
print(f" needed by {need['emulator']} as {need['name']} "
f"({'required' if need['required'] else 'optional'}, "
f"matched by {need['by']})")
for hit in entry.get("romsets", []):
versions = hit["dats"][0] if len(hit["dats"]) == 1 else (
f"{hit['dats'][0]} to {hit['dats'][-1]}"
)
print(f" in {hit['source']} {hit['archive']} as "
f"{hit['member']} ({versions})")
def main() -> int:
parser = argparse.ArgumentParser(allow_abbrev=False, description="Dump-catalog coverage report")
parser.add_argument("--db", default="database.json", help="Database path")
@@ -437,23 +459,7 @@ def main() -> int:
if args.missing:
# A dump an emulator reads comes first: it fills a hole in a pack.
for entry in sorted(data["missing"], key=lambda e: not e.get("needed_by")):
label = entry.get("description") or entry["name"]
source = derived.get(entry.get("sha1", ""))
if source:
print(f" DERIVABLE {entry['name']} ({label}): {source['transform']} "
f"of {' + '.join(source['from'])}")
else:
print(f" MISSING {entry['name']} ({label}) sha1={entry.get('sha1')}")
for need in entry.get("needed_by", []):
print(f" needed by {need['emulator']} as {need['name']} "
f"({'required' if need['required'] else 'optional'}, "
f"matched by {need['by']})")
for hit in entry.get("romsets", []):
versions = hit["dats"][0] if len(hit["dats"]) == 1 else (
f"{hit['dats'][0]} to {hit['dats'][-1]}"
)
print(f" in {hit['source']} {hit['archive']} as "
f"{hit['member']} ({versions})")
_print_missing(entry, derived)
total_missing = distinct_missing(report)
if total_missing:
+6 -8
View File
@@ -278,9 +278,7 @@ def _is_safe_tar_member(member: tarfile.TarInfo, dest: Path) -> bool:
return False
resolved = (dest / member.name).resolve()
dest_str = str(dest.resolve()) + os.sep
if not str(resolved).startswith(dest_str) and str(resolved) != str(dest.resolve()):
return False
return True
return str(resolved).startswith(dest_str) or str(resolved) == str(dest.resolve())
def _download_and_extract(
@@ -349,11 +347,11 @@ def _download_and_extract(
elif member.isfile():
dest_file = extract_dir / rel
dest_file.parent.mkdir(parents=True, exist_ok=True)
with tf.extractfile(member) as src:
if src is None:
continue
with open(dest_file, "wb") as dst:
shutil.copyfileobj(src, dst)
src = tf.extractfile(member)
if src is None:
continue
with src, open(dest_file, "wb") as dst:
shutil.copyfileobj(src, dst)
file_count += 1
if not file_count:
+20 -16
View File
@@ -581,6 +581,25 @@ def _resolve_modes(args: argparse.Namespace) -> None:
args.identify = args.missing = True
def print_identification(ident: dict) -> None:
"""Which recipe reproduces each local archive, counted by recipe."""
print(
f"\nIdentification: {len(ident['identified'])} archives reproduced "
f"by a recipe, {len(ident['unidentified'])} unidentified"
)
print(
" The label is the oldest version producing these bytes: a recipe "
"unchanged since 0.177 is counted there, not at its own version."
)
by_recipe: dict[str, int] = defaultdict(int)
for record in ident["identified"]:
by_recipe[record["recipe"]] += 1
for label, count in sorted(by_recipe.items(), key=lambda kv: (-kv[1], kv[0])):
print(f" {label}: {count}")
for record in ident["unidentified"][:10]:
print(f" UNIDENTIFIED: {record['path']}")
def main() -> int:
parser = argparse.ArgumentParser(
allow_abbrev=False,
@@ -692,22 +711,7 @@ def main() -> int:
print(f" UNREADABLE: {problem}")
if args.identify:
ident = result["identify"]
print(
f"\nIdentification: {len(ident['identified'])} archives reproduced "
f"by a recipe, {len(ident['unidentified'])} unidentified"
)
print(
" The label is the oldest version producing these bytes: a recipe "
"unchanged since 0.177 is counted there, not at its own version."
)
by_recipe: dict[str, int] = defaultdict(int)
for record in ident["identified"]:
by_recipe[record["recipe"]] += 1
for label, count in sorted(by_recipe.items(), key=lambda kv: (-kv[1], kv[0])):
print(f" {label}: {count}")
for record in ident["unidentified"][:10]:
print(f" UNIDENTIFIED: {record['path']}")
print_identification(result["identify"])
if args.missing:
print_missing(result["missing"])
+16 -18
View File
@@ -64,31 +64,29 @@ def _pick_yaml_loader() -> type[yaml.constructor.SafeConstructor] | None:
return None
base = getattr(yaml, "CSafeLoader", None) or yaml.SafeLoader
class _UniqueKeyLoader(base):
"""Refuses a mapping that names a key twice.
def construct_mapping(
self: yaml.constructor.SafeConstructor, node: yaml.MappingNode, deep: bool = False
) -> dict:
"""Refuse a mapping that names a key twice.
PyYAML keeps the last value without a word: the registry once
carried two target_source keys for Recalbox and read only one. Only
a mapping that came out shorter than its source is re-read. No data
here uses merge keys (<<), which would count as repeats too.
"""
mapping = base.construct_mapping(self, node, deep=deep)
if len(mapping) < len(node.value):
seen: set = set()
for key_node, _value in node.value:
key = self.construct_object(key_node, deep=deep)
if key in seen:
raise yaml.constructor.ConstructorError(
None, None, f"duplicate key {key!r}", key_node.start_mark
)
seen.add(key)
return mapping
def construct_mapping(
self, node: yaml.MappingNode, deep: bool = False
) -> dict:
mapping = super().construct_mapping(node, deep=deep)
if len(mapping) < len(node.value):
seen: set = set()
for key_node, _value in node.value:
key = self.construct_object(key_node, deep=deep)
if key in seen:
raise yaml.constructor.ConstructorError(
None, None, f"duplicate key {key!r}", key_node.start_mark
)
seen.add(key)
return mapping
return _UniqueKeyLoader
return type("_UniqueKeyLoader", (base,), {"construct_mapping": construct_mapping})
_YAML_LOADER = _pick_yaml_loader()