mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-24 10:37:54 -06:00
chore: merge the shared module quality work
This commit is contained in:
commit
5929d6f873
12 files changed
+2080
-1539
No files matched your search
+1335
-981
File diff suppressed because it is too large.
Load diff
+118
-94
@@ -145,7 +145,7 @@ def _plan_group_removals(
|
||||
|
||||
# True duplicates: same filename in multiple directories
|
||||
true_dupes_to_remove = []
|
||||
for name, name_paths in by_name.items():
|
||||
for name_paths in by_name.values():
|
||||
if len(name_paths) > 1:
|
||||
name_paths.sort(key=path_priority)
|
||||
true_dupes_to_remove.extend(name_paths[1:])
|
||||
@@ -194,6 +194,115 @@ def _plan_group_removals(
|
||||
return true_dupes_to_remove
|
||||
|
||||
|
||||
def _read_clone_map(clone_path: str) -> object:
|
||||
"""The clone map an earlier run wrote, {} when there is none."""
|
||||
# Read before anything is removed: the map is cumulative, and a run that
|
||||
# stopped on an unreadable one after deleting clones would lose them.
|
||||
try:
|
||||
with open(clone_path) as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except json.JSONDecodeError as e:
|
||||
raise SystemExit(
|
||||
f"{clone_path} is not valid JSON ({e}). Restore it from git "
|
||||
"before deduplicating again"
|
||||
) from e
|
||||
|
||||
|
||||
def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]:
|
||||
"""Remove (or name, in a dry run) each copy beside the canonical file."""
|
||||
removed: list[str] = []
|
||||
for dup in true_dupes_to_remove:
|
||||
if dup == canonical:
|
||||
continue
|
||||
if not os.path.exists(dup):
|
||||
continue
|
||||
if dry_run:
|
||||
print(f" WOULD REMOVE: {dup}")
|
||||
else:
|
||||
try:
|
||||
os.remove(dup)
|
||||
except OSError as e:
|
||||
print(f" WARNING: cannot remove {dup}: {e}")
|
||||
continue
|
||||
# Clean up empty .variants/ directories
|
||||
parent = os.path.dirname(dup)
|
||||
if os.path.basename(parent) == ".variants" and not os.listdir(parent):
|
||||
os.rmdir(parent)
|
||||
removed.append(dup)
|
||||
return removed
|
||||
|
||||
|
||||
def _settle_group(paths: list[str], true_dupes_to_remove: list[str], dry_run: bool) -> dict:
|
||||
"""Keep the best copy of one content and remove the others."""
|
||||
# Find the best canonical across all paths
|
||||
all_paths = [p for p in paths if p not in true_dupes_to_remove]
|
||||
if not all_paths:
|
||||
# All copies were marked for removal: keep the best one
|
||||
all_paths_sorted = sorted(paths, key=path_priority)
|
||||
all_paths = [all_paths_sorted[0]]
|
||||
true_dupes_to_remove = [p for p in paths if p != all_paths[0]]
|
||||
|
||||
canonical = sorted(all_paths, key=path_priority)[0]
|
||||
canonical_name = os.path.basename(canonical)
|
||||
|
||||
all_names = set(os.path.basename(p) for p in paths)
|
||||
alias_names = sorted(all_names - {canonical_name})
|
||||
|
||||
size = os.path.getsize(canonical)
|
||||
removed = _remove_copies(canonical, true_dupes_to_remove, dry_run)
|
||||
|
||||
if alias_names or true_dupes_to_remove:
|
||||
action = "Would remove" if dry_run else "Removed"
|
||||
dn = os.path.basename(canonical)
|
||||
print(f" {dn} (keep: {canonical})")
|
||||
if true_dupes_to_remove:
|
||||
print(f" {action} {len(true_dupes_to_remove)} copies")
|
||||
if alias_names:
|
||||
print(f" MAME clones: {alias_names}")
|
||||
return {
|
||||
"canonical": canonical,
|
||||
"removed": removed,
|
||||
"aliases": alias_names,
|
||||
"saved": size * len(removed),
|
||||
}
|
||||
|
||||
|
||||
def _remove_empty_dirs(bios_dir: str) -> int:
|
||||
"""Remove the directories the removals left empty, bottom up."""
|
||||
empty_cleaned = 0
|
||||
for root, dirs, files in os.walk(bios_dir, topdown=False):
|
||||
if not files and not dirs and root != bios_dir:
|
||||
os.rmdir(root)
|
||||
empty_cleaned += 1
|
||||
return empty_cleaned
|
||||
|
||||
|
||||
def _record_clone_map(
|
||||
mame_clones: dict[str, dict], previous: object, clone_path: str, dry_run: bool
|
||||
) -> None:
|
||||
"""Write the clone map, merged with what earlier runs recorded."""
|
||||
# A group is only visible while both copies are on disk, and this run
|
||||
# has just deleted the clone. Writing only what was seen this time
|
||||
# therefore erases every mapping an earlier run recorded, and the
|
||||
# canonical zip stops answering to the names it stands in for. The
|
||||
# older entries stay valid: their canonical file is still here.
|
||||
if not dry_run and isinstance(previous, dict):
|
||||
merged = dict(previous)
|
||||
merged.update(mame_clones)
|
||||
mame_clones = collapse_clone_chains(merged)
|
||||
if dry_run:
|
||||
print(f"\nWould write MAME clone map: {clone_path}")
|
||||
else:
|
||||
write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True))
|
||||
print(f"\nWrote MAME clone map: {clone_path}")
|
||||
print(
|
||||
f" {len(mame_clones)} canonical ZIPs with "
|
||||
f"{sum(len(v['clones']) for v in mame_clones.values())} clones"
|
||||
)
|
||||
|
||||
|
||||
def deduplicate(bios_dir: str, dry_run: bool = False) -> dict:
|
||||
"""Remove true duplicates, map MAME device clones.
|
||||
|
||||
@@ -208,21 +317,10 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict:
|
||||
clone_path = os.path.join(
|
||||
os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json"
|
||||
)
|
||||
# Read before anything is removed: the map is cumulative, and a run that
|
||||
# stopped on an unreadable one after deleting clones would lose them.
|
||||
try:
|
||||
with open(clone_path) as f:
|
||||
previous = json.load(f)
|
||||
except FileNotFoundError:
|
||||
previous = {}
|
||||
except json.JSONDecodeError as e:
|
||||
raise SystemExit(
|
||||
f"{clone_path} is not valid JSON ({e}). Restore it from git "
|
||||
"before deduplicating again"
|
||||
) from e
|
||||
previous = _read_clone_map(clone_path)
|
||||
|
||||
sha1_groups = scan_duplicates(bios_dir)
|
||||
results = {}
|
||||
results: dict[str, dict] = {}
|
||||
total_removed = 0
|
||||
total_saved = 0
|
||||
mame_clones: dict[str, dict] = {} # canonical_name -> {sha1, clones: [names]}
|
||||
@@ -236,65 +334,13 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict:
|
||||
if not true_dupes_to_remove:
|
||||
continue
|
||||
|
||||
# Find the best canonical across all paths
|
||||
all_paths = [p for p in paths if p not in true_dupes_to_remove]
|
||||
if not all_paths:
|
||||
# All copies were marked for removal: keep the best one
|
||||
all_paths_sorted = sorted(paths, key=path_priority)
|
||||
all_paths = [all_paths_sorted[0]]
|
||||
true_dupes_to_remove = [p for p in paths if p != all_paths[0]]
|
||||
|
||||
canonical = sorted(all_paths, key=path_priority)[0]
|
||||
canonical_name = os.path.basename(canonical)
|
||||
|
||||
all_names = set(os.path.basename(p) for p in paths)
|
||||
alias_names = sorted(all_names - {canonical_name})
|
||||
|
||||
size = os.path.getsize(canonical)
|
||||
|
||||
results[sha1] = {
|
||||
"canonical": canonical,
|
||||
"removed": [],
|
||||
"aliases": alias_names,
|
||||
}
|
||||
|
||||
for dup in true_dupes_to_remove:
|
||||
if dup == canonical:
|
||||
continue
|
||||
if not os.path.exists(dup):
|
||||
continue
|
||||
if dry_run:
|
||||
print(f" WOULD REMOVE: {dup}")
|
||||
else:
|
||||
try:
|
||||
os.remove(dup)
|
||||
except OSError as e:
|
||||
print(f" WARNING: cannot remove {dup}: {e}")
|
||||
continue
|
||||
# Clean up empty .variants/ directories
|
||||
parent = os.path.dirname(dup)
|
||||
if os.path.basename(parent) == ".variants" and not os.listdir(parent):
|
||||
os.rmdir(parent)
|
||||
results[sha1]["removed"].append(dup)
|
||||
total_removed += 1
|
||||
total_saved += size
|
||||
|
||||
if alias_names or true_dupes_to_remove:
|
||||
action = "Would remove" if dry_run else "Removed"
|
||||
dn = os.path.basename(canonical)
|
||||
print(f" {dn} (keep: {canonical})")
|
||||
if true_dupes_to_remove:
|
||||
print(f" {action} {len(true_dupes_to_remove)} copies")
|
||||
if alias_names:
|
||||
print(f" MAME clones: {alias_names}")
|
||||
settled = _settle_group(paths, true_dupes_to_remove, dry_run)
|
||||
total_removed += len(settled["removed"])
|
||||
total_saved += settled.pop("saved")
|
||||
results[sha1] = settled
|
||||
|
||||
# Clean up empty directories
|
||||
if not dry_run:
|
||||
empty_cleaned = 0
|
||||
for root, dirs, files in os.walk(bios_dir, topdown=False):
|
||||
if not files and not dirs and root != bios_dir:
|
||||
os.rmdir(root)
|
||||
empty_cleaned += 1
|
||||
empty_cleaned = 0 if dry_run else _remove_empty_dirs(bios_dir)
|
||||
|
||||
prefix = "Would remove" if dry_run else "Removed"
|
||||
print(f"\n{prefix}: {total_removed} files")
|
||||
@@ -305,29 +351,7 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict:
|
||||
print(f"Cleaned {empty_cleaned} empty directories")
|
||||
|
||||
if mame_clones:
|
||||
# A group is only visible while both copies are on disk, and this run
|
||||
# has just deleted the clone. Writing only what was seen this time
|
||||
# therefore erases every mapping an earlier run recorded, and the
|
||||
# canonical zip stops answering to the names it stands in for. The
|
||||
# older entries stay valid: their canonical file is still here.
|
||||
if not dry_run:
|
||||
if isinstance(previous, dict):
|
||||
merged = dict(previous)
|
||||
merged.update(mame_clones)
|
||||
mame_clones = collapse_clone_chains(merged)
|
||||
if dry_run:
|
||||
print(f"\nWould write MAME clone map: {clone_path}")
|
||||
print(
|
||||
f" {len(mame_clones)} canonical ZIPs with "
|
||||
f"{sum(len(v['clones']) for v in mame_clones.values())} clones"
|
||||
)
|
||||
else:
|
||||
write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True))
|
||||
print(f"\nWrote MAME clone map: {clone_path}")
|
||||
print(
|
||||
f" {len(mame_clones)} canonical ZIPs with "
|
||||
f"{sum(len(v['clones']) for v in mame_clones.values())} clones"
|
||||
)
|
||||
_record_clone_map(mame_clones, previous, clone_path, dry_run)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
+74
-36
@@ -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"}
|
||||
@@ -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
|
||||
|
||||
+261
-240
@@ -16,6 +16,7 @@ import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
@@ -129,10 +130,52 @@ def _takes_primary(current: str, candidate: str) -> bool:
|
||||
return _emulator_tree(current) and not _emulator_tree(candidate)
|
||||
|
||||
|
||||
def _add_scanned(
|
||||
files: dict[str, dict],
|
||||
aliases: dict[str, list[dict]],
|
||||
filepath: Path,
|
||||
rel_path: str,
|
||||
size: int,
|
||||
hashes: dict,
|
||||
) -> None:
|
||||
"""Record a scanned file as its content's primary, or as an alias of it."""
|
||||
sha1 = hashes["sha1"]
|
||||
entry = {
|
||||
"path": rel_path,
|
||||
"name": _canonical_name(filepath),
|
||||
"size": size,
|
||||
**hashes,
|
||||
}
|
||||
if sha1 not in files:
|
||||
files[sha1] = entry
|
||||
elif _takes_primary(files[sha1]["path"], rel_path):
|
||||
aliases.setdefault(sha1, []).append(
|
||||
{"name": files[sha1]["name"], "path": files[sha1]["path"]}
|
||||
)
|
||||
files[sha1] = entry
|
||||
else:
|
||||
aliases.setdefault(sha1, []).append({"name": entry["name"], "path": rel_path})
|
||||
|
||||
|
||||
def _cached_hashes(cached: dict | None, mtime: float, size: int) -> dict | None:
|
||||
"""The cache's digests of a file that has not changed since."""
|
||||
if cached is None:
|
||||
return None
|
||||
fresh = cached.get("mtime") == mtime and cached.get("size") == size
|
||||
# Rebuilding the hash dict by hand dropped whichever digest the
|
||||
# list forgot, and the entry was then written back to the cache
|
||||
# without it, so the loss survived every later run. Requiring the
|
||||
# full set instead turns a partial cache entry into a miss, which
|
||||
# heals it.
|
||||
if fresh and all(name in cached for name in CACHED_HASHES):
|
||||
return {name: cached[name] for name in CACHED_HASHES}
|
||||
return None
|
||||
|
||||
|
||||
def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict, dict]:
|
||||
"""Scan bios directory and compute hashes, using cache when possible."""
|
||||
files = {}
|
||||
aliases = {}
|
||||
files: dict[str, dict] = {}
|
||||
aliases: dict[str, list[dict]] = {}
|
||||
new_cache = {}
|
||||
|
||||
for filepath in sorted(bios_dir.rglob("*")):
|
||||
@@ -147,76 +190,10 @@ def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict,
|
||||
size = stat.st_size
|
||||
cache_key = rel_path
|
||||
|
||||
if not force and cache_key in cache:
|
||||
cached = cache[cache_key]
|
||||
fresh = cached.get("mtime") == mtime and cached.get("size") == size
|
||||
# Rebuilding the hash dict by hand dropped whichever digest the
|
||||
# list forgot, and the entry was then written back to the cache
|
||||
# without it, so the loss survived every later run. Requiring the
|
||||
# full set instead turns a partial cache entry into a miss, which
|
||||
# heals it.
|
||||
if fresh and all(name in cached for name in CACHED_HASHES):
|
||||
hashes = {name: cached[name] for name in CACHED_HASHES}
|
||||
sha1 = hashes["sha1"]
|
||||
if sha1 in files:
|
||||
if _takes_primary(files[sha1]["path"], rel_path):
|
||||
if sha1 not in aliases:
|
||||
aliases[sha1] = []
|
||||
aliases[sha1].append(
|
||||
{"name": files[sha1]["name"], "path": files[sha1]["path"]}
|
||||
)
|
||||
files[sha1] = {
|
||||
"path": rel_path,
|
||||
"name": _canonical_name(filepath),
|
||||
"size": size,
|
||||
**hashes,
|
||||
}
|
||||
else:
|
||||
if sha1 not in aliases:
|
||||
aliases[sha1] = []
|
||||
aliases[sha1].append(
|
||||
{"name": _canonical_name(filepath), "path": rel_path}
|
||||
)
|
||||
else:
|
||||
entry = {
|
||||
"path": rel_path,
|
||||
"name": _canonical_name(filepath),
|
||||
"size": size,
|
||||
**hashes,
|
||||
}
|
||||
files[sha1] = entry
|
||||
new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size}
|
||||
continue
|
||||
|
||||
hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size)
|
||||
sha1 = hashes["sha1"]
|
||||
if sha1 in files:
|
||||
if _takes_primary(files[sha1]["path"], rel_path):
|
||||
if sha1 not in aliases:
|
||||
aliases[sha1] = []
|
||||
aliases[sha1].append(
|
||||
{"name": files[sha1]["name"], "path": files[sha1]["path"]}
|
||||
)
|
||||
files[sha1] = {
|
||||
"path": rel_path,
|
||||
"name": _canonical_name(filepath),
|
||||
"size": size,
|
||||
**hashes,
|
||||
}
|
||||
else:
|
||||
if sha1 not in aliases:
|
||||
aliases[sha1] = []
|
||||
aliases[sha1].append(
|
||||
{"name": _canonical_name(filepath), "path": rel_path}
|
||||
)
|
||||
else:
|
||||
entry = {
|
||||
"path": rel_path,
|
||||
"name": _canonical_name(filepath),
|
||||
"size": size,
|
||||
**hashes,
|
||||
}
|
||||
files[sha1] = entry
|
||||
hashes = None if force else _cached_hashes(cache.get(cache_key), mtime, size)
|
||||
if hashes is None:
|
||||
hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size)
|
||||
_add_scanned(files, aliases, filepath, rel_path, size, hashes)
|
||||
new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size}
|
||||
|
||||
return files, aliases, new_cache
|
||||
@@ -244,11 +221,11 @@ def _path_suffixes(rel_path: str) -> list[str]:
|
||||
|
||||
def build_indexes(files: dict, aliases: dict) -> dict:
|
||||
"""Build secondary indexes for fast lookup."""
|
||||
by_md5 = {}
|
||||
by_name = {}
|
||||
by_crc32 = {}
|
||||
by_sha256 = {}
|
||||
by_path_suffix = {}
|
||||
by_md5: dict[str, str] = {}
|
||||
by_name: dict[str, list[str]] = {}
|
||||
by_crc32: dict[str, str] = {}
|
||||
by_sha256: dict[str, str] = {}
|
||||
by_path_suffix: dict[str, list[str]] = {}
|
||||
|
||||
for sha1, entry in files.items():
|
||||
by_md5[entry["md5"]] = sha1
|
||||
@@ -624,25 +601,38 @@ class UnreadableSource(Exception):
|
||||
self.sources = sources
|
||||
|
||||
|
||||
def _collect_all_aliases(
|
||||
files: dict,
|
||||
copies: dict | None = None,
|
||||
shadowed: list[tuple[str, set[str], list[str]]] | None = None,
|
||||
) -> dict:
|
||||
"""Collect alternate filenames from platform YAMLs, core-info, and known aliases.
|
||||
@dataclass
|
||||
class _AliasBook:
|
||||
"""The alternate names collected so far, and what designates a content."""
|
||||
|
||||
Registers alternate names so generate_pack can resolve files stored under different names.
|
||||
``copies`` maps a sha1 to the other files the scan found with that content.
|
||||
``shadowed`` receives, per profile entry, its name, the contents its hashes
|
||||
designate and the aliases a primary's name already carries.
|
||||
"""
|
||||
files: dict
|
||||
md5_to_sha1: dict[str, str]
|
||||
name_to_sha1: dict[str, str]
|
||||
# The contents held under each name, every copy counted.
|
||||
holders: dict[str, set[str]]
|
||||
# The files a name designates once case is folded.
|
||||
families: dict[str, set[str]]
|
||||
# A name only .variants/ copies carry is not a primary's.
|
||||
named_primaries: set[str]
|
||||
aliases: dict[str, list[dict]] = field(default_factory=dict)
|
||||
|
||||
def add(self, name: str, matched_sha1: str) -> None:
|
||||
if not name or name in self.named_primaries:
|
||||
return
|
||||
if matched_sha1 not in self.aliases:
|
||||
self.aliases[matched_sha1] = []
|
||||
existing = {a["name"] for a in self.aliases[matched_sha1]}
|
||||
if name not in existing:
|
||||
self.aliases[matched_sha1].append({"name": name, "path": ""})
|
||||
|
||||
|
||||
def _alias_book(files: dict, copies: dict | None) -> _AliasBook:
|
||||
"""Index the scanned files by md5, name and folded name."""
|
||||
md5_to_sha1 = {}
|
||||
name_to_sha1 = {}
|
||||
name_count: dict[str, int] = {}
|
||||
for sha1, entry in files.items():
|
||||
md5_to_sha1[entry["md5"]] = sha1
|
||||
name_to_sha1[entry["name"]] = sha1
|
||||
name_count[entry["name"]] = name_count.get(entry["name"], 0) + 1
|
||||
# The contents held under each name, every copy counted and not only the
|
||||
# primary: which copy of identical bytes is primary follows path order.
|
||||
# Keyed on primaries alone, project64's 64DD_IPL_v12_JPN.bin stopped
|
||||
@@ -670,8 +660,6 @@ def _collect_all_aliases(
|
||||
for copy in copy_list:
|
||||
_hold(copy["name"], copy["path"], sha1)
|
||||
|
||||
aliases = {}
|
||||
|
||||
# A name only .variants/ copies carry is not a primary's: those copies are
|
||||
# the other revisions of whatever the name designates. Retroarch pins
|
||||
# bios_E.sms to v1.3, and with the name refused, Genesis Plus GX got the
|
||||
@@ -679,177 +667,210 @@ def _collect_all_aliases(
|
||||
named_primaries = {
|
||||
entry["name"] for entry in files.values() if "/.variants/" not in entry["path"]
|
||||
}
|
||||
return _AliasBook(files, md5_to_sha1, name_to_sha1, holders, families, named_primaries)
|
||||
|
||||
def _add_alias(name: str, matched_sha1: str) -> None:
|
||||
if not name or name in named_primaries:
|
||||
return
|
||||
if matched_sha1 not in aliases:
|
||||
aliases[matched_sha1] = []
|
||||
existing = {a["name"] for a in aliases[matched_sha1]}
|
||||
if name not in existing:
|
||||
aliases[matched_sha1].append({"name": name, "path": ""})
|
||||
|
||||
def _platform_aliases(book: _AliasBook, unreadable: list[str]) -> None:
|
||||
"""Register the names platform YAMLs give a held content."""
|
||||
platforms_dir = Path("platforms")
|
||||
if not platforms_dir.is_dir():
|
||||
return
|
||||
for platform_name in list_registered_platforms(
|
||||
str(platforms_dir)
|
||||
):
|
||||
config_file = platforms_dir / f"{platform_name}.yml"
|
||||
try:
|
||||
with open(config_file) as f:
|
||||
config = yaml_load(f) or {}
|
||||
except (yaml.YAMLError, OSError) as e:
|
||||
unreadable.append(f"{config_file}: {e}")
|
||||
continue
|
||||
|
||||
for system in config.get("systems", {}).values():
|
||||
for file_entry in system.get("files", []):
|
||||
name = file_entry.get("name", "")
|
||||
sha1 = file_entry.get("sha1", "")
|
||||
md5 = file_entry.get("md5", "")
|
||||
|
||||
# A zipped_file entry verifies a ROM INSIDE the
|
||||
# archive, so its hash describes the member and not
|
||||
# the file the name designates. Registering the name
|
||||
# against that hash made d2fdc.zip an alias of a
|
||||
# loose 256-byte state-machine-16.rom, which three
|
||||
# platforms were then served in place of the archive.
|
||||
if file_entry.get("zipped_file"):
|
||||
continue
|
||||
|
||||
matched = None
|
||||
if sha1 and sha1 in book.files:
|
||||
matched = sha1
|
||||
elif md5 and md5 in book.md5_to_sha1:
|
||||
matched = book.md5_to_sha1[md5]
|
||||
|
||||
if matched:
|
||||
book.add(name, matched)
|
||||
|
||||
|
||||
def _profile_entry_aliases(
|
||||
book: _AliasBook,
|
||||
file_entry: dict,
|
||||
primary_names: set[str],
|
||||
shadowed: list[tuple[str, set[str], list[str]]] | None,
|
||||
) -> None:
|
||||
"""Register the aliases one profile entry gives the contents it designates."""
|
||||
entry_name = file_entry.get("name", "")
|
||||
entry_aliases = _own_aliases(file_entry, primary_names)
|
||||
# A profile may accept several revisions: each held one
|
||||
# is designated by the entry, none of them by guess.
|
||||
matched: set[str] = {
|
||||
value for value in _as_list(file_entry.get("sha1"))
|
||||
if value in book.files
|
||||
}
|
||||
matched |= {
|
||||
book.md5_to_sha1[value]
|
||||
for value in _as_list(file_entry.get("md5"))
|
||||
if value in book.md5_to_sha1
|
||||
}
|
||||
if matched:
|
||||
# Proven by content, the profile's own name designates
|
||||
# the file whatever the collection calls it.
|
||||
entry_aliases.insert(0, entry_name)
|
||||
if not entry_aliases:
|
||||
return
|
||||
if shadowed is not None:
|
||||
taken = [
|
||||
alias for alias in entry_aliases
|
||||
if alias != entry_name and alias in book.named_primaries
|
||||
]
|
||||
if taken:
|
||||
shadowed.append((entry_name, set(matched), taken))
|
||||
held = book.holders.get(entry_name, set())
|
||||
if (
|
||||
not matched
|
||||
and len(held) == 1
|
||||
and len(book.families[entry_name.casefold()]) == 1
|
||||
):
|
||||
# A name carried by several contents names none of them:
|
||||
# quasi88's disk.rom aliases went to whichever
|
||||
# disk.rom the scan met last, a Tandy CoCo ROM.
|
||||
matched = set(held)
|
||||
for sha in sorted(matched):
|
||||
for alias_name in entry_aliases:
|
||||
book.add(alias_name, sha)
|
||||
|
||||
|
||||
def _profile_aliases(
|
||||
book: _AliasBook,
|
||||
shadowed: list[tuple[str, set[str], list[str]]] | None,
|
||||
unreadable: list[str],
|
||||
) -> None:
|
||||
"""Register the aliases emulator YAMLs give (aliases field on file entries)."""
|
||||
emulators_dir = Path("emulators")
|
||||
if not emulators_dir.is_dir():
|
||||
return
|
||||
for emu_file in source_yaml_paths(emulators_dir):
|
||||
try:
|
||||
with open(emu_file) as f:
|
||||
emu_config = yaml_load(f) or {}
|
||||
except (yaml.YAMLError, OSError) as e:
|
||||
unreadable.append(f"{emu_file}: {e}")
|
||||
continue
|
||||
# A profile whose entries name each other (dosbox-x opens
|
||||
# MT32_CONTROL.ROM and CM32L_CONTROL.ROM alike, so each entry
|
||||
# aliases the other) states that ITS slot takes either name.
|
||||
# Indexed globally that became evidence for every emulator:
|
||||
# ScummVM's MT-32 slot received the CM-32L ROMs.
|
||||
primary_names = _primary_names(emu_config.get("files", []))
|
||||
for file_entry in emu_config.get("files", []):
|
||||
_profile_entry_aliases(book, file_entry, primary_names, shadowed)
|
||||
|
||||
|
||||
# Identical content named differently across platforms/cores
|
||||
KNOWN_ALIAS_GROUPS = [
|
||||
# ColecoVision - all these are the same 8KB BIOS
|
||||
["colecovision.rom", "coleco.rom", "BIOS.col", "bioscv.rom"],
|
||||
# Game Boy - DMG boot ROM
|
||||
["gb_bios.bin", "dmg_boot.bin", "dmg_rom.bin", "dmg0_rom.bin"],
|
||||
# Game Boy Color - CGB boot ROM
|
||||
["gbc_bios.bin", "cgb_boot.bin", "cgb0_boot.bin", "cgb_agb_boot.bin"],
|
||||
# Super Game Boy
|
||||
["sgb_bios.bin", "sgb_boot.bin", "sgb.boot.rom"],
|
||||
["sgb2_bios.bin", "sgb2_boot.bin", "sgb2.boot.rom"],
|
||||
["sgb1.program.rom", "SGB1.sfc/program.rom"],
|
||||
["sgb2.program.rom", "SGB2.sfc/program.rom"],
|
||||
# Nintendo DS. DraStic opens nds_bios_arm9.bin, nds_bios_arm7.bin
|
||||
# and nds_firmware.bin and checks their size only: the collection
|
||||
# answers those names with its DS dumps.
|
||||
["NDS_Bios7.bin", "bios7.bin", "nds7.bin", "nds_bios_arm7.bin"],
|
||||
["NDS_Bios9.bin", "bios9.bin", "nds9.bin", "nds_bios_arm9.bin"],
|
||||
["NDS_Lite_Firmware.bin", "nds_firmware.bin"],
|
||||
["dsi_sd_card.bin", "nds_sd_card.bin"],
|
||||
# MSX
|
||||
["MSX.ROM", "MSX.rom", "Machines/Shared Roms/MSX.rom"],
|
||||
# NEC PC-98
|
||||
["N88KNJ1.ROM", "n88knj1.rom", "quasi88/n88knj1.rom"],
|
||||
# Enterprise
|
||||
["zt19uk.rom", "zt19hfnt.rom", "ep128emu/roms/zt19hfnt.rom"],
|
||||
# ZX Spectrum
|
||||
["48.rom", "zx48.rom"],
|
||||
# SquirrelJME - all JARs are the same
|
||||
[
|
||||
"squirreljme.sqc",
|
||||
"squirreljme.jar",
|
||||
"squirreljme-fast.jar",
|
||||
"squirreljme-slow.jar",
|
||||
"squirreljme-slow-test.jar",
|
||||
"squirreljme-0.3.0.jar",
|
||||
"squirreljme-0.3.0-fast.jar",
|
||||
"squirreljme-0.3.0-slow.jar",
|
||||
"squirreljme-0.3.0-slow-test.jar",
|
||||
],
|
||||
# Arcade - FBNeo spectrum
|
||||
["spectrum.zip", "fbneo/spectrum.zip", "spec48k.zip"],
|
||||
]
|
||||
|
||||
|
||||
def _collect_all_aliases(
|
||||
files: dict,
|
||||
copies: dict | None = None,
|
||||
shadowed: list[tuple[str, set[str], list[str]]] | None = None,
|
||||
) -> dict:
|
||||
"""Collect alternate filenames from platform YAMLs, core-info, and known aliases.
|
||||
|
||||
Registers alternate names so generate_pack can resolve files stored under different names.
|
||||
``copies`` maps a sha1 to the other files the scan found with that content.
|
||||
``shadowed`` receives, per profile entry, its name, the contents its hashes
|
||||
designate and the aliases a primary's name already carries.
|
||||
"""
|
||||
book = _alias_book(files, copies)
|
||||
|
||||
# A source that does not parse is reported and the run refused: written
|
||||
# without it, the database lost every alias the file proves and the
|
||||
# command exited 0 (dosbox-x's wqy fonts answered not_found).
|
||||
unreadable: list[str] = []
|
||||
platforms_dir = Path("platforms")
|
||||
if platforms_dir.is_dir():
|
||||
for platform_name in list_registered_platforms(
|
||||
str(platforms_dir)
|
||||
):
|
||||
config_file = platforms_dir / f"{platform_name}.yml"
|
||||
try:
|
||||
with open(config_file) as f:
|
||||
config = yaml_load(f) or {}
|
||||
except (yaml.YAMLError, OSError) as e:
|
||||
unreadable.append(f"{config_file}: {e}")
|
||||
continue
|
||||
|
||||
for sys_id, system in config.get("systems", {}).items():
|
||||
for file_entry in system.get("files", []):
|
||||
name = file_entry.get("name", "")
|
||||
sha1 = file_entry.get("sha1", "")
|
||||
md5 = file_entry.get("md5", "")
|
||||
|
||||
# A zipped_file entry verifies a ROM INSIDE the
|
||||
# archive, so its hash describes the member and not
|
||||
# the file the name designates. Registering the name
|
||||
# against that hash made d2fdc.zip an alias of a
|
||||
# loose 256-byte state-machine-16.rom, which three
|
||||
# platforms were then served in place of the archive.
|
||||
if file_entry.get("zipped_file"):
|
||||
continue
|
||||
|
||||
matched = None
|
||||
if sha1 and sha1 in files:
|
||||
matched = sha1
|
||||
elif md5 and md5 in md5_to_sha1:
|
||||
matched = md5_to_sha1[md5]
|
||||
|
||||
if matched:
|
||||
_add_alias(name, matched)
|
||||
_platform_aliases(book, unreadable)
|
||||
|
||||
# core-info is not read here: it was the only network call of a build
|
||||
# that must give the same database offline, and the one name it added
|
||||
# (gearcoleco's writer.rom) is a profile entry proven by its sha1, which
|
||||
# the profile pass below now registers.
|
||||
|
||||
# Collect aliases from emulator YAMLs (aliases field on file entries)
|
||||
emulators_dir = Path("emulators")
|
||||
if emulators_dir.is_dir():
|
||||
for emu_file in source_yaml_paths(emulators_dir):
|
||||
try:
|
||||
with open(emu_file) as f:
|
||||
emu_config = yaml_load(f) or {}
|
||||
except (yaml.YAMLError, OSError) as e:
|
||||
unreadable.append(f"{emu_file}: {e}")
|
||||
continue
|
||||
# A profile whose entries name each other (dosbox-x opens
|
||||
# MT32_CONTROL.ROM and CM32L_CONTROL.ROM alike, so each entry
|
||||
# aliases the other) states that ITS slot takes either name.
|
||||
# Indexed globally that became evidence for every emulator:
|
||||
# ScummVM's MT-32 slot received the CM-32L ROMs.
|
||||
primary_names = _primary_names(emu_config.get("files", []))
|
||||
for file_entry in emu_config.get("files", []):
|
||||
entry_name = file_entry.get("name", "")
|
||||
entry_aliases = _own_aliases(file_entry, primary_names)
|
||||
# A profile may accept several revisions: each held one
|
||||
# is designated by the entry, none of them by guess.
|
||||
matched: set[str] = {
|
||||
value for value in _as_list(file_entry.get("sha1"))
|
||||
if value in files
|
||||
}
|
||||
matched |= {
|
||||
md5_to_sha1[value]
|
||||
for value in _as_list(file_entry.get("md5"))
|
||||
if value in md5_to_sha1
|
||||
}
|
||||
if matched:
|
||||
# Proven by content, the profile's own name designates
|
||||
# the file whatever the collection calls it.
|
||||
entry_aliases.insert(0, entry_name)
|
||||
if not entry_aliases:
|
||||
continue
|
||||
if shadowed is not None:
|
||||
taken = [
|
||||
alias for alias in entry_aliases
|
||||
if alias != entry_name and alias in named_primaries
|
||||
]
|
||||
if taken:
|
||||
shadowed.append((entry_name, set(matched), taken))
|
||||
held = holders.get(entry_name, set())
|
||||
if (
|
||||
not matched
|
||||
and len(held) == 1
|
||||
and len(families[entry_name.casefold()]) == 1
|
||||
):
|
||||
# A name carried by several contents names none of them:
|
||||
# quasi88's disk.rom aliases went to whichever
|
||||
# disk.rom the scan met last, a Tandy CoCo ROM.
|
||||
matched = set(held)
|
||||
for sha in sorted(matched):
|
||||
for alias_name in entry_aliases:
|
||||
_add_alias(alias_name, sha)
|
||||
|
||||
# Identical content named differently across platforms/cores
|
||||
KNOWN_ALIAS_GROUPS = [
|
||||
# ColecoVision - all these are the same 8KB BIOS
|
||||
["colecovision.rom", "coleco.rom", "BIOS.col", "bioscv.rom"],
|
||||
# Game Boy - DMG boot ROM
|
||||
["gb_bios.bin", "dmg_boot.bin", "dmg_rom.bin", "dmg0_rom.bin"],
|
||||
# Game Boy Color - CGB boot ROM
|
||||
["gbc_bios.bin", "cgb_boot.bin", "cgb0_boot.bin", "cgb_agb_boot.bin"],
|
||||
# Super Game Boy
|
||||
["sgb_bios.bin", "sgb_boot.bin", "sgb.boot.rom"],
|
||||
["sgb2_bios.bin", "sgb2_boot.bin", "sgb2.boot.rom"],
|
||||
["sgb1.program.rom", "SGB1.sfc/program.rom"],
|
||||
["sgb2.program.rom", "SGB2.sfc/program.rom"],
|
||||
# Nintendo DS. DraStic opens nds_bios_arm9.bin, nds_bios_arm7.bin
|
||||
# and nds_firmware.bin and checks their size only: the collection
|
||||
# answers those names with its DS dumps.
|
||||
["NDS_Bios7.bin", "bios7.bin", "nds7.bin", "nds_bios_arm7.bin"],
|
||||
["NDS_Bios9.bin", "bios9.bin", "nds9.bin", "nds_bios_arm9.bin"],
|
||||
["NDS_Lite_Firmware.bin", "nds_firmware.bin"],
|
||||
["dsi_sd_card.bin", "nds_sd_card.bin"],
|
||||
# MSX
|
||||
["MSX.ROM", "MSX.rom", "Machines/Shared Roms/MSX.rom"],
|
||||
# NEC PC-98
|
||||
["N88KNJ1.ROM", "n88knj1.rom", "quasi88/n88knj1.rom"],
|
||||
# Enterprise
|
||||
["zt19uk.rom", "zt19hfnt.rom", "ep128emu/roms/zt19hfnt.rom"],
|
||||
# ZX Spectrum
|
||||
["48.rom", "zx48.rom"],
|
||||
# SquirrelJME - all JARs are the same
|
||||
[
|
||||
"squirreljme.sqc",
|
||||
"squirreljme.jar",
|
||||
"squirreljme-fast.jar",
|
||||
"squirreljme-slow.jar",
|
||||
"squirreljme-slow-test.jar",
|
||||
"squirreljme-0.3.0.jar",
|
||||
"squirreljme-0.3.0-fast.jar",
|
||||
"squirreljme-0.3.0-slow.jar",
|
||||
"squirreljme-0.3.0-slow-test.jar",
|
||||
],
|
||||
# Arcade - FBNeo spectrum
|
||||
["spectrum.zip", "fbneo/spectrum.zip", "spec48k.zip"],
|
||||
]
|
||||
_profile_aliases(book, shadowed, unreadable)
|
||||
|
||||
for group in KNOWN_ALIAS_GROUPS:
|
||||
matched_sha1 = None
|
||||
for name in group:
|
||||
if name in name_to_sha1:
|
||||
matched_sha1 = name_to_sha1[name]
|
||||
if name in book.name_to_sha1:
|
||||
matched_sha1 = book.name_to_sha1[name]
|
||||
break
|
||||
if not matched_sha1:
|
||||
continue
|
||||
for name in group:
|
||||
_add_alias(name, matched_sha1)
|
||||
book.add(name, matched_sha1)
|
||||
|
||||
if unreadable:
|
||||
raise UnreadableSource(unreadable)
|
||||
return aliases
|
||||
return book.aliases
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+6
-6
@@ -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
@@ -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):
|
||||
|
||||
+192
-97
@@ -58,6 +58,7 @@ import tempfile
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
# The build scripts need CPython 3.9, which builds the same database,
|
||||
# manifests and packs as 3.12.
|
||||
@@ -80,6 +81,9 @@ from common import (
|
||||
from refresh_data_dirs import hold_data_dirs
|
||||
from packpaths import MEDIA_MARKER
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from generate_pack import PackRecord
|
||||
|
||||
|
||||
class StepResults(dict):
|
||||
"""The outcome of each step, and how long it took.
|
||||
@@ -195,7 +199,7 @@ def run(cmd: list[str], label: str) -> tuple[bool, str]:
|
||||
cwd=repo_root,
|
||||
env={**os.environ, "PYTHONUNBUFFERED": "1", "NODE_DISABLE_COMPILE_CACHE": "1"},
|
||||
) as proc:
|
||||
for line in proc.stdout:
|
||||
for line in proc.stdout or ():
|
||||
lines.append(line)
|
||||
print(line, end="", flush=True)
|
||||
returncode = proc.wait()
|
||||
@@ -378,15 +382,19 @@ def check_consistency(
|
||||
p_match = p_label
|
||||
break
|
||||
|
||||
if p_match and p_match in pack_extras and v_label in verify_extras:
|
||||
if verify_extras[v_label] != pack_extras[p_match]:
|
||||
# The cores' share: the base check passed RomM while verify
|
||||
# counted 412 core files and game data and the pack held 60.
|
||||
print(
|
||||
f" {v_label}: MISMATCH core files verify "
|
||||
f"{verify_extras[v_label]} != pack {pack_extras[p_match]}"
|
||||
)
|
||||
all_ok = False
|
||||
if (
|
||||
p_match
|
||||
and p_match in pack_extras
|
||||
and v_label in verify_extras
|
||||
and verify_extras[v_label] != pack_extras[p_match]
|
||||
):
|
||||
# The cores' share: the base check passed RomM while verify
|
||||
# counted 412 core files and game data and the pack held 60.
|
||||
print(
|
||||
f" {v_label}: MISMATCH core files verify "
|
||||
f"{verify_extras[v_label]} != pack {pack_extras[p_match]}"
|
||||
)
|
||||
all_ok = False
|
||||
if p_match:
|
||||
p_ok, p_total = p[p_match]
|
||||
p_excluded = excluded.get(p_match, 0)
|
||||
@@ -596,8 +604,9 @@ def check_emulator_packs(
|
||||
with contextlib.redirect_stdout(io.StringIO()), \
|
||||
contextlib.redirect_stderr(io.StringIO()):
|
||||
generate_pack.generate_emulator_pack(
|
||||
names, emulators_dir, db, "bios", "", standalone, zip_contents,
|
||||
offline=True, platforms_dir=platforms_dir, record=record, **narrowing,
|
||||
names, emulators_dir, db, "bios", "", standalone,
|
||||
zip_contents=zip_contents, offline=True, platforms_dir=platforms_dir,
|
||||
record=record, **narrowing,
|
||||
)
|
||||
report = verify.verify_emulator(
|
||||
names, emulators_dir, db, standalone, platforms_dir=platforms_dir,
|
||||
@@ -817,7 +826,7 @@ def check_narrowed_packs(
|
||||
|
||||
|
||||
def split_differences(
|
||||
full: object, parts: dict[str, object], same_bytes: Callable[[str, str], bool],
|
||||
full: PackRecord, parts: dict[str, PackRecord], same_bytes: Callable[[str, str], bool],
|
||||
) -> list[str]:
|
||||
"""Where the --split parts of a pack, together, are not the full pack.
|
||||
|
||||
@@ -1074,7 +1083,7 @@ def _truth_steps(args: argparse.Namespace, results: dict) -> bool:
|
||||
return all_ok
|
||||
|
||||
|
||||
def main() -> None:
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(allow_abbrev=False, description="Run the full retrobios pipeline")
|
||||
parser.add_argument(
|
||||
"--skip-packs",
|
||||
@@ -1128,45 +1137,12 @@ def main() -> None:
|
||||
action="store_true",
|
||||
help="Export native formats (implies --with-truth)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
_refuse_unapplied_flags(parser, args)
|
||||
_refuse_offline_without_caches(parser, args)
|
||||
_refuse_offline_export_without_originals(parser, args)
|
||||
if not args.offline:
|
||||
# Read once and put in the environment every step inherits: the
|
||||
# scrapers and refresh_data_dirs went anonymous unless the user had
|
||||
# exported GITHUB_TOKEN by hand, though gh was logged in.
|
||||
github_token()
|
||||
args.output_dir = _output_dir(args.output_dir)
|
||||
return parser
|
||||
|
||||
# A second run on the same output directory is refused before any work:
|
||||
# the database rebuild alone takes minutes, and the reader holding the
|
||||
# directory would otherwise see the answer only after all of it. The
|
||||
# hold lasts until this process exits: taken step by step, it let another
|
||||
# run purge the packs between the build and the integrity check, which
|
||||
# then reported every platform SKIP and passed.
|
||||
# database.json, install/, README.md, CONTRIBUTING.md and website/ sit at
|
||||
# fixed paths (artifacts.REPOSITORY_OUTPUTS), so
|
||||
# every run holds them too: a run on a scratch --output-dir otherwise
|
||||
# rewrote them beside the run on dist/.
|
||||
held = contextlib.ExitStack()
|
||||
try:
|
||||
root = str(Path(__file__).resolve().parent.parent)
|
||||
held.enter_context(hold_repository_outputs(root))
|
||||
# Its steps write database.json, install/ and README.md themselves,
|
||||
# and take the same lock to do so.
|
||||
held.enter_context(publish_hold(root))
|
||||
if not args.skip_packs:
|
||||
held.enter_context(hold_artifact_lock(args.output_dir))
|
||||
except ArtifactLockBusy as exc:
|
||||
held.close()
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
def _database_steps(results: dict) -> bool:
|
||||
"""Steps 0 to 1c: schemas, database, dump catalogs, romset recipes."""
|
||||
all_ok = True
|
||||
total_start = time.monotonic()
|
||||
results = StepResults(total_start)
|
||||
|
||||
# Step 0: the schema check PR validation runs. Without it a profile with
|
||||
# `cores: [81]` unquoted passed the whole pipeline and failed CI on push.
|
||||
# jsonschema is tooling only, so its absence skips the step.
|
||||
@@ -1188,7 +1164,7 @@ def main() -> None:
|
||||
all_ok = all_ok and ok
|
||||
|
||||
# Step 1: Generate database
|
||||
ok, out = run(
|
||||
ok, _ = run(
|
||||
[
|
||||
sys.executable,
|
||||
"scripts/generate_db.py",
|
||||
@@ -1219,7 +1195,7 @@ def main() -> None:
|
||||
# Step 1c: Which emulator version each arcade archive corresponds to, and
|
||||
# which pinned archive the collection could rebuild from ROMs it holds.
|
||||
# Read-only: writing reconstructions is an explicit --write invocation.
|
||||
ok, out = run(
|
||||
ok, _ = run(
|
||||
[sys.executable, "scripts/romset_recipes.py"],
|
||||
STEP_LABELS["romset_recipes"],
|
||||
)
|
||||
@@ -1233,10 +1209,15 @@ def main() -> None:
|
||||
ok = ok and captured
|
||||
results["romset_recipes"] = ok
|
||||
all_ok = all_ok and ok
|
||||
return all_ok
|
||||
|
||||
|
||||
def _refresh_steps(args: argparse.Namespace, results: dict) -> bool:
|
||||
"""Steps 2 to 2b2: data directories, hash scrapers, release assets."""
|
||||
all_ok = True
|
||||
# Step 2: Refresh data directories
|
||||
if not args.offline:
|
||||
ok, out = run(
|
||||
ok, _ = run(
|
||||
[sys.executable, "scripts/refresh_data_dirs.py"],
|
||||
STEP_LABELS["refresh_data"],
|
||||
)
|
||||
@@ -1295,9 +1276,18 @@ def main() -> None:
|
||||
else:
|
||||
skip_notice("check_release_assets", "--offline")
|
||||
results["check_release_assets"] = SKIPPED
|
||||
return all_ok
|
||||
|
||||
all_ok = _truth_steps(args, results) and all_ok
|
||||
|
||||
def _verify_steps(
|
||||
args: argparse.Namespace, results: dict, held: contextlib.ExitStack
|
||||
) -> tuple[bool, str, str]:
|
||||
"""Steps 3 to 3b: verify, identities, slots.
|
||||
|
||||
Returns whether they passed, verify's output and the file of the paths
|
||||
each pack holds by its report.
|
||||
"""
|
||||
all_ok = True
|
||||
# Every step from here reads the data directory trees: verify, the packs,
|
||||
# the manifests and the integrity check. Held shared until the run ends,
|
||||
# a refresh from another session waits instead of swapping a tree
|
||||
@@ -1352,52 +1342,70 @@ def main() -> None:
|
||||
ok, _ = run(slots_cmd, "3b slot arbitration")
|
||||
results["slots"] = ok
|
||||
all_ok &= ok
|
||||
return all_ok, verify_output, destinations_file
|
||||
|
||||
|
||||
def _purge_stale_packs(output_dir: str) -> None:
|
||||
"""Remove the packs of earlier builds from the output directory."""
|
||||
# Purge stale packs: leftover ZIPs from previous builds would be
|
||||
# picked up by pack verification and shipped in releases.
|
||||
out_dir = Path(output_dir)
|
||||
if not out_dir.is_dir():
|
||||
return
|
||||
try:
|
||||
with artifact_lock(str(out_dir)):
|
||||
stale = [
|
||||
p for p in out_dir.iterdir()
|
||||
if p.is_file() and (
|
||||
p.suffix == ".zip"
|
||||
or ".zip." in p.name
|
||||
or p.name == "SHA256SUMS.txt"
|
||||
)
|
||||
]
|
||||
for p in stale:
|
||||
p.unlink()
|
||||
if stale:
|
||||
print(f"Purged {len(stale)} stale pack file(s) from {out_dir}/")
|
||||
except ArtifactLockBusy as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _pack_command(args: argparse.Namespace) -> list[str]:
|
||||
"""The step 4 command: every platform's pack."""
|
||||
pack_cmd = [
|
||||
sys.executable,
|
||||
"scripts/generate_pack.py",
|
||||
"--all",
|
||||
"--output-dir",
|
||||
args.output_dir,
|
||||
]
|
||||
if args.offline:
|
||||
pack_cmd.append("--offline")
|
||||
else:
|
||||
# Step 2 refreshed the trees once: refreshing again here let the
|
||||
# pack and the manifest describe two revisions of a moving tree.
|
||||
pack_cmd.append("--no-refresh-data")
|
||||
if args.target:
|
||||
pack_cmd.extend(["--target", args.target])
|
||||
if args.source != "full":
|
||||
pack_cmd.extend(["--source", args.source])
|
||||
if args.all_variants:
|
||||
pack_cmd.append("--all-variants")
|
||||
return pack_cmd
|
||||
|
||||
|
||||
def _pack_steps(args: argparse.Namespace, results: dict) -> tuple[bool, str]:
|
||||
"""Steps 4 to 4c: packs, install manifests, target manifests.
|
||||
|
||||
Returns whether they passed and the pack build's output.
|
||||
"""
|
||||
all_ok = True
|
||||
# Step 4: Generate packs
|
||||
pack_output = ""
|
||||
if not args.skip_packs:
|
||||
# Purge stale packs: leftover ZIPs from previous builds would be
|
||||
# picked up by pack verification and shipped in releases.
|
||||
out_dir = Path(args.output_dir)
|
||||
if out_dir.is_dir():
|
||||
try:
|
||||
with artifact_lock(str(out_dir)):
|
||||
stale = [
|
||||
p for p in out_dir.iterdir()
|
||||
if p.is_file() and (
|
||||
p.suffix == ".zip"
|
||||
or ".zip." in p.name
|
||||
or p.name == "SHA256SUMS.txt"
|
||||
)
|
||||
]
|
||||
for p in stale:
|
||||
p.unlink()
|
||||
if stale:
|
||||
print(f"Purged {len(stale)} stale pack file(s) from {out_dir}/")
|
||||
except ArtifactLockBusy as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
pack_cmd = [
|
||||
sys.executable,
|
||||
"scripts/generate_pack.py",
|
||||
"--all",
|
||||
"--output-dir",
|
||||
args.output_dir,
|
||||
]
|
||||
if args.offline:
|
||||
pack_cmd.append("--offline")
|
||||
else:
|
||||
# Step 2 refreshed the trees once: refreshing again here let the
|
||||
# pack and the manifest describe two revisions of a moving tree.
|
||||
pack_cmd.append("--no-refresh-data")
|
||||
if args.target:
|
||||
pack_cmd.extend(["--target", args.target])
|
||||
if args.source != "full":
|
||||
pack_cmd.extend(["--source", args.source])
|
||||
if args.all_variants:
|
||||
pack_cmd.append("--all-variants")
|
||||
ok, pack_output = run(pack_cmd, STEP_LABELS["generate_packs"])
|
||||
_purge_stale_packs(args.output_dir)
|
||||
ok, pack_output = run(_pack_command(args), STEP_LABELS["generate_packs"])
|
||||
results["generate_packs"] = ok
|
||||
all_ok = all_ok and ok
|
||||
else:
|
||||
@@ -1445,7 +1453,12 @@ def main() -> None:
|
||||
else:
|
||||
skip_notice("generate_target_manifests", "--skip-packs")
|
||||
results["generate_target_manifests"] = SKIPPED
|
||||
return all_ok, pack_output
|
||||
|
||||
|
||||
def _index_steps(results: dict) -> bool:
|
||||
"""Steps 4d and 4e: bundled-only copies, the games index."""
|
||||
all_ok = True
|
||||
# Step 4d: A collected copy that only an emulator's own install provides.
|
||||
# Packs leave such files out, so a copy nothing else asks for is weight
|
||||
# the collection carries for nobody. Read after the manifests, which say
|
||||
@@ -1468,7 +1481,19 @@ def main() -> None:
|
||||
)
|
||||
results["games_index"] = ok
|
||||
all_ok &= ok
|
||||
return all_ok
|
||||
|
||||
|
||||
def _check_steps(
|
||||
args: argparse.Namespace,
|
||||
results: dict,
|
||||
*,
|
||||
pack_output: str,
|
||||
verify_output: str,
|
||||
destinations_file: str,
|
||||
) -> bool:
|
||||
"""Steps 5 and 6: verify against the packs, then the packs' integrity."""
|
||||
all_ok = True
|
||||
# Step 5: Consistency check. verify describes the full pack, and a run that
|
||||
# built only a reduced one (--source platform or truth) has nothing to
|
||||
# compare it with, and says so instead of failing on an empty parse.
|
||||
@@ -1509,7 +1534,12 @@ def main() -> None:
|
||||
else:
|
||||
skip_notice("pack_integrity", "--skip-packs")
|
||||
results["pack_integrity"] = SKIPPED
|
||||
return all_ok
|
||||
|
||||
|
||||
def _docs_steps(args: argparse.Namespace, results: dict) -> bool:
|
||||
"""Steps 7 to 8b: README and pages, site pages, the rendered site."""
|
||||
all_ok = True
|
||||
# Step 7: Generate README
|
||||
if not args.skip_docs:
|
||||
ok, _ = run(
|
||||
@@ -1565,8 +1595,11 @@ def main() -> None:
|
||||
"8b validate site")
|
||||
results["render_site"] = ok
|
||||
all_ok = all_ok and ok
|
||||
return all_ok
|
||||
|
||||
# Summary
|
||||
|
||||
def _print_summary(results: StepResults, total_start: float, all_ok: bool) -> None:
|
||||
"""The table of every step's outcome and duration, then the verdict."""
|
||||
total_elapsed = time.monotonic() - total_start
|
||||
print(f"\n{'=' * 60}")
|
||||
warned = []
|
||||
@@ -1590,10 +1623,72 @@ def main() -> None:
|
||||
if warned:
|
||||
print(f" {', '.join(warned)} reported a difference, which does not fail the run")
|
||||
print(f"{'=' * 60}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = _parser()
|
||||
args = parser.parse_args()
|
||||
_refuse_unapplied_flags(parser, args)
|
||||
_refuse_offline_without_caches(parser, args)
|
||||
_refuse_offline_export_without_originals(parser, args)
|
||||
if not args.offline:
|
||||
# Read once and put in the environment every step inherits: the
|
||||
# scrapers and refresh_data_dirs went anonymous unless the user had
|
||||
# exported GITHUB_TOKEN by hand, though gh was logged in.
|
||||
github_token()
|
||||
args.output_dir = _output_dir(args.output_dir)
|
||||
held = _hold_outputs(args)
|
||||
|
||||
total_start = time.monotonic()
|
||||
results = StepResults(total_start)
|
||||
|
||||
all_ok = _database_steps(results)
|
||||
all_ok = _refresh_steps(args, results) and all_ok
|
||||
all_ok = _truth_steps(args, results) and all_ok
|
||||
ok, verify_output, destinations_file = _verify_steps(args, results, held)
|
||||
all_ok = all_ok and ok
|
||||
ok, pack_output = _pack_steps(args, results)
|
||||
all_ok = all_ok and ok
|
||||
all_ok = _index_steps(results) and all_ok
|
||||
all_ok = _check_steps(
|
||||
args, results, pack_output=pack_output, verify_output=verify_output,
|
||||
destinations_file=destinations_file,
|
||||
) and all_ok
|
||||
all_ok = _docs_steps(args, results) and all_ok
|
||||
|
||||
_print_summary(results, total_start, all_ok)
|
||||
held.close()
|
||||
sys.exit(0 if all_ok else 1)
|
||||
|
||||
|
||||
def _hold_outputs(args: argparse.Namespace) -> contextlib.ExitStack:
|
||||
"""Take every lock the run holds until it exits, or exit when one is busy."""
|
||||
# A second run on the same output directory is refused before any work:
|
||||
# the database rebuild alone takes minutes, and the reader holding the
|
||||
# directory would otherwise see the answer only after all of it. The
|
||||
# hold lasts until this process exits: taken step by step, it let another
|
||||
# run purge the packs between the build and the integrity check, which
|
||||
# then reported every platform SKIP and passed.
|
||||
# database.json, install/, README.md, CONTRIBUTING.md and website/ sit at
|
||||
# fixed paths (artifacts.REPOSITORY_OUTPUTS), so
|
||||
# every run holds them too: a run on a scratch --output-dir otherwise
|
||||
# rewrote them beside the run on dist/.
|
||||
held = contextlib.ExitStack()
|
||||
try:
|
||||
root = str(Path(__file__).resolve().parent.parent)
|
||||
held.enter_context(hold_repository_outputs(root))
|
||||
# Its steps write database.json, install/ and README.md themselves,
|
||||
# and take the same lock to do so.
|
||||
held.enter_context(publish_hold(root))
|
||||
if not args.skip_packs:
|
||||
held.enter_context(hold_artifact_lock(args.output_dir))
|
||||
except ArtifactLockBusy as exc:
|
||||
held.close()
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
return held
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from common import run_cli
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
@@ -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
@@ -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()
|
||||
|
||||
|
||||
Reference in new issue
Block a user