refactor: public names for cross-module reads

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 22:59:51 +01:00
1 parent f371790dc6
commit 3853ca2f1c
254 files changed
+2955 -2969

No files matched your search

+13 -13
View File
@@ -16,7 +16,7 @@ from model.composition import GAME_DATA_TOPS
from model.profiles import load_emulator_profiles
def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]:
def copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]:
"""sha1 -> every (manufacturer, console, file name) holding a copy.
The database keeps one path per content, deduplication having left one
@@ -39,7 +39,7 @@ def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]:
return places
def _slug(manufacturer: str) -> str:
def manufacturer_slug(manufacturer: str) -> str:
return manufacturer.lower().replace(" ", "-")
@@ -65,7 +65,7 @@ def collection_paths(db: dict) -> dict[str, set[str]]:
return paths
def _group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]:
def group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]:
"""Group files by manufacturer -> console -> files.
The database keeps one path per content, and a copy filed elsewhere was
@@ -76,7 +76,7 @@ def _group_by_manufacturer(db: dict) -> dict[str, dict[str, list]]:
"""
files = db.get("files", {})
manufacturers: dict[str, dict[str, list]] = {}
for sha1, where in _copy_places(db).items():
for sha1, where in copy_places(db).items():
for manufacturer, console in sorted({(m, c) for m, c, _ in where}):
manufacturers.setdefault(manufacturer, {}).setdefault(console, []).append(files[sha1])
return _engine_sections(manufacturers)
@@ -94,7 +94,7 @@ def _engine_sections(manufacturers: dict[str, dict[str, list]]) -> dict[str, dic
the engine's name (SECTION_LABELS), its address unchanged.
"""
profiles = {key: profile for key, profile in _profiles_on_disk().items()
profiles = {key: profile for key, profile in profiles_on_disk().items()
if profile.get("type") != "alias" and profile.get("role") != "test"}
engines = _Engines(profiles, _file_readers(profiles))
out: dict[str, dict[str, list]] = {}
@@ -168,7 +168,7 @@ def _join_other_folders(out: dict[str, dict[str, list]]) -> None:
for folder in sorted(others):
top = next((t for t in out if t in GAME_DATA_TOPS and t.casefold() == folder.casefold()),
None)
if top is None or top in _PROGRAM_TOPS:
if top is None or top in PROGRAM_TOPS:
continue
sections = out[top]
target = next((c for c in sections if c.casefold() == folder.casefold()), folder)
@@ -179,27 +179,27 @@ def _join_other_folders(out: dict[str, dict[str, list]]) -> None:
*(f for f in others.pop(folder) if str(f.get("sha1", "")) not in held)]
def _profiles_on_disk() -> dict[str, dict]:
return _profiles_in(str(siteinputs.current().emulators), skip_aliases=False)
def profiles_on_disk() -> dict[str, dict]:
return profiles_in(str(siteinputs.current().emulators), skip_aliases=False)
@functools.cache
def _profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]:
def profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]:
return load_emulator_profiles(emulators_dir, skip_aliases=skip_aliases)
# (manufacturer slug, folder, sha1) -> the (manufacturer slug, console) a
# copy's card went to when the system pages file it outside its folder:
# ScummVM's engine data under Other/ScummVM, neogeo.zip under Arcade.
_card_moves: dict[tuple[str, str, str], tuple[str, str]] = {}
card_moves: dict[tuple[str, str, str], tuple[str, str]] = {}
def record_card_move(manufacturer: str, folder: str, sha1: str,
to_manufacturer: str, to_console: str) -> None:
"""Mark that the card of the copy under bios/<manufacturer>/<folder>/
sits in the section (to_manufacturer, to_console)."""
_card_moves[(_slug(manufacturer), folder, str(sha1))] = (
_slug(to_manufacturer), to_console)
card_moves[(manufacturer_slug(manufacturer), folder, str(sha1))] = (
manufacturer_slug(to_manufacturer), to_console)
# System display names. A system is named by the heading of the console
@@ -212,7 +212,7 @@ def record_card_move(manufacturer: str, folder: str, sha1: str,
# Folders that file copies by the emulator or board that loads them. Their
# headings name a program, not a system.
_PROGRAM_TOPS = frozenset({"Other", "Arcade"})
PROGRAM_TOPS = frozenset({"Other", "Arcade"})
# A section whose folder is a short name the code reads, headed with the
+1 -1
View File
@@ -49,6 +49,6 @@ NODEDUP_DIRS = {
}
def _in_nodedup_dir(path: str) -> bool:
def in_nodedup_dir(path: str) -> bool:
parts = Path(path).parts
return any(nodedup in parts for nodedup in NODEDUP_DIRS)
+10 -10
View File
@@ -15,7 +15,7 @@ except ImportError:
from core.cli import InputMissing, suggest_names
from model.alternatives import derive_member_requirements
from model.sources import source_yaml
from model.systems import _norm_system_id
from model.systems import norm_system_id
from core.paths import REPO_ROOT
@@ -24,7 +24,7 @@ from core.paths import REPO_ROOT
CONTENT_CHECKS = frozenset({"romdir", "masked_sha1"})
_emulator_profiles_cache: dict[tuple[str, bool], dict[str, dict]] = {}
emulator_profiles_cache: dict[tuple[str, bool], dict[str, dict]] = {}
class ProfileSelectionError(ValueError):
@@ -40,14 +40,14 @@ def profiles_for_systems(
other profile writes atari-2600, and an exact match built two different
packs under one file name, the second replacing the first.
"""
wanted = {_norm_system_id(sid) for sid in system_ids}
wanted = {norm_system_id(sid) for sid in system_ids}
matching = []
for name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias") or profile.get("role") == "test":
continue
if standalone and "standalone" not in profile.get("type", "libretro"):
continue
if wanted & {_norm_system_id(sid) for sid in profile.get("systems", [])}:
if wanted & {norm_system_id(sid) for sid in profile.get("systems", [])}:
matching.append(name)
return matching
@@ -73,8 +73,8 @@ def entry_serves_systems(entry: dict, profile: dict, system_ids: list[str]) -> b
serves every system of its profile, the rule a platform pack applies to
core extras.
"""
wanted = {_norm_system_id(sid) for sid in system_ids}
return bool(wanted & {_norm_system_id(sid) for sid in entry_system_ids(entry, profile)})
wanted = {norm_system_id(sid) for sid in system_ids}
return bool(wanted & {norm_system_id(sid) for sid in entry_system_ids(entry, profile)})
def select_emulator_profiles(
@@ -187,8 +187,8 @@ def load_emulator_profiles(
) -> dict[str, dict]:
"""Load all emulator YAML profiles from a directory (cached)."""
cache_key = (os.path.realpath(emulators_dir), skip_aliases)
if cache_key in _emulator_profiles_cache:
return _emulator_profiles_cache[cache_key]
if cache_key in emulator_profiles_cache:
return emulator_profiles_cache[cache_key]
if skip_aliases:
# A filter over the full set: parsed once, 534 YAML files cost 1.6 s
# every time a process asked for both variants.
@@ -197,7 +197,7 @@ def load_emulator_profiles(
for name, profile in load_emulator_profiles(emulators_dir, False).items()
if profile.get("type") != "alias"
}
_emulator_profiles_cache[cache_key] = profiles
emulator_profiles_cache[cache_key] = profiles
return profiles
if importlib.util.find_spec("yaml") is None:
# Every consumer reads {} as "this repo documents no emulator", which
@@ -223,7 +223,7 @@ def load_emulator_profiles(
_normalize_hash_fields(profile)
derive_member_requirements(profile)
profiles[f.stem] = profile
_emulator_profiles_cache[cache_key] = profiles
emulator_profiles_cache[cache_key] = profiles
return profiles
+4 -4
View File
@@ -57,11 +57,11 @@ AREA_TERRITORIES: dict[str, frozenset[str]] = {
"asia-pal": frozenset({"china"}),
}
_PARENT: dict[str, str] = {
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))
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
@@ -149,8 +149,8 @@ def comparable(a: str, b: str) -> bool:
territory it serves."""
return (
a == b
or _PARENT.get(a) == b
or _PARENT.get(b) == a
or PARENT.get(a) == b
or PARENT.get(b) == a
or a in AREA_TERRITORIES.get(b, ())
or b in AREA_TERRITORIES.get(a, ())
)
+1 -1
View File
@@ -74,7 +74,7 @@ def list_release_pack_platforms(platforms_dir: str = "platforms") -> list[str]:
VERSIONS_FILE = "data/.versions.json"
def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]:
def load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]:
path = Path(versions_path)
if not path.exists():
return {}
+6 -6
View File
@@ -6,7 +6,7 @@ the BIOS folder, each folder with the system name the OS gives it, the
extensions it lists and the core it starts by default. Those files hold the
OS's facts only. Which repository system a folder is, and which profile its
core is, is decided here, through the one alias table in model/systems.py
(`SYSTEM_ALIASES`, `_norm_system_id`) and the profiles' `cores:` lists, so a
(`SYSTEM_ALIASES`, `norm_system_id`) and the profiles' `cores:` lists, so a
change to either reaches every setup without a rescrape.
"""
@@ -16,7 +16,7 @@ import re
from dataclasses import dataclass, field
from pathlib import Path
from model.systems import _norm_system_id
from model.systems import norm_system_id
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles, preferred_profile, upstream_profile_index
from model.platforms import load_platform_config, native_layer
@@ -70,7 +70,7 @@ class SystemResolver:
The universe is every system a profile or a platform file names. A name
resolves, in this order, as one of those ids, as a name a platform's own
file gives a system (`native_system`, the folder Batocera calls `psx`),
or through `_norm_system_id`, which applies SYSTEM_ALIASES then drops the
or through `norm_system_id`, which applies SYSTEM_ALIASES then drops the
maker prefix and separators. A name nothing matches stays unresolved:
a new abbreviation goes into SYSTEM_ALIASES, never into a table here.
@@ -89,7 +89,7 @@ class SystemResolver:
def __post_init__(self) -> None:
for sid in self.ids:
self.by_norm.setdefault(_norm_system_id(sid), set()).add(sid)
self.by_norm.setdefault(norm_system_id(sid), set()).add(sid)
for members in self.by_norm.values():
best = min(members, key=lambda s: (-self.profile_use.get(s, 0), -len(s), s))
for sid in members:
@@ -123,7 +123,7 @@ class SystemResolver:
def equivalents(self, sid: str) -> set[str]:
"""Every id spelling the same machine as sid, sid included."""
return set(self.by_norm.get(_norm_system_id(sid), ())) | {sid}
return set(self.by_norm.get(norm_system_id(sid), ())) | {sid}
def _answer(self, found: set[str], basis: str) -> Resolution:
return Resolution(sorted({self.canonical(s) for s in found}), basis)
@@ -139,7 +139,7 @@ class SystemResolver:
own = self.native.get(platform, {}).get(lowered)
if own and len(own) == 1:
return self._answer(own, f"native name of {platform}")
norm = self.by_norm.get(_norm_system_id(lowered))
norm = self.by_norm.get(norm_system_id(lowered))
if norm:
return self._answer(norm, "normalized id")
claimed = [
+3 -5
View File
@@ -13,14 +13,12 @@ from pathlib import Path
from core.paths import REPO_ROOT
ROOT = REPO_ROOT
@dataclass(frozen=True)
class SiteInputs:
db: Path = ROOT / "database.json"
emulators: Path = ROOT / "emulators"
platforms: Path = ROOT / "platforms"
db: Path = REPO_ROOT / "database.json"
emulators: Path = REPO_ROOT / "emulators"
platforms: Path = REPO_ROOT / "platforms"
_current = [SiteInputs()]
+6 -6
View File
@@ -13,7 +13,7 @@ from typing import Iterable, Iterator
_REF_RE = re.compile(r"^(?P<path>[^:]+?)(?::(?P<start>\d+)(?:-(?P<end>\d+))?)?$")
_BARE_RANGE_RE = re.compile(r"^:?(\d+(?:-\d+)?)$")
_SPLIT_RE = re.compile(r"[,;]")
_ANNOTATION_RE = re.compile(r"\s*\([^)]*\)?")
ANNOTATION_RE = re.compile(r"\s*\([^)]*\)?")
_LOCATED_RE = re.compile(r"^[^\s:]+:\d+(?:-\d+)?$")
@@ -28,7 +28,7 @@ REPO_ROLES = ("source", "upstream")
_BINARY_SUFFIXES = (
".dll", ".exe", ".so", ".dylib", ".apk", ".elf", ".o", ".a", ".jar", ".dex",
)
_HEX_ADDRESS_RE = re.compile(r"\b0x[0-9a-fA-F]{2,}")
HEX_ADDRESS_RE = re.compile(r"\b0x[0-9a-fA-F]{2,}")
def is_binary_citation(path: str) -> bool:
@@ -39,7 +39,7 @@ def is_binary_citation(path: str) -> bool:
of any repository holds those bytes, so the ref can neither anchor nor
break: 77 parts of `future-pinball-fploader` alone were reported GONE.
"""
if _HEX_ADDRESS_RE.search(path):
if HEX_ADDRESS_RE.search(path):
return True
if " " not in path:
# A bare `DesktopKinect.dll` names a shipped library, never a source
@@ -108,7 +108,7 @@ def split_source_ref(ref: str) -> list[RefPart]:
"""
parts: list[RefPart] = []
for raw in split_outside_parentheses(str(ref or "")):
chunk = _trim_prose(_ANNOTATION_RE.sub("", raw).strip())
chunk = trim_prose(ANNOTATION_RE.sub("", raw).strip())
if not chunk:
continue
bare = _BARE_RANGE_RE.match(chunk)
@@ -206,7 +206,7 @@ def split_outside_parentheses(text: str) -> list[str]:
return [c for c in (chunk.strip() for chunk in chunks) if c]
def _trim_prose(chunk: str) -> str:
def trim_prose(chunk: str) -> str:
"""Drop a trailing comment written without parentheses.
`libretro.cpp:1520-1521 candidates_a1200` cites a location followed by a
@@ -445,7 +445,7 @@ def _run_spans(line: str, match: re.Match) -> tuple[list[tuple[int, int]], int]:
return spans, end
def _prose_runs(
def prose_runs(
text: str, known: frozenset[str] | set[str] = frozenset()
) -> Iterator[tuple[
int, tuple[int, int], tuple[tuple[int, int], ...], tuple[RefPart, ...], str, int
+32 -32
View File
@@ -3,27 +3,27 @@
from __future__ import annotations
from model import siteinputs
from model.collection import SECTION_LABELS, _PROGRAM_TOPS, _slug
from model.collection import SECTION_LABELS, PROGRAM_TOPS, manufacturer_slug
# (manufacturer slug, console) -> the id of the console's heading. Two
# folders spelled alike (Sega's "Mega CD" and "Mega-CD") share a slug, and
# the second heading took "mega-cd_1" while every link said "mega-cd".
_console_anchors: dict[tuple[str, str], str] = {}
console_anchors: dict[tuple[str, str], str] = {}
_boards_built = [False]
boards_built = [False]
# Every (manufacturer, console) section the system pages carry.
_section_pairs: set[tuple[str, str]] = set()
section_pairs: set[tuple[str, str]] = set()
# Normalized id -> the console sections spelled that way.
_console_sections: dict[str, set[tuple[str, str]]] = {}
# A console section by the name its heading reads (Bandai WonderSwan).
_sections_by_name: dict[str, set[tuple[str, str]]] = {}
sections_by_name: dict[str, set[tuple[str, str]]] = {}
# Emulator and engine names. A heading spelled like one (Game Engines >
# Solarus, ZC > ZC210) files that program's copies and names no system.
_program_names: set[str] = set()
known_program_names: set[str] = set()
def program_names(profiles: dict[str, dict]) -> set[str]:
@@ -48,7 +48,7 @@ def set_console_sections(
group them, or is a set of (manufacturer, console) pairs. ``programs``
are the emulator names, which never name a system.
"""
from model.systems import _norm_system_id
from model.systems import norm_system_id
pairs = (
{(mfr, console) for mfr, consoles in sections.items() for console in consoles}
@@ -59,40 +59,40 @@ def set_console_sections(
# system pages file them under Acorn (sitegen.systempages.arcade_board_sections).
makers = {mfr for mfr, _console in pairs}
pairs |= {parent for parent in SYSTEM_PARENTS.values()
if parent[0] in makers and parent[0] not in _PROGRAM_TOPS}
from core.anchors import _unique, toc_slug
if parent[0] in makers and parent[0] not in PROGRAM_TOPS}
from core.anchors import unique_anchor, toc_slug
_console_sections.clear()
_sections_by_name.clear()
_console_anchors.clear()
_section_pairs.clear()
_section_pairs.update(pairs)
sections_by_name.clear()
console_anchors.clear()
section_pairs.clear()
section_pairs.update(pairs)
by_maker: dict[str, list[str]] = {}
for mfr, console in pairs:
by_maker.setdefault(mfr, []).append(console)
for name in {_heading_name(mfr, console).casefold(), console.casefold()}:
_sections_by_name.setdefault(name, set()).add((mfr, console))
for name in {heading_name(mfr, console).casefold(), console.casefold()}:
sections_by_name.setdefault(name, set()).add((mfr, console))
# In the order the page lists them, after the page title's own id.
for mfr, consoles in by_maker.items():
used = {toc_slug(mfr)}
for console in sorted(consoles):
_console_anchors[(_slug(mfr), console)] = _unique(toc_slug(console), used)
console_anchors[(manufacturer_slug(mfr), console)] = unique_anchor(toc_slug(console), used)
for mfr, console in pairs:
spelled = console.lower().replace(" ", "-")
slug = mfr.lower().replace(" ", "-")
for key in {_norm_system_id(f"{slug}-{spelled}"), _norm_system_id(spelled)}:
for key in {norm_system_id(f"{slug}-{spelled}"), norm_system_id(spelled)}:
_console_sections.setdefault(key, set()).add((mfr, console))
_program_names.clear()
_program_names.update(name.casefold() for name in programs)
known_program_names.clear()
known_program_names.update(name.casefold() for name in programs)
_sections_installed[0] = True
# Which ids are boards depends on which have a section elsewhere.
_boards_built[0] = False
boards_built[0] = False
_sections_installed = [False]
def _ensure_console_sections() -> None:
def ensure_console_sections() -> None:
"""Read the sections from the repository when no generator installed
them, so a page rendered on its own names systems as the site does."""
if _sections_installed[0]:
@@ -100,26 +100,26 @@ def _ensure_console_sections() -> None:
import json
from model.profiles import load_emulator_profiles
from model.collection import _group_by_manufacturer
from model.collection import group_by_manufacturer
inputs = siteinputs.current()
with open(inputs.db, encoding="utf-8") as handle:
db = json.load(handle)
profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False)
set_console_sections(_group_by_manufacturer(db), program_names(profiles))
set_console_sections(group_by_manufacturer(db), program_names(profiles))
def _own_section(sys_id: str) -> tuple[str, str] | None:
def own_section(sys_id: str) -> tuple[str, str] | None:
"""The console section that is this id's own, or None.
Of two sections spelled alike (Atari and Camputers both file a Lynx),
the one under the maker the id names is kept. Two left is no answer,
and neither is a section that files a program's copies.
"""
from model.systems import _norm_system_id
from model.systems import norm_system_id
_ensure_console_sections()
places = _console_sections.get(_norm_system_id(sys_id), set())
ensure_console_sections()
places = _console_sections.get(norm_system_id(sys_id), set())
if len(places) > 1:
places = {
(mfr, console) for mfr, console in places
@@ -131,15 +131,15 @@ def _own_section(sys_id: str) -> tuple[str, str] | None:
# A folder under a program's top, named like its own page (Dinothawr) or
# like an emulator holds a program's files, not a system's.
if (
mfr in _PROGRAM_TOPS
mfr in PROGRAM_TOPS
or console.casefold() == mfr.casefold()
or _heading_name(mfr, console).casefold() in _program_names
or heading_name(mfr, console).casefold() in known_program_names
):
return None
return mfr, console
def _heading_name(mfr: str, console: str) -> str:
def heading_name(mfr: str, console: str) -> str:
"""A console heading read out of its page: the maker in front, unless
the heading already starts with it or the page is a game publisher's."""
from model.composition import GAME_DATA_TOPS
@@ -154,9 +154,9 @@ def _heading_name(mfr: str, console: str) -> str:
def system_name(sys_id: str) -> str:
"""The display name of a system id, the only one a page prints."""
sys_id = str(sys_id)
section = _own_section(sys_id)
section = own_section(sys_id)
if section is not None:
return _heading_name(*section)
return heading_name(*section)
name = SYSTEM_NAMES.get(sys_id)
if name is None:
raise KeyError(
+6 -6
View File
@@ -204,7 +204,7 @@ SYSTEM_ALIASES: dict[str, str] = {
@functools.cache
def _norm_system_id(sid: str) -> str:
def norm_system_id(sid: str) -> str:
"""Normalize system ID for cross-platform matching.
Resolves known aliases, then strips manufacturer prefixes and separators
@@ -259,10 +259,10 @@ def platform_system_names(config: dict, systems: list[str]) -> dict[str, list[st
def select_systems(systems: dict, wanted: list[str]) -> dict:
"""The systems a --system list keeps, by id or normalized id."""
norm = {_norm_system_id(s) for s in wanted}
norm = {norm_system_id(s) for s in wanted}
return {
sid: data for sid, data in systems.items()
if sid in wanted or _norm_system_id(sid) in norm
if sid in wanted or norm_system_id(sid) in norm
}
@@ -295,7 +295,7 @@ def resolve_system_arg(
by_key[_name_key(alias)] = [sid]
by_norm: dict[str, list[str]] = {}
for sid in systems:
by_norm.setdefault(_norm_system_id(sid), []).append(sid)
by_norm.setdefault(norm_system_id(sid), []).append(sid)
value = value.strip()
tokens = [value] if value.lower() in exact else value.split(",")
@@ -308,7 +308,7 @@ def resolve_system_arg(
found = (
exact.get(token.lower())
or (keyed if len(keyed) == 1 else None)
or by_norm.get(_norm_system_id(token))
or by_norm.get(norm_system_id(token))
)
if not found:
unknown.append(token)
@@ -335,6 +335,6 @@ def system_index(profiles: dict) -> dict[str, tuple[str, set[str]]]:
if p.get("type") in ("alias", "launcher") or p.get("role") == "test":
continue
for sys_id in p.get("systems", []):
key = _norm_system_id(sys_id)
key = norm_system_id(sys_id)
index.setdefault(key, (sys_id, set()))[1].add(name)
return index