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:
Abdessamad Derraz committed 2026-11-18 11:39:47 +01:00
1 parent 83cfa6fd0f
commit c764d9abf1
56 files changed
+839 -804

No files matched your search

+117
View 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)
)
+47
View File
@@ -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)))
+3 -3
View File
@@ -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 "")))
+259
View File
@@ -0,0 +1,259 @@
"""Region-ordered selection of the files a platform's cores declare."""
from __future__ import annotations
from model.region import WORLD, normalize_declared, rank
def platform_region_index(
config: dict, profiles: dict, target_cores: set[str] | None = None
) -> dict[str, dict]:
"""The region index of the emulators a platform runs, nothing else.
Built over every profile, an emulator foreign to the platform voided the
filter: Pizza Boy SC, an Android app, declares bios_CD_E.bin without a
region, so the Genesis Plus GX and PicoDrive tags never counted and
`--region us` kept both CD BIOSes in the RetroArch pack.
"""
from resolve.cores import resolve_platform_cores
cores = resolve_platform_cores(config, profiles, target_cores=target_cores)
return build_region_index({n: profiles[n] for n in cores if n in profiles})
def build_region_index(profiles: dict) -> dict[str, dict]:
"""Build a region lookup from emulator profiles.
Keyed by the entry's path when present, by name otherwise. Untagged
declarations are recorded as ambiguity evidence: if the same lookup key is
both tagged and untagged, filtering keeps it instead of inventing a region.
"""
index: dict[str, dict] = {}
for emu_name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias"):
continue
for f in profile.get("files") or []:
if not isinstance(f, dict):
continue
try:
regions = normalize_declared(f.get("region"))
except ValueError as exc:
raise ValueError(
f"{emu_name}: {f.get('name', '?')}: {exc}"
) from exc
name = f.get("name", "")
path = f.get("path") or ""
# Path-keyed so same-named entries stay separate (Dolphin declares
# three IPL.bin), name-keyed so a candidate identified by name alone
# sees the union and is never dropped on ambiguity. The standalone
# layout is a path of its own: GC/EUR/IPL.bin fell through to the
# bare name and its five-region union, and was never reduced.
# An alias is another name the core reads for the same file:
# scph5552.bin, the name beetle_psx also opens for its European
# BIOS, stayed in a --region jp pack once scph5502.bin went.
aliases = {str(a) for a in f.get("aliases") or []}
priority = f.get("priority")
for key in {path, f.get("standalone_path") or "", name, *aliases} - {""}:
entry = index.setdefault(
key,
{"regions": set(), "has_untagged": False, "emulators": [],
"priorities": set()},
)
entry["regions"] |= regions
entry["priorities"].add(priority if isinstance(priority, int) else None)
if not regions:
entry["has_untagged"] = True
if emu_name not in entry["emulators"]:
entry["emulators"].append(emu_name)
return index
def lookup_regions(index: dict[str, dict], destination: str, name: str) -> set[str]:
"""Look a candidate file up in the region index.
Tries the full destination, then progressively shorter path suffixes, then
the bare name. Suffix matching bridges a platform entry whose destination
carries an extra prefix to the profile entry that declares the region.
"""
if destination:
entry = index.get(destination)
if entry:
return set() if entry.get("has_untagged") else set(entry["regions"])
parts = destination.split("/")
for i in range(1, len(parts)):
entry = index.get("/".join(parts[i:]))
if entry:
return set() if entry.get("has_untagged") else set(entry["regions"])
entry = index.get(name)
if not entry or entry.get("has_untagged"):
return set()
return set(entry["regions"])
def _index_entry(index: dict[str, dict], destination: str, name: str) -> dict | None:
"""The index entry a candidate resolves to, by the lookup_regions order."""
if destination:
entry = index.get(destination)
if entry:
return entry
parts = destination.split("/")
for i in range(1, len(parts)):
entry = index.get("/".join(parts[i:]))
if entry:
return entry
return index.get(name)
def lookup_priority(index: dict[str, dict], destination: str, name: str) -> int | None:
"""The search rank the code gives a candidate, lower first.
None when no entry declares one, or when two declarations disagree: a
rank in doubt cannot decide what to drop.
"""
entry = _index_entry(index, destination, name)
priorities = (entry or {}).get("priorities", set())
if len(priorities) != 1:
return None
return next(iter(priorities))
def _competing_ranks(
members: list[tuple[str, str]],
index: dict[str, dict],
requested: list[str],
) -> list[tuple[int, str]]:
"""Rank the members of a group that compete regionally.
Files with no declared region, and files declared world, are excluded: they
never compete and never drop.
"""
ranked: list[tuple[int, str]] = []
for destination, name in members:
regions = lookup_regions(index, destination, name)
if not regions or WORLD in regions:
continue
ranked.append((rank(regions, requested), destination))
return ranked
# Marks the group of a file no system names (extra_region_groups and the
# emulator-mode grouping both build it).
FILE_GROUP = ":file:"
def resolve_region_drops(
groups: dict[str, list[tuple[str, str]]],
index: dict[str, dict],
requested: list[str],
held: set[str] | None = None,
) -> set[str]:
"""Destinations to skip for a requested region priority list.
Per group, an exact/parent regional match beats other regional candidates.
A world candidate beats unmatched regional fallbacks the code does not
search before it, while untagged files always survive. If neither a requested nor a world candidate exists, all
regional candidates survive so filtering can never empty a group.
``held`` names the destinations the collection holds. A match it lacks
never displaces a held file: the American BIOS stays in a Japanese pack
when the Japanese one is missing, and the missing one stays reported.
"""
if not requested:
return set()
keep: set[str] = set()
drop: set[str] = set()
for group_id, members in groups.items():
if FILE_GROUP in group_id:
# A file no system names competes with nothing: it drops nothing,
# and keeping it would veto the group that does decide for the
# same path. Dolphin's GC/EUR/IPL.bin, alone as a core extra,
# kept what the GameCube group dropped for --region us. A system
# holding one file still keeps it: a group is never emptied.
continue
regional: list[tuple[int, str]] = []
world: set[str] = set()
untagged: set[str] = set()
for destination, name in members:
regions = lookup_regions(index, destination, name)
if not regions:
untagged.add(destination)
elif WORLD in regions:
world.add(destination)
else:
regional.append((rank(regions, requested), destination))
keep |= untagged | world
if not regional:
continue
matched = [(r, destination) for r, destination in regional if r < len(requested)]
winners, rivals = matched, world
if held is not None:
# A missing file answers the request but takes no held file's
# place: only held files decide what gives way.
winners = [(r, d) for r, d in matched if d in held]
rivals = world & held
if winners:
best = min(r for r, _destination in winners)
keep |= {
destination for r, destination in matched
if r == best or (r < best and destination not in (held or ()))
}
drop |= {destination for _r, destination in regional if destination not in keep}
elif rivals:
# A world file beats an unmatched regional one, unless the code
# provably looks for the regional one first: DuckStation ranks its
# PS1 images 5 to 50 and its world PS2 images 100, so a request
# for Brazil would otherwise leave it only the PS2 fallbacks.
world_ranks = [
lookup_priority(index, destination, name)
for destination, name in members
if destination in rivals
]
ranked = [rank for rank in world_ranks if rank is not None]
known = len(ranked) == len(world_ranks)
best_world = min(ranked) if known and ranked else None
for _r, destination in regional:
name = next(n for d, n in members if d == destination)
ours = lookup_priority(index, destination, name)
if best_world is not None and ours is not None and ours < best_world:
keep.add(destination)
else:
drop.add(destination)
else:
# Preserve every unmatched candidate as a visible fallback.
keep |= {destination for _r, destination in regional}
return drop - keep
def fallback_groups(
groups: dict[str, list[tuple[str, str]]],
index: dict[str, dict],
requested: list[str],
) -> list[str]:
"""Group IDs where no candidate matched, so the whole group was kept.
A world file, or one that declares no region at all, answers every
region: the C64 kernal VICE loads by default is untagged, and a group
holding it beside a Japanese and a Swedish kernal does have a BIOS for
North America. A file no system claims is a group of its own and keeps
nothing as a fallback: Dolphin's GC/EUR/IPL.bin named the GameCube as
lacking a North American BIOS the pack carries.
"""
if not requested:
return []
out: list[str] = []
for group_id, members in groups.items():
if ":file:" in group_id:
continue
ranked = _competing_ranks(members, index, requested)
served = any(
not regions or WORLD in regions
for regions in (
lookup_regions(index, destination, name)
for destination, name in members
)
)
if ranked and not served and min(r for r, _ in ranked) == len(requested):
out.append(group_id)
return sorted(out)