mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-26 19:38:52 -06:00
refactor: split the leaf modules libraries use
model.region holds the region vocabulary, resolve.regions the selection that needs the cores a platform runs. The libraries behind identity.py, retired_files.py and torrentzip.py move to resolve.identity, model.retired and core.torrentzip, with their long docstrings; the commands stay where they are run from. The source_ref parts that cite a config or feature file move from scraper.shell_launchers to resolve.launcherrefs, so resolve no longer imports the scraper package.
This commit is contained in:
1 parent
83cfa6fd0f
commit
c764d9abf1
56 files changed
+839
-804
No files matched your search
@@ -45,8 +45,8 @@ from typing import BinaryIO
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from torrentzip import Source as Readable
|
||||
from torrentzip import write_torrentzip, zlib_ng_version
|
||||
from core.torrentzip import Source as Readable
|
||||
from core.torrentzip import write_torrentzip, zlib_ng_version
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
ARCHIVES_FILE = REPO_ROOT / "recipes" / "archives.json"
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
"""TorrentZip archive builder for MAME/FBNeo ROM sets.
|
||||
|
||||
TorrentZip is the archive format MAME romset distributions use. It fixes
|
||||
every non-content variable (member order, timestamps, compression level,
|
||||
extra fields, attributes), so the archive bytes are a pure function of the
|
||||
member names and their contents.
|
||||
|
||||
That property makes it possible to rebuild a romset ZIP that matches an
|
||||
upstream-published hash exactly, and to identify which romset revision a
|
||||
published hash refers to.
|
||||
|
||||
Usage:
|
||||
from core.torrentzip import build_torrentzip, identify_romset
|
||||
|
||||
data = build_torrentzip([("sp-s2.sp1", rom_bytes), ...])
|
||||
md5 = hashlib.md5(data).hexdigest()
|
||||
|
||||
Command line: scripts/torrentzip.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import hashlib
|
||||
import io
|
||||
import struct
|
||||
import zipfile
|
||||
import zlib
|
||||
from collections.abc import Callable, Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, NamedTuple, Protocol
|
||||
|
||||
|
||||
class Source(Protocol):
|
||||
"""An open member: read in chunks, closed by its ``with`` block."""
|
||||
|
||||
def read(self, size: int = -1, /) -> bytes: ...
|
||||
def __enter__(self) -> Source: ...
|
||||
def __exit__(self, *exc: Any) -> Any: ...
|
||||
|
||||
|
||||
class Sink(Protocol):
|
||||
def write(self, data: bytes | bytearray, /) -> int: ...
|
||||
|
||||
# TorrentZip constants: 1996-12-24 23:32:00, deflate level 9
|
||||
_DOS_DATE = ((1996 - 1980) << 9) | (12 << 5) | 24
|
||||
_DOS_TIME = (23 << 11) | (32 << 5) | 0
|
||||
_COMMENT_PREFIX = "TORRENTZIPPED-"
|
||||
# Members are read and deflated this much at a time. Deflate output does not
|
||||
# depend on how its input is cut, so a 2 GiB disk image streams through in
|
||||
# the same bytes a one-shot compression gives.
|
||||
CHUNK = 16 * 1024 * 1024
|
||||
# A size or offset that does not fit 32 bits takes a ZIP64 field. No
|
||||
# TorrentZip-conformant archive needs one, so their layout is untouched.
|
||||
ZIP32_LIMIT = 0xFFFFFFFF
|
||||
_ZIP64_MARK = 0xFFFFFFFF
|
||||
|
||||
|
||||
class Written(NamedTuple):
|
||||
"""A member as the writer read it from its source."""
|
||||
|
||||
name: str
|
||||
size: int
|
||||
crc32: str
|
||||
sha1: str
|
||||
|
||||
|
||||
def zlib_ng_version(module: object = zlib) -> str | None:
|
||||
"""The zlib-ng version this interpreter deflates with, None for zlib.
|
||||
|
||||
TorrentZip bytes are the output of zlib's level-9 deflate. Stock zlib
|
||||
1.2.13 to 1.3.2 reproduces every TorrentZip archive in the collection.
|
||||
zlib-ng 2.2.4 (python.org 3.14 on Windows) reproduces 479 of 1,561 and
|
||||
2.3.3 545, and the two disagree with each other.
|
||||
"""
|
||||
version = getattr(module, "ZLIBNG_VERSION", None)
|
||||
if version:
|
||||
return str(version)
|
||||
runtime = str(getattr(module, "ZLIB_RUNTIME_VERSION", "") or "")
|
||||
return runtime if "zlib-ng" in runtime.lower() else None
|
||||
|
||||
|
||||
def _deflate(stream: Source) -> tuple[bytes, Written]:
|
||||
compressor = zlib.compressobj(9, zlib.DEFLATED, -15)
|
||||
blob = bytearray()
|
||||
crc, size, sha1 = 0, 0, hashlib.sha1()
|
||||
while chunk := stream.read(CHUNK):
|
||||
crc = zlib.crc32(chunk, crc)
|
||||
size += len(chunk)
|
||||
sha1.update(chunk)
|
||||
blob += compressor.compress(chunk)
|
||||
blob += compressor.flush()
|
||||
return bytes(blob), Written("", size, f"{crc & 0xFFFFFFFF:08x}", sha1.hexdigest())
|
||||
|
||||
|
||||
def write_torrentzip(
|
||||
sink: Sink, members: Iterable[tuple[str, Callable[[], Source]]]
|
||||
) -> list[Written]:
|
||||
"""Write a TorrentZip archive to *sink*, one member in memory at a time.
|
||||
|
||||
*members* pairs each name with a callable opening its bytes. Members are
|
||||
sorted case-insensitively by name, as the format requires. Returns what
|
||||
was read, in archive order, so a caller can check every member.
|
||||
"""
|
||||
ordered = sorted(members, key=lambda m: m[0].lower())
|
||||
central = bytearray()
|
||||
offset = 0
|
||||
written: list[Written] = []
|
||||
for name, opener in ordered:
|
||||
raw = name.encode("ascii")
|
||||
with opener() as stream:
|
||||
blob, read = _deflate(stream)
|
||||
crc = int(read.crc32, 16)
|
||||
written.append(read._replace(name=name))
|
||||
wide = read.size >= ZIP32_LIMIT or len(blob) >= ZIP32_LIMIT
|
||||
far = offset >= ZIP32_LIMIT
|
||||
local_extra = struct.pack("<HHQQ", 1, 16, read.size, len(blob)) if wide else b""
|
||||
central_extra = (
|
||||
struct.pack("<QQ", read.size, len(blob)) if wide else b""
|
||||
) + (struct.pack("<Q", offset) if far else b"")
|
||||
if central_extra:
|
||||
central_extra = struct.pack("<HH", 1, len(central_extra)) + central_extra
|
||||
sizes = (_ZIP64_MARK, _ZIP64_MARK) if wide else (len(blob), read.size)
|
||||
needed = 45 if wide or far else 20
|
||||
header = struct.pack(
|
||||
"<IHHHHHIIIHH", 0x04034B50, needed, 2, 8, _DOS_TIME, _DOS_DATE,
|
||||
crc, *sizes, len(raw), len(local_extra),
|
||||
) + raw + local_extra
|
||||
sink.write(header)
|
||||
sink.write(blob)
|
||||
central += struct.pack(
|
||||
"<IHHHHHHIIIHHHHHII", 0x02014B50, 0, needed, 2, 8, _DOS_TIME, _DOS_DATE,
|
||||
crc, *sizes, len(raw), len(central_extra), 0, 0, 0, 0,
|
||||
_ZIP64_MARK if far else offset,
|
||||
) + raw + central_extra
|
||||
offset += len(header) + len(blob)
|
||||
|
||||
cd_offset = offset
|
||||
sink.write(central)
|
||||
count = len(ordered)
|
||||
if cd_offset >= ZIP32_LIMIT or len(central) >= ZIP32_LIMIT or count >= 0xFFFF:
|
||||
end64 = cd_offset + len(central)
|
||||
sink.write(struct.pack(
|
||||
"<IQHHIIQQQQ", 0x06064B50, 44, 45, 45, 0, 0, count, count,
|
||||
len(central), cd_offset,
|
||||
))
|
||||
sink.write(struct.pack("<IIQI", 0x07064B50, 0, end64, 1))
|
||||
comment = (
|
||||
f"{_COMMENT_PREFIX}{zlib.crc32(bytes(central)) & 0xFFFFFFFF:08X}"
|
||||
).encode("ascii")
|
||||
sink.write(struct.pack(
|
||||
"<IHHHHIIH", 0x06054B50, 0, 0, min(count, 0xFFFF), min(count, 0xFFFF),
|
||||
min(len(central), _ZIP64_MARK), min(cd_offset, _ZIP64_MARK), len(comment),
|
||||
))
|
||||
sink.write(comment)
|
||||
return written
|
||||
|
||||
|
||||
def build_torrentzip(members: list[tuple[str, bytes]]) -> bytes:
|
||||
"""Build a TorrentZip archive from (name, data) members.
|
||||
|
||||
Members are sorted case-insensitively by name, as the format requires.
|
||||
Returns the complete archive bytes.
|
||||
"""
|
||||
sink = io.BytesIO()
|
||||
write_torrentzip(
|
||||
sink, [(name, functools.partial(io.BytesIO, data)) for name, data in members]
|
||||
)
|
||||
return sink.getvalue()
|
||||
|
||||
|
||||
def rebuild_torrentzip(source: str | Path) -> bytes:
|
||||
"""Read an archive and return its TorrentZip normalization."""
|
||||
with zipfile.ZipFile(source) as zf:
|
||||
members = [
|
||||
(info.filename, zf.read(info.filename))
|
||||
for info in zf.infolist()
|
||||
if not info.is_dir()
|
||||
]
|
||||
return build_torrentzip(members)
|
||||
|
||||
|
||||
def is_torrentzip(source: str | Path) -> bool:
|
||||
"""Report whether an archive already carries the TorrentZip signature."""
|
||||
with zipfile.ZipFile(source) as zf:
|
||||
return zf.comment.decode("ascii", "replace").startswith(_COMMENT_PREFIX)
|
||||
|
||||
|
||||
def identify_romset(
|
||||
recipes: dict[str, list[tuple[str, str]]],
|
||||
atoms: dict[str, bytes],
|
||||
target_md5: str,
|
||||
) -> str | None:
|
||||
"""Find which recipe rebuilds to a target archive MD5.
|
||||
|
||||
recipes maps a label (e.g. a MAME version) to a list of
|
||||
(member name, CRC32 hex) pairs, and atoms maps CRC32 hex to ROM bytes.
|
||||
Returns the matching label, or None when no recipe reproduces the hash.
|
||||
"""
|
||||
target = target_md5.lower()
|
||||
for label, recipe in recipes.items():
|
||||
if any(crc.lower() not in atoms for _, crc in recipe):
|
||||
continue
|
||||
members = [(name, atoms[crc.lower()]) for name, crc in recipe]
|
||||
if hashlib.md5(build_torrentzip(members)).hexdigest() == target:
|
||||
return label
|
||||
return None
|
||||
@@ -20,7 +20,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from model.profiles import load_emulator_profiles
|
||||
from region import REGIONS, normalize_declared
|
||||
from model.region import REGIONS, normalize_declared
|
||||
from model.safeparse import yaml_load
|
||||
|
||||
REGIONS_FILE = Path("games") / "regions.yml"
|
||||
|
||||
@@ -33,7 +33,7 @@ from core.artifacts import (
|
||||
from model.safeparse import require_yaml, yaml_load
|
||||
from model.profiles import source_yaml_paths
|
||||
from resolve.localfile import variant_base_name
|
||||
import retired_files
|
||||
from model import retired
|
||||
|
||||
# Platform and profile aliases are read from YAML: without pyyaml the
|
||||
# database lost every one of them and the run still exited 0.
|
||||
@@ -542,13 +542,13 @@ def _generate(args: argparse.Namespace) -> int:
|
||||
output = Path(args.output)
|
||||
if output.is_file():
|
||||
previous = json.loads(output.read_text(encoding="utf-8"))
|
||||
left = retired_files.update(
|
||||
retired_files.retired_path(output), previous, database,
|
||||
left = retired.update(
|
||||
retired.retired_path(output), previous, database,
|
||||
database["generated_at"][:10],
|
||||
)
|
||||
if left:
|
||||
print(f" Left the collection: {left} files, recorded in "
|
||||
f"{retired_files.retired_path(output)}")
|
||||
f"{retired.retired_path(output)}")
|
||||
|
||||
new_content = json.dumps(database, indent=2)
|
||||
written = write_if_changed(args.output, new_content)
|
||||
|
||||
@@ -47,7 +47,7 @@ from model.profiles import load_emulator_profiles
|
||||
from model.platforms import load_platform_config, native_layer
|
||||
from core.artifacts import repository_output_lock
|
||||
from core.cli import run_cli
|
||||
from region import normalize_declared
|
||||
from model.region import normalize_declared
|
||||
from romfolders import (
|
||||
ProfileResolver,
|
||||
Resolution,
|
||||
|
||||
@@ -110,7 +110,8 @@ from resolve.standalone import platform_layouts, standalone_set
|
||||
from core.paths import sanitize_pack_path
|
||||
import packresolve
|
||||
from refresh_data_dirs import cache_lock, hold_data_dirs
|
||||
import region as region_mod
|
||||
from model import region
|
||||
from resolve import regions as resolve_regions
|
||||
from manifestselect import SelectionIndex
|
||||
from resolve import slot as slot_mod
|
||||
import slots
|
||||
@@ -339,7 +340,7 @@ def _narrowings(
|
||||
" ".join(w.title() for w in slug.split("-")) for slug in regions
|
||||
)
|
||||
applied.append(
|
||||
(f"_{region_mod.region_tag(regions)}", f"region priority {pretty}")
|
||||
(f"_{region.region_tag(regions)}", f"region priority {pretty}")
|
||||
)
|
||||
if target_name:
|
||||
applied.append(
|
||||
@@ -841,13 +842,13 @@ def _select_variants(
|
||||
slot_overrides=options.get("slot_overrides"),
|
||||
)
|
||||
if regions:
|
||||
region_index = region_mod.platform_region_index(
|
||||
region_index = resolve_regions.platform_region_index(
|
||||
config, emu_profiles or {}, target_cores
|
||||
)
|
||||
region_drops = region_mod.resolve_region_drops(
|
||||
region_drops = resolve_regions.resolve_region_drops(
|
||||
region_groups, region_index, regions, held
|
||||
)
|
||||
region_fallbacks = region_mod.fallback_groups(
|
||||
region_fallbacks = resolve_regions.fallback_groups(
|
||||
region_groups, region_index, regions
|
||||
)
|
||||
|
||||
@@ -3903,7 +3904,7 @@ def _refuse_unapplied_flags(args: argparse.Namespace, parser: argparse.ArgumentP
|
||||
args.regions = []
|
||||
if args.region:
|
||||
try:
|
||||
args.regions = region_mod.parse_requested(args.region)
|
||||
args.regions = region.parse_requested(args.region)
|
||||
except ValueError as exc:
|
||||
parser.error(str(exc))
|
||||
if args.manifest_targets:
|
||||
@@ -5225,11 +5226,11 @@ def _manifest_selection(
|
||||
data_registry=options.get("data_registry"),
|
||||
slot_overrides=options.get("slot_overrides"),
|
||||
)
|
||||
region_index = region_mod.platform_region_index(
|
||||
region_index = resolve_regions.platform_region_index(
|
||||
config, emu_profiles, target_cores
|
||||
)
|
||||
drops = (
|
||||
region_mod.resolve_region_drops(region_groups, region_index, regions, held)
|
||||
resolve_regions.resolve_region_drops(region_groups, region_index, regions, held)
|
||||
if regions
|
||||
else set()
|
||||
)
|
||||
|
||||
@@ -88,7 +88,7 @@ from provenance_report import build_report, distinct_missing, profile_needs
|
||||
import sitemarkup as markup
|
||||
import siteentries
|
||||
import siteinputs
|
||||
import retired_files
|
||||
from model import retired as model_retired
|
||||
import siteagents
|
||||
import sitediagrams
|
||||
import sitestarlight
|
||||
@@ -1697,7 +1697,7 @@ def generate_data_exports(
|
||||
}
|
||||
write_lookup_shards(
|
||||
api, file_lookup_records(db, coverages, profiles, locations, members, consumers,
|
||||
retired_files.load(_REPO_ROOT / "retired.json"), wanted),
|
||||
model_retired.load(_REPO_ROOT / "retired.json"), wanted),
|
||||
generated_at, commit,
|
||||
)
|
||||
for filename, (kind, items) in envelopes.items():
|
||||
@@ -6814,7 +6814,7 @@ def _region_order() -> dict[str, int]:
|
||||
for every region is a region-free stand-in for the BIOS of each one:
|
||||
the PlayStation section opened on psxonpsp660.bin, which one emulator
|
||||
requires among the BIOS it accepts, above the scph files most read."""
|
||||
from region import REGION_TREE, WORLD
|
||||
from model.region import REGION_TREE, WORLD
|
||||
|
||||
ordered = []
|
||||
for parent, members in REGION_TREE.items():
|
||||
@@ -7460,7 +7460,7 @@ def _runs_without(words: _GroupWords) -> list[tuple[str, str]]:
|
||||
def _region_lines(words: _GroupWords) -> tuple[list[tuple[str, str]], set[str], set[str]]:
|
||||
"""The lines of the files picked by region, the emulators they answer
|
||||
and the names they give."""
|
||||
from region import _PARENT
|
||||
from model.region import _PARENT
|
||||
|
||||
group = words.group
|
||||
order = _region_order()
|
||||
@@ -8250,7 +8250,7 @@ def _region_words(value: object, most: int = 0) -> str:
|
||||
"""A region: value in words. ``most`` caps the regions named, the rest
|
||||
counted: one Saturn BIOS serves seven."""
|
||||
raw = value if isinstance(value, list) else [value] if value else []
|
||||
from region import label
|
||||
from model.region import label
|
||||
|
||||
words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw]
|
||||
if most and len(words) > most:
|
||||
|
||||
+2
-113
@@ -1,119 +1,8 @@
|
||||
"""Files whose bytes contradict the identity they are stored under.
|
||||
|
||||
The collection is indexed by content, so one sha1 keeps one path. A file
|
||||
copied into a second system's directory under a second name therefore becomes
|
||||
invisible: the index answers with whichever path was recorded, and every
|
||||
consumer of that name is served bytes belonging to another machine. That is
|
||||
how the Amiga Kickstart came to be served as a Saturn cartridge firmware, and
|
||||
nothing in the pipeline could see it, because on paper both names resolved.
|
||||
|
||||
This walks the tree rather than the index, groups by content, and reports a
|
||||
group whose paths sit under different manufacturers. A dump legitimately
|
||||
shared by two systems of the same maker is common, one shared across makers
|
||||
almost never is.
|
||||
"""
|
||||
"""Report one content stored under identities that disagree (resolve/identity.py)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
# A manufacturer directory holding files that genuinely belong to several
|
||||
# machines, where a shared dump says nothing about a misfiling.
|
||||
SHARED_TREES = frozenset({"Arcade", "Other"})
|
||||
|
||||
# One dump, two machines that really did share it. Each entry names the makers
|
||||
# whose directories may hold it and the reason they do, so a crossing that is
|
||||
# not on this list, or a further copy under a third maker, is a finding rather
|
||||
# than noise.
|
||||
KNOWN_SHARED: dict[str, tuple[frozenset[str], str]] = {
|
||||
"45bedc4cbdeac66c7df59e9e599195c778d86a92": (
|
||||
frozenset({"Coleco", "Microsoft"}),
|
||||
"ColecoVision BIOS, carried by MSX emulators for their ColecoVision "
|
||||
"machine",
|
||||
),
|
||||
"286b2e1fb21cc79851da01666db6c0b0e88f25e3": (
|
||||
frozenset({"Infocom", "ZC"}),
|
||||
"one soundfont shipped by two interpreters",
|
||||
),
|
||||
}
|
||||
|
||||
CHUNK = 1 << 20
|
||||
|
||||
|
||||
@dataclass
|
||||
class Duplicate:
|
||||
"""One content, stored under paths that disagree about what it is."""
|
||||
|
||||
sha1: str
|
||||
size: int
|
||||
paths: list[str]
|
||||
manufacturers: list[str]
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return sorted({Path(p).name for p in self.paths})
|
||||
|
||||
|
||||
def _manufacturer(path: Path, root: Path) -> str:
|
||||
"""The vendor directory a path sits under, relative to the scanned root."""
|
||||
parts = path.relative_to(root).parts
|
||||
return parts[0] if len(parts) > 1 else ""
|
||||
|
||||
|
||||
def _sha1(path: Path) -> str:
|
||||
digest = hashlib.sha1()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(CHUNK), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def scan(bios_dir: str = "bios") -> list[Duplicate]:
|
||||
"""Group the tree by content and keep the groups that cross makers.
|
||||
|
||||
Only files that share a size can share a content, so a size held by one
|
||||
file is never read: hashing the whole tree read 18 GB on every pipeline.
|
||||
"""
|
||||
by_size: dict[int, list[Path]] = {}
|
||||
root = Path(bios_dir)
|
||||
for path in sorted(root.rglob("*")):
|
||||
if path.is_file():
|
||||
by_size.setdefault(path.stat().st_size, []).append(path)
|
||||
by_content: dict[str, list[Path]] = {}
|
||||
for paths in by_size.values():
|
||||
if len(paths) < 2:
|
||||
continue
|
||||
for path in paths:
|
||||
by_content.setdefault(_sha1(path), []).append(path)
|
||||
|
||||
found: list[Duplicate] = []
|
||||
for sha1, paths in by_content.items():
|
||||
if len(paths) < 2:
|
||||
continue
|
||||
makers = {_manufacturer(p, root) for p in paths} - SHARED_TREES
|
||||
if sha1 in KNOWN_SHARED and makers <= KNOWN_SHARED[sha1][0]:
|
||||
continue
|
||||
names = {p.name for p in paths}
|
||||
if len(makers) > 1 and len(names) > 1:
|
||||
found.append(
|
||||
Duplicate(
|
||||
sha1=sha1,
|
||||
size=paths[0].stat().st_size,
|
||||
paths=[str(p) for p in paths],
|
||||
manufacturers=sorted(makers),
|
||||
)
|
||||
)
|
||||
return sorted(found, key=lambda d: d.paths[0])
|
||||
|
||||
|
||||
def format_duplicate(duplicate: Duplicate) -> str:
|
||||
"""One line naming the content and every identity it answers to."""
|
||||
return (
|
||||
f"{duplicate.sha1[:12]} ({duplicate.size} bytes) is stored as "
|
||||
+ " and as ".join(duplicate.paths)
|
||||
)
|
||||
from resolve.identity import format_duplicate, scan
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -17,7 +17,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import region as region_mod
|
||||
from resolve import regions as resolve_regions
|
||||
from resolve import slot as slot_mod
|
||||
from model.systems import _norm_system_id
|
||||
from core.paths import sanitize_pack_path
|
||||
@@ -117,7 +117,7 @@ class SelectionIndex:
|
||||
return out
|
||||
if dest in self.slots:
|
||||
out["slot"] = self.slots[dest]
|
||||
regions = region_mod.lookup_regions(self.region_index, dest, name)
|
||||
regions = resolve_regions.lookup_regions(self.region_index, dest, name)
|
||||
if not regions:
|
||||
return out
|
||||
out["regions"] = sorted(regions)
|
||||
@@ -129,7 +129,7 @@ class SelectionIndex:
|
||||
out["region_system_groups"] = sorted(declared)
|
||||
# The code's search rank decides whether a world file may withdraw
|
||||
# this one when no region matches.
|
||||
priority = region_mod.lookup_priority(self.region_index, dest, name)
|
||||
priority = resolve_regions.lookup_priority(self.region_index, dest, name)
|
||||
if priority is not None:
|
||||
out["priority"] = priority
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Region vocabulary: territories, aliases, labels and their order."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
|
||||
|
||||
WORLD = "world"
|
||||
|
||||
# Two levels only: super-region -> member territories.
|
||||
REGION_TREE: dict[str, frozenset[str]] = {
|
||||
"north-america": frozenset({"canada"}),
|
||||
"latin-america": frozenset({"brazil", "mexico", "argentina"}),
|
||||
"europe": frozenset(
|
||||
{
|
||||
"uk",
|
||||
"france",
|
||||
"germany",
|
||||
"italy",
|
||||
"spain",
|
||||
"netherlands",
|
||||
"portugal",
|
||||
"greece",
|
||||
"poland",
|
||||
"russia",
|
||||
"sweden",
|
||||
"norway",
|
||||
"denmark",
|
||||
"finland",
|
||||
}
|
||||
),
|
||||
"asia": frozenset(
|
||||
{
|
||||
"japan",
|
||||
"south-korea",
|
||||
"china",
|
||||
"taiwan",
|
||||
"hong-kong",
|
||||
"singapore",
|
||||
"india",
|
||||
"asia-ntsc",
|
||||
"asia-pal",
|
||||
}
|
||||
),
|
||||
"oceania": frozenset({"australia", "new-zealand"}),
|
||||
}
|
||||
|
||||
# Hardware areas that fuse territory and signal standard, with the territories
|
||||
# the code serves through them. Mednafen's Saturn SMPC area 0x2 is "For TAIWAN
|
||||
# and PHILIPINES" and its area option offers it as "Taiwan", area 0xA as
|
||||
# "China" (mednafen/ss/ss.cpp:1119, 2363-2364 in the mednafen_stv port).
|
||||
# kronos tags the ST-V BIOS epr-19854.ic8 taiwan and mednafen_stv tags it
|
||||
# asia-ntsc: a request in either spelling has to reach the other.
|
||||
AREA_TERRITORIES: dict[str, frozenset[str]] = {
|
||||
"asia-ntsc": frozenset({"taiwan"}),
|
||||
"asia-pal": frozenset({"china"}),
|
||||
}
|
||||
|
||||
_PARENT: dict[str, str] = {
|
||||
member: parent for parent, members in REGION_TREE.items() for member in members
|
||||
}
|
||||
|
||||
REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(_PARENT))
|
||||
|
||||
# Accepted on the CLI and for legacy profile values. Every territory also
|
||||
# answers to its ISO 3166-1 code: `au` alone was unknown, and the closest
|
||||
# spelling offered first was `auto`, which means world.
|
||||
ALIASES: dict[str, str] = {
|
||||
"jp": "japan",
|
||||
"ntsc-j": "japan",
|
||||
"us": "north-america",
|
||||
"usa": "north-america",
|
||||
"na": "north-america",
|
||||
"ntsc-u": "north-america",
|
||||
"eu": "europe",
|
||||
"pal": "europe",
|
||||
"kr": "south-korea",
|
||||
"korea": "south-korea",
|
||||
"auto": WORLD,
|
||||
"gb": "uk",
|
||||
"ca": "canada",
|
||||
"br": "brazil",
|
||||
"mx": "mexico",
|
||||
"ar": "argentina",
|
||||
"fr": "france",
|
||||
"de": "germany",
|
||||
"it": "italy",
|
||||
"es": "spain",
|
||||
"nl": "netherlands",
|
||||
"pt": "portugal",
|
||||
"gr": "greece",
|
||||
"pl": "poland",
|
||||
"ru": "russia",
|
||||
"se": "sweden",
|
||||
"no": "norway",
|
||||
"dk": "denmark",
|
||||
"fi": "finland",
|
||||
"cn": "china",
|
||||
"tw": "taiwan",
|
||||
"hk": "hong-kong",
|
||||
"sg": "singapore",
|
||||
"in": "india",
|
||||
"au": "australia",
|
||||
"nz": "new-zealand",
|
||||
}
|
||||
|
||||
|
||||
# Slugs a person does not write title-cased: "Asia Ntsc" read as machine text.
|
||||
LABELS: dict[str, str] = {
|
||||
"uk": "UK",
|
||||
"asia-ntsc": "Asia (NTSC)",
|
||||
"asia-pal": "Asia (PAL)",
|
||||
}
|
||||
|
||||
|
||||
def label(slug: str) -> str:
|
||||
"""A region slug in words: north-america as North America."""
|
||||
return LABELS.get(slug) or " ".join(word.title() for word in slug.split("-"))
|
||||
|
||||
|
||||
def unknown_region_message(raw: str, aliases: dict[str, str], regions: frozenset[str]) -> str:
|
||||
"""What to type instead: the closest spellings, then every short form.
|
||||
|
||||
`unknown region: 'uss'` left the user to read the source for `us`.
|
||||
"""
|
||||
import difflib
|
||||
|
||||
spelled = raw.strip()
|
||||
close = difflib.get_close_matches(spelled.lower(), [*aliases, *regions], n=3, cutoff=0.5)
|
||||
hint = f" Close matches: {', '.join(close)}." if close else ""
|
||||
return (
|
||||
f"unknown region: {spelled}.{hint} Short forms: {', '.join(aliases)}; "
|
||||
f"regions: {', '.join(sorted(regions))}"
|
||||
)
|
||||
|
||||
|
||||
def _canonical(raw: str) -> str:
|
||||
"""Map one token to a canonical region slug."""
|
||||
key = raw.strip().lower()
|
||||
key = ALIASES.get(key, key)
|
||||
if key not in REGIONS:
|
||||
raise ValueError(unknown_region_message(raw, ALIASES, REGIONS))
|
||||
return key
|
||||
|
||||
|
||||
def comparable(a: str, b: str) -> bool:
|
||||
"""True when two regions are equal, parent and child, or an area and a
|
||||
territory it serves."""
|
||||
return (
|
||||
a == b
|
||||
or _PARENT.get(a) == b
|
||||
or _PARENT.get(b) == a
|
||||
or a in AREA_TERRITORIES.get(b, ())
|
||||
or b in AREA_TERRITORIES.get(a, ())
|
||||
)
|
||||
|
||||
|
||||
def normalize_declared(raw: str | list | None) -> set[str]:
|
||||
"""Normalise a profile region: value to canonical slugs."""
|
||||
if raw is None:
|
||||
return set()
|
||||
values = raw if isinstance(raw, list) else [raw]
|
||||
return {_canonical(str(v)) for v in values}
|
||||
|
||||
|
||||
def parse_requested(raw: str) -> list[str]:
|
||||
"""Parse a comma-separated --region value into an ordered priority list."""
|
||||
out: list[str] = []
|
||||
for part in raw.split(","):
|
||||
if not part.strip():
|
||||
continue
|
||||
slug = _canonical(part)
|
||||
if slug not in out:
|
||||
out.append(slug)
|
||||
if not out:
|
||||
raise ValueError("--region requires at least one region")
|
||||
return out
|
||||
|
||||
|
||||
def rank(file_regions: set[str], requested: list[str]) -> int:
|
||||
"""Priority index of a file, lower is better.
|
||||
|
||||
Returns len(requested) when no requested region is comparable, the implicit
|
||||
lowest rank that keeps a group from ever being emptied.
|
||||
"""
|
||||
for i, req in enumerate(requested):
|
||||
if any(comparable(req, fr) for fr in file_regions):
|
||||
return i
|
||||
return len(requested)
|
||||
|
||||
|
||||
def region_tag(requested: list[str]) -> str:
|
||||
"""Pack filename tag for a requested priority list."""
|
||||
return "_".join(
|
||||
"".join(part.title() for part in slug.split("-")) for slug in requested
|
||||
)
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Files that left the collection, and the file that took their place.
|
||||
|
||||
A file's content address (files/?sha1=, #sha1-<12> on its card) is
|
||||
published, and a published address never stops answering. When a rebuild
|
||||
of database.json drops a sha1, the file it named is recorded here: its
|
||||
name, its last path, its hashes, the day it left and the sha1 the
|
||||
collection now holds at that path, or under that name in that folder.
|
||||
The site's lookup reads the record and answers with it.
|
||||
|
||||
The record is append-only, written by generate_db.py beside the database.
|
||||
A sha1 that comes back leaves it. `--backfill` rebuilds it from the
|
||||
history of database.json since content addresses were published.
|
||||
|
||||
The command (`--backfill`) is scripts/retired_files.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from core.artifacts import write_if_changed
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
|
||||
RETIRED_FILE = REPO_ROOT / "retired.json"
|
||||
# The commit that published content addresses: 0d586ef6b, 2026-10-19.
|
||||
FIRST_ADDRESSED = "0d586ef6b"
|
||||
KEPT_FIELDS = ("name", "path", "size", "md5", "crc32", "sha256")
|
||||
|
||||
|
||||
def retired_path(database: str | Path) -> Path:
|
||||
"""The record kept beside a database file."""
|
||||
return Path(database).with_name("retired.json")
|
||||
|
||||
|
||||
def _successor(entry: dict, by_path: dict[str, str],
|
||||
by_name: dict[str, list[tuple[str, str]]]) -> str | None:
|
||||
"""The sha1 the new database holds at the entry's path, else under its
|
||||
name in the same folder, else the one file of that name: a2diskiing.zip
|
||||
was rebuilt from its recipe and filed under Apple II the same day."""
|
||||
path = str(entry.get("path", ""))
|
||||
if path in by_path:
|
||||
return by_path[path]
|
||||
named = by_name.get(str(entry.get("name", "")), [])
|
||||
folder = path.rsplit("/", 1)[0]
|
||||
beside = [sha1 for sha1, other in named if other.rsplit("/", 1)[0] == folder]
|
||||
for found in (beside, [sha1 for sha1, _other in named]):
|
||||
if len(found) == 1:
|
||||
return found[0]
|
||||
return None
|
||||
|
||||
|
||||
def retired_between(old: dict, new: dict, day: str) -> dict[str, dict]:
|
||||
"""sha1 -> record, for each file of *old* that *new* no longer holds."""
|
||||
old_files = old.get("files") or {}
|
||||
new_files = new.get("files") or {}
|
||||
by_path = {str(e.get("path", "")): sha1 for sha1, e in new_files.items()}
|
||||
by_name: dict[str, list[tuple[str, str]]] = {}
|
||||
for sha1, e in new_files.items():
|
||||
by_name.setdefault(str(e.get("name", "")), []).append((sha1, str(e.get("path", ""))))
|
||||
records = {}
|
||||
for sha1 in sorted(set(old_files) - set(new_files)):
|
||||
entry = old_files[sha1]
|
||||
record = {key: entry[key] for key in KEPT_FIELDS if entry.get(key) not in (None, "")}
|
||||
record["left"] = day
|
||||
successor = _successor(entry, by_path, by_name)
|
||||
if successor:
|
||||
record["successor"] = successor
|
||||
records[sha1] = record
|
||||
return records
|
||||
|
||||
|
||||
def merge(record: dict[str, dict], left: dict[str, dict], new: dict) -> dict[str, dict]:
|
||||
"""The record with *left* added, first departure kept, and every sha1
|
||||
the new database holds again taken out."""
|
||||
held = set(new.get("files") or {})
|
||||
merged = {sha1: entry for sha1, entry in record.items() if sha1 not in held}
|
||||
for sha1, entry in left.items():
|
||||
merged.setdefault(sha1, entry)
|
||||
return dict(sorted(merged.items()))
|
||||
|
||||
|
||||
def load(path: Path) -> dict[str, dict]:
|
||||
if not path.is_file():
|
||||
return {}
|
||||
return json.loads(path.read_text(encoding="utf-8")).get("files") or {}
|
||||
|
||||
|
||||
def dump(records: dict[str, dict]) -> str:
|
||||
return json.dumps({"schema_version": 1, "files": records}, indent=1, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def update(path: Path, old: dict, new: dict, day: str) -> int:
|
||||
"""Records what *new* dropped from *old*. Returns how many left now."""
|
||||
left = retired_between(old, new, day)
|
||||
record = load(path)
|
||||
merged = merge(record, left, new)
|
||||
if merged != record:
|
||||
write_if_changed(str(path), dump(merged))
|
||||
return len(set(left) - set(record))
|
||||
@@ -27,7 +27,7 @@ from core.paths import sanitize_pack_path
|
||||
from resolve.content import declares_shape, shape_fits, size_fits
|
||||
from resolve.validation import deliverable, read_from_save_dir, read_from_system_dir
|
||||
from packpaths import libretro_systems, save_destination, save_layout
|
||||
from region import FILE_GROUP
|
||||
from resolve.regions import FILE_GROUP
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import Unpack
|
||||
@@ -2321,11 +2321,11 @@ def emulator_region_drops(
|
||||
BIOS at all. ``zip_contents`` and ``data_registry`` are the ones the
|
||||
emulator pack resolves with.
|
||||
"""
|
||||
import region as region_mod
|
||||
from resolve import regions as resolve_regions
|
||||
from packpaths import _resolve_destination
|
||||
from resolve.validation import _build_validation_index, filter_files_by_mode
|
||||
|
||||
region_index = region_mod.build_region_index(dict(selected))
|
||||
region_index = resolve_regions.build_region_index(dict(selected))
|
||||
region_groups: dict[str, list[tuple[str, str]]] = {}
|
||||
held: set[str] | None = set() if db is not None else None
|
||||
validation_index = _build_validation_index(dict(selected)) if db is not None else {}
|
||||
@@ -2345,7 +2345,7 @@ def emulator_region_drops(
|
||||
zip_contents, data_registry,
|
||||
):
|
||||
held.add(dest)
|
||||
return region_mod.resolve_region_drops(region_groups, region_index, regions, held)
|
||||
return resolve_regions.resolve_region_drops(region_groups, region_index, regions, held)
|
||||
|
||||
|
||||
class SpareOptions(TypedDict, total=False):
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
from packextras import reject_unknown
|
||||
from region import label as region_label
|
||||
from model.region import label as region_label
|
||||
from siteguides import INSTALL_PS1, INSTALL_SH, pack_manual
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
@@ -31,7 +31,7 @@ import os
|
||||
from packextras import platform_region_groups
|
||||
from packpaths import _flat
|
||||
from resolve.nativemode import reads_file_contents
|
||||
import region as region_mod
|
||||
from resolve import regions as resolve_regions
|
||||
import slots
|
||||
from packresolve import resolve_declaration, resolve_file
|
||||
from resolve.categories import BIOS, EntryCategories
|
||||
@@ -776,7 +776,7 @@ def _region_drops(
|
||||
region_drops: set[str] = set()
|
||||
if not opts.regions:
|
||||
return region_drops
|
||||
region_index = region_mod.platform_region_index(
|
||||
region_index = resolve_regions.platform_region_index(
|
||||
config, emu_profiles, target_cores
|
||||
)
|
||||
held: set[str] = set()
|
||||
@@ -800,7 +800,7 @@ def _region_drops(
|
||||
target_cores=target_cores, source=opts.source,
|
||||
) if db is not None else None,
|
||||
)
|
||||
return region_mod.resolve_region_drops(
|
||||
return resolve_regions.resolve_region_drops(
|
||||
region_groups, region_index, opts.regions, held
|
||||
)
|
||||
|
||||
|
||||
+4
-4
@@ -552,11 +552,11 @@ def emulator_variants(profiles: list[dict], full: bool) -> list[tuple[str, dict]
|
||||
sampled as check_narrowed_packs samples them unless *full*. A profile
|
||||
without a regional file has nothing --region could withdraw.
|
||||
"""
|
||||
import region as region_mod
|
||||
from model import region
|
||||
|
||||
regions = sorted({
|
||||
r for profile in profiles for fe in profile.get("files") or []
|
||||
for r in region_mod.normalize_declared(fe.get("region"))
|
||||
for r in region.normalize_declared(fe.get("region"))
|
||||
})
|
||||
variants: list[tuple[str, dict]] = [("", {}), (" --required-only", {"required_only": True})]
|
||||
variants += [
|
||||
@@ -701,11 +701,11 @@ def narrowed_variants(
|
||||
target, every system, --no-game-data and --required-only. Without
|
||||
*full*, regions, targets and systems are sampled (_matrix_coverage).
|
||||
"""
|
||||
import region as region_mod
|
||||
from resolve import regions as resolve_regions
|
||||
from model.targets import list_available_targets
|
||||
|
||||
regions = sorted({
|
||||
r for entry in region_mod.platform_region_index(config, profiles).values()
|
||||
r for entry in resolve_regions.platform_region_index(config, profiles).values()
|
||||
for r in entry["regions"]
|
||||
})
|
||||
targets = [t["name"] for t in list_available_targets(platform, platforms_dir)]
|
||||
|
||||
@@ -18,7 +18,7 @@ from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import region
|
||||
from model import region
|
||||
from model.database import load_database
|
||||
from model.profiles import load_emulator_profiles
|
||||
from resolve.localfile import resolve_local_file
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Files whose bytes contradict the identity they are stored under.
|
||||
|
||||
The collection is indexed by content, so one sha1 keeps one path. A file
|
||||
copied into a second system's directory under a second name therefore becomes
|
||||
invisible: the index answers with whichever path was recorded, and every
|
||||
consumer of that name is served bytes belonging to another machine. That is
|
||||
how the Amiga Kickstart came to be served as a Saturn cartridge firmware, and
|
||||
nothing in the pipeline could see it, because on paper both names resolved.
|
||||
|
||||
This walks the tree rather than the index, groups by content, and reports a
|
||||
group whose paths sit under different manufacturers. A dump legitimately
|
||||
shared by two systems of the same maker is common, one shared across makers
|
||||
almost never is.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# A manufacturer directory holding files that genuinely belong to several
|
||||
# machines, where a shared dump says nothing about a misfiling.
|
||||
SHARED_TREES = frozenset({"Arcade", "Other"})
|
||||
|
||||
# One dump, two machines that really did share it. Each entry names the makers
|
||||
# whose directories may hold it and the reason they do, so a crossing that is
|
||||
# not on this list, or a further copy under a third maker, is a finding rather
|
||||
# than noise.
|
||||
KNOWN_SHARED: dict[str, tuple[frozenset[str], str]] = {
|
||||
"45bedc4cbdeac66c7df59e9e599195c778d86a92": (
|
||||
frozenset({"Coleco", "Microsoft"}),
|
||||
"ColecoVision BIOS, carried by MSX emulators for their ColecoVision "
|
||||
"machine",
|
||||
),
|
||||
"286b2e1fb21cc79851da01666db6c0b0e88f25e3": (
|
||||
frozenset({"Infocom", "ZC"}),
|
||||
"one soundfont shipped by two interpreters",
|
||||
),
|
||||
}
|
||||
|
||||
CHUNK = 1 << 20
|
||||
|
||||
|
||||
@dataclass
|
||||
class Duplicate:
|
||||
"""One content, stored under paths that disagree about what it is."""
|
||||
|
||||
sha1: str
|
||||
size: int
|
||||
paths: list[str]
|
||||
manufacturers: list[str]
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return sorted({Path(p).name for p in self.paths})
|
||||
|
||||
|
||||
def _manufacturer(path: Path, root: Path) -> str:
|
||||
"""The vendor directory a path sits under, relative to the scanned root."""
|
||||
parts = path.relative_to(root).parts
|
||||
return parts[0] if len(parts) > 1 else ""
|
||||
|
||||
|
||||
def _sha1(path: Path) -> str:
|
||||
digest = hashlib.sha1()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(CHUNK), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def scan(bios_dir: str = "bios") -> list[Duplicate]:
|
||||
"""Group the tree by content and keep the groups that cross makers.
|
||||
|
||||
Only files that share a size can share a content, so a size held by one
|
||||
file is never read: hashing the whole tree read 18 GB on every pipeline.
|
||||
"""
|
||||
by_size: dict[int, list[Path]] = {}
|
||||
root = Path(bios_dir)
|
||||
for path in sorted(root.rglob("*")):
|
||||
if path.is_file():
|
||||
by_size.setdefault(path.stat().st_size, []).append(path)
|
||||
by_content: dict[str, list[Path]] = {}
|
||||
for paths in by_size.values():
|
||||
if len(paths) < 2:
|
||||
continue
|
||||
for path in paths:
|
||||
by_content.setdefault(_sha1(path), []).append(path)
|
||||
|
||||
found: list[Duplicate] = []
|
||||
for sha1, paths in by_content.items():
|
||||
if len(paths) < 2:
|
||||
continue
|
||||
makers = {_manufacturer(p, root) for p in paths} - SHARED_TREES
|
||||
if sha1 in KNOWN_SHARED and makers <= KNOWN_SHARED[sha1][0]:
|
||||
continue
|
||||
names = {p.name for p in paths}
|
||||
if len(makers) > 1 and len(names) > 1:
|
||||
found.append(
|
||||
Duplicate(
|
||||
sha1=sha1,
|
||||
size=paths[0].stat().st_size,
|
||||
paths=[str(p) for p in paths],
|
||||
manufacturers=sorted(makers),
|
||||
)
|
||||
)
|
||||
return sorted(found, key=lambda d: d.paths[0])
|
||||
|
||||
|
||||
def format_duplicate(duplicate: Duplicate) -> str:
|
||||
"""One line naming the content and every identity it answers to."""
|
||||
return (
|
||||
f"{duplicate.sha1[:12]} ({duplicate.size} bytes) is stored as "
|
||||
+ " and as ".join(duplicate.paths)
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""The parts of a launcher record's source_ref that cite a config or feature file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
|
||||
# The files a platform ships as configuration: an emulator reads them, the
|
||||
# platform's code never runs them. Batocera's .yml lists and an EmuELEC .opt
|
||||
# only offer the values a menu option takes.
|
||||
_CONFIG_FILE = re.compile(
|
||||
r"\.(?:ini|cfg|conf|rc|rc_\w+|opt|bml|toml|uae|template|yml|yaml)$", re.IGNORECASE
|
||||
)
|
||||
_FEATURE_FILE = re.compile(r"(?:^|/)es_features[^/]*$|\.opt$", re.IGNORECASE)
|
||||
|
||||
|
||||
def split_ref(ref: str) -> list[str]:
|
||||
"""The parts of a source_ref, each "path:lines", a bare line span
|
||||
continuing the path before it."""
|
||||
parts: list[str] = []
|
||||
for part in (p.strip() for p in ref.split(", ")):
|
||||
if not part:
|
||||
continue
|
||||
if re.fullmatch(r"\d+(?:-\d+)?", part) and parts:
|
||||
parts[-1] += f", {part}"
|
||||
else:
|
||||
parts.append(part)
|
||||
return parts
|
||||
|
||||
|
||||
def ref_path(part: str) -> str:
|
||||
return part.rsplit(":", 1)[0] if re.search(r":\d", part) else part
|
||||
|
||||
|
||||
def config_ref(ref: str) -> list[str]:
|
||||
"""The parts of a source_ref that cite a config, option or feature file.
|
||||
|
||||
Such a part proves what the file says, never that an emulator reads it:
|
||||
melonDS.ini keys are written on ROCKNIX for a build that reads them only
|
||||
when another key is set.
|
||||
"""
|
||||
return [part for part in split_ref(ref) if _CONFIG_FILE.search(ref_path(part))]
|
||||
|
||||
|
||||
def is_feature_ref(part: str) -> bool:
|
||||
"""Whether a source_ref part cites a file that lists a menu option's values."""
|
||||
return bool(_FEATURE_FILE.search(ref_path(part)))
|
||||
@@ -288,7 +288,7 @@ def config_target(record: dict) -> tuple[str, list[str]]:
|
||||
if "." not in head or head.startswith("<"):
|
||||
# The file is the one the record installs, named by its path or,
|
||||
# when a variable spells the path, by the config file it cites.
|
||||
from scraper.shell_launchers import config_ref, is_feature_ref, ref_path
|
||||
from resolve.launcherrefs import config_ref, is_feature_ref, ref_path
|
||||
|
||||
installed = str((record.get("installs") or {}).get("path") or "").rsplit("/", 1)[-1]
|
||||
cited = [
|
||||
@@ -453,7 +453,7 @@ def config_evidence(
|
||||
values a menu offers: it goes in ``choices_from``, beside the code that
|
||||
writes the choice, and such a record needs (c) and (d) too.
|
||||
"""
|
||||
from scraper.shell_launchers import config_ref, is_feature_ref
|
||||
from resolve.launcherrefs import config_ref, is_feature_ref
|
||||
|
||||
cited = config_ref(str(record.get("source_ref") or ""))
|
||||
choices = str(record.get("choices_from") or "")
|
||||
@@ -521,7 +521,7 @@ def _profiles_or_repo(profiles: Mapping[str, dict] | None) -> Mapping[str, dict]
|
||||
|
||||
|
||||
def _cites_config(record: dict) -> bool:
|
||||
from scraper.shell_launchers import config_ref
|
||||
from resolve.launcherrefs import config_ref
|
||||
|
||||
return bool(record.get("choices_from")) or bool(config_ref(str(record.get("source_ref") or "")))
|
||||
|
||||
|
||||
@@ -1,201 +1,8 @@
|
||||
"""Region vocabulary and ordered-priority selection for pack generation.
|
||||
|
||||
A file's region: value is the region the emulator code selects it for, not the
|
||||
region of the dump. Signal standard has no field of its own. It survives only
|
||||
inside slugs whose hardware register fuses the two axes (Saturn SMPC areas).
|
||||
"""
|
||||
"""Region-ordered selection of the files a platform's cores declare."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
WORLD = "world"
|
||||
|
||||
# Two levels only: super-region -> member territories.
|
||||
REGION_TREE: dict[str, frozenset[str]] = {
|
||||
"north-america": frozenset({"canada"}),
|
||||
"latin-america": frozenset({"brazil", "mexico", "argentina"}),
|
||||
"europe": frozenset(
|
||||
{
|
||||
"uk",
|
||||
"france",
|
||||
"germany",
|
||||
"italy",
|
||||
"spain",
|
||||
"netherlands",
|
||||
"portugal",
|
||||
"greece",
|
||||
"poland",
|
||||
"russia",
|
||||
"sweden",
|
||||
"norway",
|
||||
"denmark",
|
||||
"finland",
|
||||
}
|
||||
),
|
||||
"asia": frozenset(
|
||||
{
|
||||
"japan",
|
||||
"south-korea",
|
||||
"china",
|
||||
"taiwan",
|
||||
"hong-kong",
|
||||
"singapore",
|
||||
"india",
|
||||
"asia-ntsc",
|
||||
"asia-pal",
|
||||
}
|
||||
),
|
||||
"oceania": frozenset({"australia", "new-zealand"}),
|
||||
}
|
||||
|
||||
# Hardware areas that fuse territory and signal standard, with the territories
|
||||
# the code serves through them. Mednafen's Saturn SMPC area 0x2 is "For TAIWAN
|
||||
# and PHILIPINES" and its area option offers it as "Taiwan", area 0xA as
|
||||
# "China" (mednafen/ss/ss.cpp:1119, 2363-2364 in the mednafen_stv port).
|
||||
# kronos tags the ST-V BIOS epr-19854.ic8 taiwan and mednafen_stv tags it
|
||||
# asia-ntsc: a request in either spelling has to reach the other.
|
||||
AREA_TERRITORIES: dict[str, frozenset[str]] = {
|
||||
"asia-ntsc": frozenset({"taiwan"}),
|
||||
"asia-pal": frozenset({"china"}),
|
||||
}
|
||||
|
||||
_PARENT: dict[str, str] = {
|
||||
member: parent for parent, members in REGION_TREE.items() for member in members
|
||||
}
|
||||
|
||||
REGIONS: frozenset[str] = frozenset({WORLD} | set(REGION_TREE) | set(_PARENT))
|
||||
|
||||
# Accepted on the CLI and for legacy profile values. Every territory also
|
||||
# answers to its ISO 3166-1 code: `au` alone was unknown, and the closest
|
||||
# spelling offered first was `auto`, which means world.
|
||||
ALIASES: dict[str, str] = {
|
||||
"jp": "japan",
|
||||
"ntsc-j": "japan",
|
||||
"us": "north-america",
|
||||
"usa": "north-america",
|
||||
"na": "north-america",
|
||||
"ntsc-u": "north-america",
|
||||
"eu": "europe",
|
||||
"pal": "europe",
|
||||
"kr": "south-korea",
|
||||
"korea": "south-korea",
|
||||
"auto": WORLD,
|
||||
"gb": "uk",
|
||||
"ca": "canada",
|
||||
"br": "brazil",
|
||||
"mx": "mexico",
|
||||
"ar": "argentina",
|
||||
"fr": "france",
|
||||
"de": "germany",
|
||||
"it": "italy",
|
||||
"es": "spain",
|
||||
"nl": "netherlands",
|
||||
"pt": "portugal",
|
||||
"gr": "greece",
|
||||
"pl": "poland",
|
||||
"ru": "russia",
|
||||
"se": "sweden",
|
||||
"no": "norway",
|
||||
"dk": "denmark",
|
||||
"fi": "finland",
|
||||
"cn": "china",
|
||||
"tw": "taiwan",
|
||||
"hk": "hong-kong",
|
||||
"sg": "singapore",
|
||||
"in": "india",
|
||||
"au": "australia",
|
||||
"nz": "new-zealand",
|
||||
}
|
||||
|
||||
|
||||
# Slugs a person does not write title-cased: "Asia Ntsc" read as machine text.
|
||||
LABELS: dict[str, str] = {
|
||||
"uk": "UK",
|
||||
"asia-ntsc": "Asia (NTSC)",
|
||||
"asia-pal": "Asia (PAL)",
|
||||
}
|
||||
|
||||
|
||||
def label(slug: str) -> str:
|
||||
"""A region slug in words: north-america as North America."""
|
||||
return LABELS.get(slug) or " ".join(word.title() for word in slug.split("-"))
|
||||
|
||||
|
||||
def unknown_region_message(raw: str, aliases: dict[str, str], regions: frozenset[str]) -> str:
|
||||
"""What to type instead: the closest spellings, then every short form.
|
||||
|
||||
`unknown region: 'uss'` left the user to read the source for `us`.
|
||||
"""
|
||||
import difflib
|
||||
|
||||
spelled = raw.strip()
|
||||
close = difflib.get_close_matches(spelled.lower(), [*aliases, *regions], n=3, cutoff=0.5)
|
||||
hint = f" Close matches: {', '.join(close)}." if close else ""
|
||||
return (
|
||||
f"unknown region: {spelled}.{hint} Short forms: {', '.join(aliases)}; "
|
||||
f"regions: {', '.join(sorted(regions))}"
|
||||
)
|
||||
|
||||
|
||||
def _canonical(raw: str) -> str:
|
||||
"""Map one token to a canonical region slug."""
|
||||
key = raw.strip().lower()
|
||||
key = ALIASES.get(key, key)
|
||||
if key not in REGIONS:
|
||||
raise ValueError(unknown_region_message(raw, ALIASES, REGIONS))
|
||||
return key
|
||||
|
||||
|
||||
def comparable(a: str, b: str) -> bool:
|
||||
"""True when two regions are equal, parent and child, or an area and a
|
||||
territory it serves."""
|
||||
return (
|
||||
a == b
|
||||
or _PARENT.get(a) == b
|
||||
or _PARENT.get(b) == a
|
||||
or a in AREA_TERRITORIES.get(b, ())
|
||||
or b in AREA_TERRITORIES.get(a, ())
|
||||
)
|
||||
|
||||
|
||||
def normalize_declared(raw: str | list | None) -> set[str]:
|
||||
"""Normalise a profile region: value to canonical slugs."""
|
||||
if raw is None:
|
||||
return set()
|
||||
values = raw if isinstance(raw, list) else [raw]
|
||||
return {_canonical(str(v)) for v in values}
|
||||
|
||||
|
||||
def parse_requested(raw: str) -> list[str]:
|
||||
"""Parse a comma-separated --region value into an ordered priority list."""
|
||||
out: list[str] = []
|
||||
for part in raw.split(","):
|
||||
if not part.strip():
|
||||
continue
|
||||
slug = _canonical(part)
|
||||
if slug not in out:
|
||||
out.append(slug)
|
||||
if not out:
|
||||
raise ValueError("--region requires at least one region")
|
||||
return out
|
||||
|
||||
|
||||
def rank(file_regions: set[str], requested: list[str]) -> int:
|
||||
"""Priority index of a file, lower is better.
|
||||
|
||||
Returns len(requested) when no requested region is comparable, the implicit
|
||||
lowest rank that keeps a group from ever being emptied.
|
||||
"""
|
||||
for i, req in enumerate(requested):
|
||||
if any(comparable(req, fr) for fr in file_regions):
|
||||
return i
|
||||
return len(requested)
|
||||
|
||||
|
||||
def region_tag(requested: list[str]) -> str:
|
||||
"""Pack filename tag for a requested priority list."""
|
||||
return "_".join(
|
||||
"".join(part.title() for part in slug.split("-")) for slug in requested
|
||||
)
|
||||
from model.region import WORLD, normalize_declared, rank
|
||||
|
||||
|
||||
def platform_region_index(
|
||||
@@ -1,16 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Files that left the collection, and the file that took their place.
|
||||
|
||||
A file's content address (files/?sha1=, #sha1-<12> on its card) is
|
||||
published, and a published address never stops answering. When a rebuild
|
||||
of database.json drops a sha1, the file it named is recorded here: its
|
||||
name, its last path, its hashes, the day it left and the sha1 the
|
||||
collection now holds at that path, or under that name in that folder.
|
||||
The site's lookup reads the record and answers with it.
|
||||
|
||||
The record is append-only, written by generate_db.py beside the database.
|
||||
A sha1 that comes back leaves it. `--backfill` rebuilds it from the
|
||||
history of database.json since content addresses were published.
|
||||
"""Rebuild retired.json from the history of database.json (model/retired.py).
|
||||
|
||||
Usage:
|
||||
python scripts/retired_files.py --backfill
|
||||
@@ -27,84 +16,8 @@ from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from core.cli import run_cli
|
||||
from core.artifacts import write_if_changed
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
RETIRED_FILE = REPO_ROOT / "retired.json"
|
||||
# The commit that published content addresses: 0d586ef6b, 2026-10-19.
|
||||
FIRST_ADDRESSED = "0d586ef6b"
|
||||
KEPT_FIELDS = ("name", "path", "size", "md5", "crc32", "sha256")
|
||||
|
||||
|
||||
def retired_path(database: str | Path) -> Path:
|
||||
"""The record kept beside a database file."""
|
||||
return Path(database).with_name("retired.json")
|
||||
|
||||
|
||||
def _successor(entry: dict, by_path: dict[str, str],
|
||||
by_name: dict[str, list[tuple[str, str]]]) -> str | None:
|
||||
"""The sha1 the new database holds at the entry's path, else under its
|
||||
name in the same folder, else the one file of that name: a2diskiing.zip
|
||||
was rebuilt from its recipe and filed under Apple II the same day."""
|
||||
path = str(entry.get("path", ""))
|
||||
if path in by_path:
|
||||
return by_path[path]
|
||||
named = by_name.get(str(entry.get("name", "")), [])
|
||||
folder = path.rsplit("/", 1)[0]
|
||||
beside = [sha1 for sha1, other in named if other.rsplit("/", 1)[0] == folder]
|
||||
for found in (beside, [sha1 for sha1, _other in named]):
|
||||
if len(found) == 1:
|
||||
return found[0]
|
||||
return None
|
||||
|
||||
|
||||
def retired_between(old: dict, new: dict, day: str) -> dict[str, dict]:
|
||||
"""sha1 -> record, for each file of *old* that *new* no longer holds."""
|
||||
old_files = old.get("files") or {}
|
||||
new_files = new.get("files") or {}
|
||||
by_path = {str(e.get("path", "")): sha1 for sha1, e in new_files.items()}
|
||||
by_name: dict[str, list[tuple[str, str]]] = {}
|
||||
for sha1, e in new_files.items():
|
||||
by_name.setdefault(str(e.get("name", "")), []).append((sha1, str(e.get("path", ""))))
|
||||
records = {}
|
||||
for sha1 in sorted(set(old_files) - set(new_files)):
|
||||
entry = old_files[sha1]
|
||||
record = {key: entry[key] for key in KEPT_FIELDS if entry.get(key) not in (None, "")}
|
||||
record["left"] = day
|
||||
successor = _successor(entry, by_path, by_name)
|
||||
if successor:
|
||||
record["successor"] = successor
|
||||
records[sha1] = record
|
||||
return records
|
||||
|
||||
|
||||
def merge(record: dict[str, dict], left: dict[str, dict], new: dict) -> dict[str, dict]:
|
||||
"""The record with *left* added, first departure kept, and every sha1
|
||||
the new database holds again taken out."""
|
||||
held = set(new.get("files") or {})
|
||||
merged = {sha1: entry for sha1, entry in record.items() if sha1 not in held}
|
||||
for sha1, entry in left.items():
|
||||
merged.setdefault(sha1, entry)
|
||||
return dict(sorted(merged.items()))
|
||||
|
||||
|
||||
def load(path: Path) -> dict[str, dict]:
|
||||
if not path.is_file():
|
||||
return {}
|
||||
return json.loads(path.read_text(encoding="utf-8")).get("files") or {}
|
||||
|
||||
|
||||
def dump(records: dict[str, dict]) -> str:
|
||||
return json.dumps({"schema_version": 1, "files": records}, indent=1, sort_keys=True) + "\n"
|
||||
|
||||
|
||||
def update(path: Path, old: dict, new: dict, day: str) -> int:
|
||||
"""Records what *new* dropped from *old*. Returns how many left now."""
|
||||
left = retired_between(old, new, day)
|
||||
record = load(path)
|
||||
merged = merge(record, left, new)
|
||||
if merged != record:
|
||||
write_if_changed(str(path), dump(merged))
|
||||
return len(set(left) - set(record))
|
||||
from core.paths import REPO_ROOT
|
||||
from model.retired import FIRST_ADDRESSED, RETIRED_FILE, dump, merge, retired_between
|
||||
|
||||
|
||||
def _git(*args: str) -> str:
|
||||
|
||||
@@ -57,7 +57,7 @@ from model.database import load_database
|
||||
from model.profiles import load_emulator_profiles
|
||||
from model.platforms import load_platform_config
|
||||
from model.registry import list_registered_platforms
|
||||
from torrentzip import build_torrentzip, is_torrentzip
|
||||
from core.torrentzip import build_torrentzip, is_torrentzip
|
||||
|
||||
ARCHIVES_FILE = Path(__file__).resolve().parent.parent / "recipes" / "archives.json"
|
||||
|
||||
@@ -232,7 +232,7 @@ DIGEST_CACHE = Path(__file__).resolve().parent.parent / ".cache" / "romset_diges
|
||||
# The writer's own source is part of every key: a change to how TorrentZip
|
||||
# bytes are laid out invalidates every digest it produced.
|
||||
_WRITER = hashlib.sha256(
|
||||
(Path(__file__).resolve().parent / "torrentzip.py").read_bytes()
|
||||
(Path(__file__).resolve().parent / "core" / "torrentzip.py").read_bytes()
|
||||
).hexdigest()[:16]
|
||||
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from .configgen_launchers import Launcher, Source
|
||||
from .shell_launchers import (
|
||||
from scraper.shell_launchers import (
|
||||
LauncherPatternMissing,
|
||||
Script,
|
||||
config_placement,
|
||||
|
||||
@@ -15,7 +15,7 @@ import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from .configgen_launchers import Launcher
|
||||
from .shell_launchers import (
|
||||
from scraper.shell_launchers import (
|
||||
LauncherPatternMissing,
|
||||
RepoTree,
|
||||
Script,
|
||||
|
||||
@@ -26,7 +26,7 @@ from .base_scraper import (
|
||||
requirement_entry,
|
||||
)
|
||||
from .emudeck_launchers import emulator_of_script, extract_launchers
|
||||
from .shell_launchers import RepoTree
|
||||
from scraper.shell_launchers import RepoTree
|
||||
|
||||
PLATFORM_NAME = "emudeck"
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from dataclasses import dataclass, field
|
||||
|
||||
from .configgen_launchers import Launcher
|
||||
from .rocknix_launchers import fixed_paths
|
||||
from .shell_launchers import (
|
||||
from scraper.shell_launchers import (
|
||||
LauncherPatternMissing,
|
||||
Link,
|
||||
config_placement,
|
||||
|
||||
@@ -51,7 +51,7 @@ from .es_emulators import (
|
||||
json_systems,
|
||||
system_cores,
|
||||
)
|
||||
from .shell_launchers import RepoTree
|
||||
from scraper.shell_launchers import RepoTree
|
||||
|
||||
PLATFORM_NAME = "emuelec"
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path:
|
||||
|
||||
from core.artifacts import copy_stream_atomic, write_if_changed, write_text_atomic
|
||||
from model.safeparse import parse_untrusted_xml
|
||||
from region import REGIONS, WORLD
|
||||
from model.region import REGIONS, WORLD
|
||||
from region_audit import NOINTRO
|
||||
|
||||
from .base_scraper import github_headers
|
||||
|
||||
@@ -53,7 +53,7 @@ from .configgen_launchers import (
|
||||
_assigned_name,
|
||||
end_line,
|
||||
)
|
||||
from .shell_launchers import LauncherPatternMissing, Script, source_ref
|
||||
from scraper.shell_launchers import LauncherPatternMissing, Script, source_ref
|
||||
|
||||
CONFIGGEN = "package/system/knulli-configgen/configgen/configgen"
|
||||
GENERATORS = f"{CONFIGGEN}/generators"
|
||||
|
||||
@@ -14,7 +14,7 @@ import bisect
|
||||
import re
|
||||
from collections.abc import Callable, Iterator
|
||||
|
||||
from .shell_launchers import is_feature_ref, split_ref
|
||||
from resolve.launcherrefs import is_feature_ref, split_ref
|
||||
|
||||
GENERATORS = "emulatorLauncher/Generators"
|
||||
FEATURES = ".emulationstation/es_features.cfg"
|
||||
|
||||
@@ -18,8 +18,8 @@ from dataclasses import dataclass
|
||||
from typing import TypeVar
|
||||
|
||||
from .configgen_launchers import Launcher
|
||||
from .shell_launchers import config_placement, evidence_fields
|
||||
from .shell_launchers import (
|
||||
from scraper.shell_launchers import config_placement, evidence_fields
|
||||
from scraper.shell_launchers import (
|
||||
LauncherPatternMissing,
|
||||
Link,
|
||||
RepoTree,
|
||||
|
||||
@@ -25,7 +25,7 @@ from .base_scraper import (
|
||||
requirement_entry,
|
||||
)
|
||||
from .rocknix_launchers import extract_launchers
|
||||
from .shell_launchers import RepoTree
|
||||
from scraper.shell_launchers import RepoTree
|
||||
|
||||
PLATFORM_NAME = "rocknix"
|
||||
|
||||
|
||||
@@ -59,48 +59,6 @@ def source_ref(parts: Iterable[tuple[str, Iterable[int]]]) -> str:
|
||||
)
|
||||
|
||||
|
||||
# The files a platform ships as configuration: an emulator reads them, the
|
||||
# platform's code never runs them. Batocera's .yml lists and an EmuELEC .opt
|
||||
# only offer the values a menu option takes.
|
||||
_CONFIG_FILE = re.compile(
|
||||
r"\.(?:ini|cfg|conf|rc|rc_\w+|opt|bml|toml|uae|template|yml|yaml)$", re.IGNORECASE
|
||||
)
|
||||
_FEATURE_FILE = re.compile(r"(?:^|/)es_features[^/]*$|\.opt$", re.IGNORECASE)
|
||||
|
||||
|
||||
def split_ref(ref: str) -> list[str]:
|
||||
"""The parts of a source_ref, each "path:lines", a bare line span
|
||||
continuing the path before it."""
|
||||
parts: list[str] = []
|
||||
for part in (p.strip() for p in ref.split(", ")):
|
||||
if not part:
|
||||
continue
|
||||
if re.fullmatch(r"\d+(?:-\d+)?", part) and parts:
|
||||
parts[-1] += f", {part}"
|
||||
else:
|
||||
parts.append(part)
|
||||
return parts
|
||||
|
||||
|
||||
def ref_path(part: str) -> str:
|
||||
return part.rsplit(":", 1)[0] if re.search(r":\d", part) else part
|
||||
|
||||
|
||||
def config_ref(ref: str) -> list[str]:
|
||||
"""The parts of a source_ref that cite a config, option or feature file.
|
||||
|
||||
Such a part proves what the file says, never that an emulator reads it:
|
||||
melonDS.ini keys are written on ROCKNIX for a build that reads them only
|
||||
when another key is set.
|
||||
"""
|
||||
return [part for part in split_ref(ref) if _CONFIG_FILE.search(ref_path(part))]
|
||||
|
||||
|
||||
def is_feature_ref(part: str) -> bool:
|
||||
"""Whether a source_ref part cites a file that lists a menu option's values."""
|
||||
return bool(_FEATURE_FILE.search(ref_path(part)))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Word:
|
||||
"""A shell word: as written, and with quotes removed."""
|
||||
|
||||
+3
-199
@@ -1,213 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
"""TorrentZip archive builder for MAME/FBNeo ROM sets.
|
||||
"""Check or normalize a TorrentZip archive.
|
||||
|
||||
TorrentZip is the archive format MAME romset distributions use. It fixes
|
||||
every non-content variable (member order, timestamps, compression level,
|
||||
extra fields, attributes), so the archive bytes are a pure function of the
|
||||
member names and their contents.
|
||||
|
||||
That property makes it possible to rebuild a romset ZIP that matches an
|
||||
upstream-published hash exactly, and to identify which romset revision a
|
||||
published hash refers to.
|
||||
|
||||
Usage:
|
||||
from torrentzip import build_torrentzip, identify_romset
|
||||
|
||||
data = build_torrentzip([("sp-s2.sp1", rom_bytes), ...])
|
||||
md5 = hashlib.md5(data).hexdigest()
|
||||
|
||||
CLI:
|
||||
python scripts/torrentzip.py --check bios/Arcade/Arcade/naomi2.zip
|
||||
python scripts/torrentzip.py --rebuild in.zip --output out.zip
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import functools
|
||||
import hashlib
|
||||
import io
|
||||
import struct
|
||||
import zipfile
|
||||
import zlib
|
||||
from collections.abc import Callable, Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, NamedTuple, Protocol
|
||||
|
||||
|
||||
class Source(Protocol):
|
||||
"""An open member: read in chunks, closed by its ``with`` block."""
|
||||
|
||||
def read(self, size: int = -1, /) -> bytes: ...
|
||||
def __enter__(self) -> Source: ...
|
||||
def __exit__(self, *exc: Any) -> Any: ...
|
||||
|
||||
|
||||
class Sink(Protocol):
|
||||
def write(self, data: bytes | bytearray, /) -> int: ...
|
||||
|
||||
# TorrentZip constants: 1996-12-24 23:32:00, deflate level 9
|
||||
_DOS_DATE = ((1996 - 1980) << 9) | (12 << 5) | 24
|
||||
_DOS_TIME = (23 << 11) | (32 << 5) | 0
|
||||
_COMMENT_PREFIX = "TORRENTZIPPED-"
|
||||
# Members are read and deflated this much at a time. Deflate output does not
|
||||
# depend on how its input is cut, so a 2 GiB disk image streams through in
|
||||
# the same bytes a one-shot compression gives.
|
||||
CHUNK = 16 * 1024 * 1024
|
||||
# A size or offset that does not fit 32 bits takes a ZIP64 field. No
|
||||
# TorrentZip-conformant archive needs one, so their layout is untouched.
|
||||
ZIP32_LIMIT = 0xFFFFFFFF
|
||||
_ZIP64_MARK = 0xFFFFFFFF
|
||||
|
||||
|
||||
class Written(NamedTuple):
|
||||
"""A member as the writer read it from its source."""
|
||||
|
||||
name: str
|
||||
size: int
|
||||
crc32: str
|
||||
sha1: str
|
||||
|
||||
|
||||
def zlib_ng_version(module: object = zlib) -> str | None:
|
||||
"""The zlib-ng version this interpreter deflates with, None for zlib.
|
||||
|
||||
TorrentZip bytes are the output of zlib's level-9 deflate. Stock zlib
|
||||
1.2.13 to 1.3.2 reproduces every TorrentZip archive in the collection.
|
||||
zlib-ng 2.2.4 (python.org 3.14 on Windows) reproduces 479 of 1,561 and
|
||||
2.3.3 545, and the two disagree with each other.
|
||||
"""
|
||||
version = getattr(module, "ZLIBNG_VERSION", None)
|
||||
if version:
|
||||
return str(version)
|
||||
runtime = str(getattr(module, "ZLIB_RUNTIME_VERSION", "") or "")
|
||||
return runtime if "zlib-ng" in runtime.lower() else None
|
||||
|
||||
|
||||
def _deflate(stream: Source) -> tuple[bytes, Written]:
|
||||
compressor = zlib.compressobj(9, zlib.DEFLATED, -15)
|
||||
blob = bytearray()
|
||||
crc, size, sha1 = 0, 0, hashlib.sha1()
|
||||
while chunk := stream.read(CHUNK):
|
||||
crc = zlib.crc32(chunk, crc)
|
||||
size += len(chunk)
|
||||
sha1.update(chunk)
|
||||
blob += compressor.compress(chunk)
|
||||
blob += compressor.flush()
|
||||
return bytes(blob), Written("", size, f"{crc & 0xFFFFFFFF:08x}", sha1.hexdigest())
|
||||
|
||||
|
||||
def write_torrentzip(
|
||||
sink: Sink, members: Iterable[tuple[str, Callable[[], Source]]]
|
||||
) -> list[Written]:
|
||||
"""Write a TorrentZip archive to *sink*, one member in memory at a time.
|
||||
|
||||
*members* pairs each name with a callable opening its bytes. Members are
|
||||
sorted case-insensitively by name, as the format requires. Returns what
|
||||
was read, in archive order, so a caller can check every member.
|
||||
"""
|
||||
ordered = sorted(members, key=lambda m: m[0].lower())
|
||||
central = bytearray()
|
||||
offset = 0
|
||||
written: list[Written] = []
|
||||
for name, opener in ordered:
|
||||
raw = name.encode("ascii")
|
||||
with opener() as stream:
|
||||
blob, read = _deflate(stream)
|
||||
crc = int(read.crc32, 16)
|
||||
written.append(read._replace(name=name))
|
||||
wide = read.size >= ZIP32_LIMIT or len(blob) >= ZIP32_LIMIT
|
||||
far = offset >= ZIP32_LIMIT
|
||||
local_extra = struct.pack("<HHQQ", 1, 16, read.size, len(blob)) if wide else b""
|
||||
central_extra = (
|
||||
struct.pack("<QQ", read.size, len(blob)) if wide else b""
|
||||
) + (struct.pack("<Q", offset) if far else b"")
|
||||
if central_extra:
|
||||
central_extra = struct.pack("<HH", 1, len(central_extra)) + central_extra
|
||||
sizes = (_ZIP64_MARK, _ZIP64_MARK) if wide else (len(blob), read.size)
|
||||
needed = 45 if wide or far else 20
|
||||
header = struct.pack(
|
||||
"<IHHHHHIIIHH", 0x04034B50, needed, 2, 8, _DOS_TIME, _DOS_DATE,
|
||||
crc, *sizes, len(raw), len(local_extra),
|
||||
) + raw + local_extra
|
||||
sink.write(header)
|
||||
sink.write(blob)
|
||||
central += struct.pack(
|
||||
"<IHHHHHHIIIHHHHHII", 0x02014B50, 0, needed, 2, 8, _DOS_TIME, _DOS_DATE,
|
||||
crc, *sizes, len(raw), len(central_extra), 0, 0, 0, 0,
|
||||
_ZIP64_MARK if far else offset,
|
||||
) + raw + central_extra
|
||||
offset += len(header) + len(blob)
|
||||
|
||||
cd_offset = offset
|
||||
sink.write(central)
|
||||
count = len(ordered)
|
||||
if cd_offset >= ZIP32_LIMIT or len(central) >= ZIP32_LIMIT or count >= 0xFFFF:
|
||||
end64 = cd_offset + len(central)
|
||||
sink.write(struct.pack(
|
||||
"<IQHHIIQQQQ", 0x06064B50, 44, 45, 45, 0, 0, count, count,
|
||||
len(central), cd_offset,
|
||||
))
|
||||
sink.write(struct.pack("<IIQI", 0x07064B50, 0, end64, 1))
|
||||
comment = (
|
||||
f"{_COMMENT_PREFIX}{zlib.crc32(bytes(central)) & 0xFFFFFFFF:08X}"
|
||||
).encode("ascii")
|
||||
sink.write(struct.pack(
|
||||
"<IHHHHIIH", 0x06054B50, 0, 0, min(count, 0xFFFF), min(count, 0xFFFF),
|
||||
min(len(central), _ZIP64_MARK), min(cd_offset, _ZIP64_MARK), len(comment),
|
||||
))
|
||||
sink.write(comment)
|
||||
return written
|
||||
|
||||
|
||||
def build_torrentzip(members: list[tuple[str, bytes]]) -> bytes:
|
||||
"""Build a TorrentZip archive from (name, data) members.
|
||||
|
||||
Members are sorted case-insensitively by name, as the format requires.
|
||||
Returns the complete archive bytes.
|
||||
"""
|
||||
sink = io.BytesIO()
|
||||
write_torrentzip(
|
||||
sink, [(name, functools.partial(io.BytesIO, data)) for name, data in members]
|
||||
)
|
||||
return sink.getvalue()
|
||||
|
||||
|
||||
def rebuild_torrentzip(source: str | Path) -> bytes:
|
||||
"""Read an archive and return its TorrentZip normalization."""
|
||||
with zipfile.ZipFile(source) as zf:
|
||||
members = [
|
||||
(info.filename, zf.read(info.filename))
|
||||
for info in zf.infolist()
|
||||
if not info.is_dir()
|
||||
]
|
||||
return build_torrentzip(members)
|
||||
|
||||
|
||||
def is_torrentzip(source: str | Path) -> bool:
|
||||
"""Report whether an archive already carries the TorrentZip signature."""
|
||||
with zipfile.ZipFile(source) as zf:
|
||||
return zf.comment.decode("ascii", "replace").startswith(_COMMENT_PREFIX)
|
||||
|
||||
|
||||
def identify_romset(
|
||||
recipes: dict[str, list[tuple[str, str]]],
|
||||
atoms: dict[str, bytes],
|
||||
target_md5: str,
|
||||
) -> str | None:
|
||||
"""Find which recipe rebuilds to a target archive MD5.
|
||||
|
||||
recipes maps a label (e.g. a MAME version) to a list of
|
||||
(member name, CRC32 hex) pairs, and atoms maps CRC32 hex to ROM bytes.
|
||||
Returns the matching label, or None when no recipe reproduces the hash.
|
||||
"""
|
||||
target = target_md5.lower()
|
||||
for label, recipe in recipes.items():
|
||||
if any(crc.lower() not in atoms for _, crc in recipe):
|
||||
continue
|
||||
members = [(name, atoms[crc.lower()]) for name, crc in recipe]
|
||||
if hashlib.md5(build_torrentzip(members)).hexdigest() == target:
|
||||
return label
|
||||
return None
|
||||
from core.torrentzip import is_torrentzip, rebuild_torrentzip
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -134,7 +134,7 @@ def _config_records_without_evidence(path: Path, document: object) -> list[str]:
|
||||
"""
|
||||
if not isinstance(document, dict):
|
||||
return []
|
||||
from scraper.shell_launchers import config_ref, is_feature_ref
|
||||
from resolve.launcherrefs import config_ref, is_feature_ref
|
||||
|
||||
out: list[str] = []
|
||||
for index, record in enumerate(document.get("launchers") or []):
|
||||
|
||||
+6
-6
@@ -1652,7 +1652,7 @@ def _region_pass(
|
||||
) -> tuple[set[str], list[str], dict[tuple[str, str, str], str]]:
|
||||
"""The destinations a region run withdraws, the groups no file answers,
|
||||
and the destination of each core extra."""
|
||||
import region as region_mod
|
||||
from resolve import regions as resolve_regions
|
||||
|
||||
# The builder owns pack composition, so it owns the grouping the region
|
||||
# pass reads. Grouping the platform files here and the core extras
|
||||
@@ -1676,14 +1676,14 @@ def _region_pass(
|
||||
data_registry=run.data_dir_registry,
|
||||
slot_overrides=pack_overrides,
|
||||
)
|
||||
region_index = region_mod.platform_region_index(config, run.profiles, run.target_cores)
|
||||
region_drops = region_mod.resolve_region_drops(
|
||||
region_index = resolve_regions.platform_region_index(config, run.profiles, run.target_cores)
|
||||
region_drops = resolve_regions.resolve_region_drops(
|
||||
region_groups, region_index, regions, held,
|
||||
)
|
||||
# The pack README names these: no file answers the request, so every
|
||||
# candidate stays. Reported here too, or verify reads all OK for a
|
||||
# system that has no BIOS for the region asked.
|
||||
region_fallbacks = region_mod.fallback_groups(
|
||||
region_fallbacks = resolve_regions.fallback_groups(
|
||||
region_groups, region_index, regions
|
||||
)
|
||||
return region_drops, region_fallbacks, region_extra_dests
|
||||
@@ -3528,10 +3528,10 @@ def _build_parser() -> argparse.ArgumentParser:
|
||||
def _requested_regions(args: argparse.Namespace, parser: argparse.ArgumentParser) -> list[str]:
|
||||
requested_regions: list[str] = []
|
||||
if getattr(args, "region", None):
|
||||
import region as region_mod
|
||||
from model import region
|
||||
|
||||
try:
|
||||
requested_regions = region_mod.parse_requested(args.region)
|
||||
requested_regions = region.parse_requested(args.region)
|
||||
except ValueError as exc:
|
||||
parser.error(str(exc))
|
||||
return requested_regions
|
||||
|
||||
Reference in new issue
Block a user