mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-26 11:28:51 -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
@@ -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))
|
||||
Reference in new issue
Block a user