chore: merge origin/main

# Conflicts:
#	install.ps1
#	install.sh
#	install/launchers/index.json
#	wiki/testing-guide.md
This commit is contained in:
Abdessamad Derraz committed 2026-11-11 19:35:01 +01:00
commit 733b059712
377 files changed
+339375 -53793

No files matched your search

+9 -6
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Build the handheld launchers in ports/ into their archives in dist/.
"""Build the handheld launchers in ports/ into their archives.
RetroBIOS.zip the PortMaster port (ports/RetroBIOS)
RetroBIOS-batocera.zip Batocera and Knulli, from Ports (ports/batocera)
@@ -17,13 +17,16 @@ the applications folder, so its top folder is the application.
install.py is copied from the repository root, and only when it is the
installer the bootstraps pin, so every launcher runs the same bytes as the
one-line command of the same commit. Members are written as the packs write
one-line command of the same commit. The site builds them at each deploy
and serves them under get/handheld/ (scripts/sitehandheld.py): they are no
release files, and are written to tmp/handheld/ by default, away from the
packs of dist/. Members are written as the packs write
theirs: fixed timestamps, sorted names, the executable bit read from the
source, so the same tree gives the same archives.
Usage:
python scripts/build_port.py
python scripts/build_port.py --output-dir tmp/port
python scripts/build_port.py --output-dir tmp/port # default: tmp/handheld
"""
from __future__ import annotations
@@ -44,7 +47,7 @@ PORT_ZIP = "RetroBIOS.zip"
BATOCERA_ZIP = "RetroBIOS-batocera.zip"
MUOS_APP = "RetroBIOS.muxapp"
TOOLS_ZIP = "RetroBIOS-tools.zip"
# Every archive a release attaches, in the order the release notes list them.
# Every launcher archive the site serves.
ARCHIVES = (PORT_ZIP, BATOCERA_ZIP, MUOS_APP, TOOLS_ZIP)
# Which release pack serves each platform, read by tui.txt offline.
PACKS_TABLE = "packs.txt"
@@ -201,8 +204,8 @@ def main() -> int:
parser = argparse.ArgumentParser(
allow_abbrev=False, description="Build the RetroBIOS handheld launchers"
)
parser.add_argument("--output-dir", type=Path, default=REPO_ROOT / "dist",
help="where the archives are written (default: dist/)")
parser.add_argument("--output-dir", type=Path, default=REPO_ROOT / "tmp" / "handheld",
help="where the archives are written (default: tmp/handheld/)")
args = parser.parse_args()
try:
with artifact_lock(str(args.output_dir)):
+17 -3
View File
@@ -282,7 +282,8 @@ def diff_targets(old: dict, new: dict) -> PlatformDiff:
def _scrape_into_copy(
module: str, source: Path, workdir: Path, timeout: int = 900
module: str, source: Path, workdir: Path, timeout: int = 900,
extra: tuple[str, ...] = (),
) -> tuple[Path, str | None]:
"""Run a scraper's own write path on a throwaway copy of *source*.
@@ -292,7 +293,7 @@ def _scrape_into_copy(
target = workdir / source.name
shutil.copyfile(source, target)
proc = subprocess.run(
[sys.executable, "-m", module, "-o", str(target)],
[sys.executable, "-m", module, "-o", str(target), *extra],
cwd=REPO_ROOT,
capture_output=True,
text=True,
@@ -327,6 +328,17 @@ def _scrapable_platforms(platforms_dir: Path) -> list[tuple[str, str, Path]]:
return rows
def rescrape_args(platforms_dir: Path, name: str) -> tuple[str, ...]:
"""What a rescrape passes so the scraper reads upstream's moving head.
A scraper that rereads the revision its platform file pins by default
(RetroBat) names the ref to move to in the registry's rescrape_args.
"""
with (platforms_dir / "_registry.yml").open(encoding="utf-8") as fh:
registry = (yaml_load(fh) or {}).get("platforms") or {}
return tuple(str(a) for a in (registry.get(name) or {}).get("rescrape_args") or ())
def check_platforms(platforms_dir: Path, workdir: Path, jobs: int) -> list[Finding]:
rows = _scrapable_platforms(platforms_dir)
findings: list[Finding] = []
@@ -334,7 +346,9 @@ def check_platforms(platforms_dir: Path, workdir: Path, jobs: int) -> list[Findi
def run(row: tuple[str, str, Path]) -> Finding:
name, module, path = row
try:
fresh, error = _scrape_into_copy(module, path, workdir)
fresh, error = _scrape_into_copy(
module, path, workdir, extra=rescrape_args(platforms_dir, name)
)
except subprocess.TimeoutExpired:
return Finding("platforms", name, ERROR, detail="scraper timed out")
if error:
+6 -9
View File
@@ -3,13 +3,13 @@
Run on the draft before publishing it, and on the published release at any
time. Every pack asset release.json names must be on the release at the sha256
SHA256SUMS.txt lists for it, as must each handheld launcher (RetroBIOS.zip
and the others build_port.py writes) the list names, the parts of a pack must add up to the download
SHA256SUMS.txt lists for it, the parts of a pack must add up to the download
size the README prints, and nothing else may be attached. The record holds
one pack for each platform the registry marks release_pack, and no other
pack. The installer and the file lists are not release files: a package pins
them from the tag, so a reader of the release page sees the packs and nothing
to puzzle over. An upload that
pack. The installer, the file lists and the handheld launchers are not
release files: a package pins the first two from the tag, and the site
serves the launchers built from its own commit (sitehandheld.py), so a
reader of the release page sees the packs and nothing to puzzle over. An upload that
failed in the loop, or a part re-uploaded from an older build, otherwise
publishes a release that `sha256sum --check` rejects for every user.
@@ -31,7 +31,6 @@ from dataclasses import dataclass
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from build_port import ARCHIVES
from check_release_assets import digests_of
from common import list_release_pack_platforms, require_directory
from largefiles import LARGE_FILES_REPO
@@ -112,9 +111,7 @@ def compare_release(
findings.append(Finding("extra", name, "attached but neither recorded nor listed"))
for name in sorted(set(recorded) - set(sums)):
findings.append(Finding("unlisted", name, f"absent from {SUMS}"))
# The handheld launchers are release files but no packs: release.json
# records packs, and the checksum list alone vouches for the launchers.
for name in sorted(set(sums) - set(recorded) - set(ARCHIVES)):
for name in sorted(set(sums) - set(recorded)):
findings.append(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json"))
wanted = {**sums, **(local_files or {})}
+713 -41
View File
@@ -316,11 +316,110 @@ def adler32_fits(file_entry: dict, path: str, db: dict | None = None) -> bool:
return chosen is None or actual == chosen
# The content tests a profile can declare in ``validation:``, each run by
# reading the candidate the way the emulator does.
CONTENT_CHECKS = frozenset({"romdir", "masked_sha1"})
def _core_checks(file_entry: dict) -> list:
validation = file_entry.get("validation")
if isinstance(validation, dict):
validation = validation.get("core", [])
return list(validation or [])
def declared_content_checks(file_entry: dict) -> set[str]:
"""The content tests the entry's code runs on a candidate."""
return set(CONTENT_CHECKS.intersection(_core_checks(file_entry)))
@functools.lru_cache(maxsize=4096)
def _romdir_verdict(path: str, size: int, mtime_ns: int, spec: str) -> bool:
from romdir import romdir_accepts # noqa: PLC0415
with open(path, "rb") as f:
data = f.read()
return romdir_accepts(data, json.loads(spec))
@functools.lru_cache(maxsize=4096)
def _masked_sha1_verdict(path: str, size: int, mtime_ns: int, spec: str) -> bool:
"""Amiberry's flash image identification (getromdatabydata, rommgr.cpp).
A CyberStorm or Blizzard PPC image carries its board configuration in
bytes 0x10-0x2f, so the table SHA-1 is taken with those bytes cleared,
over the first 0x1c000 bytes, and for a 512 KB file also over the
first 0x50000. ``reads`` lists the file sizes the code tries the
transform on and the lengths it hashes for each.
"""
rules = json.loads(spec)
reads = {int(r["size"]): [int(n) for n in r["lengths"]] for r in rules.get("reads", [])}
if size not in reads:
return False
with open(path, "rb") as f:
data = bytearray(f.read())
start, end = (int(v) for v in rules.get("zeroed", [0, 0]))
data[start:end] = bytes(max(0, min(end, len(data)) - start))
wanted = str(rules.get("sha1", "")).lower()
return any(hashlib.sha1(data[:length]).hexdigest() == wanted for length in reads[size])
def content_fits(file_entry: dict, path: str) -> bool:
"""Whether a candidate passes the content tests its entry declares.
The PCSX2 family lists any file of its BIOS folder whose ROM directory
holds RESET and ROMVER (LoadBiosVersion, pcsx2/ps2/BiosTools.cpp), with
no name and, in most forks, no size: ``validation: [romdir]`` and the
``romdir:`` spec of how that fork reads the table (romdir.py). Amiberry
names a flash image by the SHA-1 of its bytes with the configuration
cleared (``masked_sha1``). A file that cannot be read fails. An entry
declaring no content test accepts every candidate.
"""
checks = declared_content_checks(file_entry)
if not checks:
return True
try:
stat = os.stat(path)
except OSError:
return False
verdicts = {"romdir": _romdir_verdict, "masked_sha1": _masked_sha1_verdict}
for check in sorted(checks):
spec = json.dumps(file_entry.get(check) or {}, sort_keys=True)
try:
if not verdicts[check](path, stat.st_size, stat.st_mtime_ns, spec):
return False
except OSError:
return False
return True
def shape_fits(file_entry: dict, path: str, size: int | None = None) -> bool:
"""Size and content together: what a scan by shape checks per candidate."""
if size is None:
try:
size = os.path.getsize(path)
except OSError:
return False
return size_fits(file_entry, size) and content_fits(file_entry, path)
def declares_shape(file_entry: dict) -> bool:
"""Whether the entry says anything that tells one candidate from another."""
return bool(
file_entry.get("size") or file_entry.get("min_size")
or file_entry.get("max_size") or file_entry.get("size_multiple")
or declared_content_checks(file_entry)
)
def size_fits(file_entry: dict, candidate_size: int) -> bool:
"""Whether a size is one the entry declares.
``size`` is an exact size or the list of sizes the code accepts, and it
outranks a ``min_size``/``max_size`` range. Nothing declared fits all.
outranks a ``min_size``/``max_size`` range. ``size_multiple`` is a
granule the size must be a whole number of, as xemu maps any flash
image whose size is a positive multiple of 64 KiB (hw/xbox/xbox.c).
Nothing declared fits all.
"""
declared = file_entry.get("size")
if declared is not None:
@@ -330,7 +429,10 @@ def size_fits(file_entry: dict, candidate_size: int) -> bool:
high = file_entry.get("max_size")
if low is not None and candidate_size < low:
return False
return not (high is not None and candidate_size > high)
if high is not None and candidate_size > high:
return False
multiple = file_entry.get("size_multiple")
return not (multiple and candidate_size % int(multiple))
@@ -517,6 +619,10 @@ def load_platform_config(platform_name: str, platforms_dir: str = "platforms") -
roms_root = (source_yaml(f) or {}).get("roms_root")
if isinstance(roms_root, dict):
config["_roms_root"] = roms_root
with open(romfolders) as f:
folders = (source_yaml(f) or {}).get("folders")
if isinstance(folders, list):
config["_rom_folders"] = [row for row in folders if isinstance(row, dict)]
_platform_config_cache[cache_key] = config
return config
@@ -993,6 +1099,7 @@ def declared_hash_verdict(
if file_entry is not None and not (
name_match_size_ok(file_entry, os.path.getsize(candidate))
and adler32_fits(file_entry, candidate, db)
and content_fits(file_entry, candidate)
):
return "hash_mismatch"
return "data_dir"
@@ -1100,7 +1207,9 @@ def _data_dir_tail(
for candidate in hits:
if name_match_size_ok(
file_entry, os.path.getsize(candidate)
) and adler32_fits(file_entry, candidate, db):
) and adler32_fits(file_entry, candidate, db) and content_fits(
file_entry, candidate
):
return candidate
return None
@@ -1156,7 +1265,7 @@ def _resolve_agnostic(
path = entry.get("path", "")
if not path.startswith(prefix):
continue
if size_fits(file_entry, entry.get("size", 0)) and os.path.exists(path):
if os.path.exists(path) and shape_fits(file_entry, path, entry.get("size", 0)):
return path, "agnostic_fallback"
return None
@@ -1465,12 +1574,12 @@ def _by_affinity(paths: list[str], file_entry: dict, dest_hint: str) -> list[str
hint = dest_hint or file_entry.get("path") or file_entry.get("destination") or ""
wanted = _affinity_tokens(hint.rsplit("/", 1)[0] if "/" in hint else "")
owners = _owner_tokens(file_entry)
sized = any(file_entry.get(k) for k in ("size", "min_size", "max_size"))
sized = declares_shape(file_entry)
def score(path: str) -> tuple[int, bool, bool, bool, int]:
fits = 0
if sized and os.path.exists(path):
fits = int(size_fits(file_entry, os.path.getsize(path)))
fits = int(shape_fits(file_entry, path))
tokens = _affinity_tokens(path.rsplit("/", 1)[0])
# The owner's own copy ranks above any shared tree segment: NetherSX2's
# shaders/common/ beat armsx2's own fxaa.fx on two directory tokens.
@@ -1541,12 +1650,15 @@ def resolve_local_file(
layout = file_entry.get("layout_path")
if layout and layout != dest_hint:
plain = {k: v for k, v in file_entry.items() if k != "layout_path"}
# A destination outside the BIOS tree says nothing of the collection:
# EmuELEC's roms/mame/konamigv.zip is not bios/Arcade/MAME's set.
outside = file_entry.get("unprefixed") or file_entry.get("root")
answers = [
resolve_local_file(
plain, db, zip_contents, dest_hint=hint, _depth=_depth,
data_dir_registry=data_dir_registry,
)
for hint in (dest_hint, str(layout))
for hint in ((str(layout),) if outside else (dest_hint, str(layout)))
]
for found in answers:
if found[0] is not None and (
@@ -1797,7 +1909,9 @@ def resolve_local_file(
# cpc6128.rom is not cap32's 32 KB one at the same tail.
if not name_match_size_ok(
file_entry, files_db[match_sha1].get("size")
) or not adler32_fits(file_entry, path, db):
) or not adler32_fits(file_entry, path, db) or not content_fits(
file_entry, path
):
continue
return path, "path_exact"
status = _record_match_status(match_sha1)
@@ -1830,7 +1944,7 @@ def resolve_local_file(
record = files_db.get(match_sha1, {})
return name_match_size_ok(file_entry, record.get("size")) and adler32_fits(
file_entry, record.get("path", ""), db
)
) and content_fits(file_entry, record.get("path", ""))
# An entry the profile documents as unsourceable is one the collection
# cannot hold: a font that only exists inside a paid package, cheat codes
@@ -2030,7 +2144,10 @@ def resolve_local_file(
# both an Apple IIgs image and a Macintosh one. It ranks rather than
# excludes, because a present file of the wrong size is reported as
# present and untested, and dropping it would report it as absent.
sized = [c for c in named if name_match_size_ok(file_entry, c[2])]
sized = [
c for c in named
if name_match_size_ok(file_entry, c[2]) and content_fits(file_entry, c[0])
]
if sized:
named = sized
@@ -2107,7 +2224,10 @@ def resolve_local_file(
if canonical and canonical != name:
canonical_entry = {
field: file_entry[field]
for field in ("size", "min_size", "max_size", "validation")
for field in (
"size", "min_size", "max_size", "size_multiple", "validation",
*sorted(CONTENT_CHECKS),
)
if field in file_entry
}
canonical_entry["name"] = canonical
@@ -2644,27 +2764,49 @@ def expand_directory_entries(
if not any(entry.get("type") == "directory" for entry in files):
return files
# A file the profile names itself is left to that entry, in the same
# build and below the same root: MAME's libretro floppy samples share
# their path with the standalone tree RetroPie reads below roms/.
other_build = "libretro" if standalone else "standalone"
named = {
destination(entry) for entry in files if entry.get("type") != "directory"
(entry.get("root") or "", destination(entry)) for entry in files
if entry.get("type") != "directory" and entry.get("mode") != other_build
}
expanded: list[dict] = []
for entry in files:
if entry.get("type") != "directory":
expanded.append(entry)
continue
members = directory_members(db, destination(entry))
target = destination(entry)
# A directory a platform moved (platform_layouts) is the profile's
# tree at the platform's place: the collection holds it under the
# layout path, and the platform's folder proves nothing (RetroDECK
# hands MAME samplepath $bios_path/mame-sa/samples).
layout = str(entry.get("layout_path") or "") if standalone else ""
members = directory_members(db, layout) if layout else {}
if not members:
# A layout tail two trees answer (MAME's hash/) leaves the
# platform's own tail.
layout = ""
members = directory_members(db, target)
if layout and layout.strip("/") != target.strip("/"):
source, place = layout.strip("/") + "/", target.strip("/") + "/"
members = {
place + dest[len(source):]: sha1
for dest, sha1 in members.items() if dest.startswith(source)
}
if not members:
expanded.append(entry)
continue
inherited = {
key: value
for key, value in entry.items()
if key not in ("type", "standalone_path")
if key not in ("type", "standalone_path", "layout_path")
}
expanded.extend(
{**inherited, "name": dest, "path": dest, "sha1": sha1}
for dest, sha1 in members.items()
if dest not in named
if (entry.get("root") or "", dest) not in named
)
return expanded
@@ -2723,6 +2865,24 @@ OWN_BUILD_PREFIX = "ownbuild:"
SYSTEM_FILE_PREFIX = "sysfile:"
# The key, in that index, of a machine a launcher record offers.
MACHINE_KEY = "machine:"
# The platform is known: an entry read beside the content is placed in the
# roms folders a core is launched for, or named as read outside the BIOS
# folder. The tags below carry those folders.
CONTENT_SCOPE_TAG = "contentscope:"
# [core name, roms folder, (tree, path)]: a libretro core the platform
# launches for the games of that folder, which it reads beside.
CONTENT_FOLDER_PREFIX = "contentdir:"
# [emulator or core, (tree, path), system, machines, any machine,
# source_ref, build]: a standalone emulator, or a libretro core in the
# command line it is handed as content, given a roms folder as its ROM
# search path by a system's launch command.
ROM_SEARCH_PREFIX = "romsearch:"
# The frontend writes the BIOS it hands a core beside the content: the
# folder it gives the BIOS is the content's.
CONTENT_SYSTEM_TAG = "contentsystem:"
CONTENT_TAG_PREFIXES = (
CONTENT_SCOPE_TAG, CONTENT_FOLDER_PREFIX, ROM_SEARCH_PREFIX, CONTENT_SYSTEM_TAG,
)
def core_system_dirs(
@@ -2789,6 +2949,32 @@ def own_build_tags(config: dict, standalone: set[str]) -> set[str]:
}
def twin_build_names(config: dict) -> set[str]:
"""The libretro core names of emulators a platform also runs standalone
under another name.
RetroBat's es_systems.cfg offers MAME as the libretro core mame and as
the standalone mame64, two names of one profile: the platform runs it
both ways, and each build reads its own layout.
"""
standalone = {str(c) for c in config.get("standalone_cores") or []}
libretro = {str(c) for c in config.get("cores") or []} - standalone if isinstance(
config.get("cores"), list
) else set()
if not standalone or not libretro:
return set()
profiles = load_emulator_profiles(str(Path(__file__).resolve().parent.parent / "emulators"))
found: set[str] = set()
for key, profile in profiles.items():
kind = str(profile.get("type", ""))
if "libretro" not in kind or "standalone" not in kind:
continue
names = {key, *(str(c) for c in profile.get("cores") or [])}
if names & standalone:
found |= names & libretro
return found
def standalone_set(config: dict) -> set[str]:
"""The emulators a platform launches standalone, with its dual-mode ones.
@@ -2808,6 +2994,7 @@ def standalone_set(config: dict) -> set[str]:
& set(map(str, config.get("standalone_cores") or []))
}
names |= own_build_tags(config, names)
names |= {DUAL_MODE_PREFIX + n for n in twin_build_names(config)}
# The system directory each core is handed travels the same way, so
# platform_layouts places a core's files below it for every reader.
names |= {
@@ -2851,7 +3038,7 @@ def standalone_set(config: dict) -> set[str]:
EXECUTED_PREFIX + json.dumps([run.emulator, run.name, run.place, run.source_ref])
for run in executed_files(config)
}
return names
return names | content_folder_tags(config)
def merged_standalone_set(configs: Iterable[dict]) -> set[str]:
@@ -2866,7 +3053,7 @@ def merged_standalone_set(configs: Iterable[dict]) -> set[str]:
tag
for config in configs
for tag in standalone_set(config)
if not tag.startswith(CORE_DIR_PREFIX)
if not tag.startswith((CORE_DIR_PREFIX, *CONTENT_TAG_PREFIXES))
}
@@ -2985,12 +3172,14 @@ def standalone_layout_path(entry: dict, profile: dict) -> str | None:
``standalone_path`` when the entry has one. A profile with no libretro
build has one layout, so its ``path`` is that layout: UAE4All2 reads
kickstarts/kick13.rom below its working directory.
kickstarts/kick13.rom below its working directory. So does an entry only
the standalone build reads (``mode: standalone``), whose destination is
its ``path``: Dolphin's Load/Firmware/rtl_bt/ under its User directory.
"""
own = entry.get("standalone_path")
if own:
return own
if "libretro" in str(profile.get("type", "")):
if "libretro" in str(profile.get("type", "")) and entry.get("mode") != "standalone":
return None
return entry.get("path") or None
@@ -3022,11 +3211,12 @@ def standalone_bindings_for(
``systems`` are those the entry is launched for (entry_launch_systems).
"""
declared = profile.get("standalone_directories") or []
pools = profile.get("standalone_pools") or {}
from launchers import directory_handles, pool_folders, standalone_bindings # noqa: PLC0415
declared = directory_handles(profile)
pools = pool_folders(profile)
if not declared and not pools:
return {}
from launchers import standalone_bindings # noqa: PLC0415
names = {emu_name, *(str(c) for c in profile.get("cores") or [])}
layout = [
@@ -3039,8 +3229,42 @@ def standalone_bindings_for(
)
def _placed_entry(entry: dict, profile: dict, placed: tuple[str, str]) -> dict:
"""A standalone entry moved to the (tree, path) a platform reads it from."""
tree, path = placed
moved = {**entry, "standalone_path": path,
"layout_path": standalone_layout_path(entry, profile)}
if entry.get("load_from"):
# The build's own root no longer applies: RetroDECK hands
# Cemu's MLC, read from its data directory, to bios/cemu.
load_from = entry["load_from"]
moved["load_from"] = {
**(load_from if isinstance(load_from, dict) else {"libretro": load_from}),
"standalone": "system_dir",
}
if tree == "install":
# Below the roms root inside the install tree (AmberELEC's
# /storage/roms): a plain dest the platform prefix skips.
return {**moved, "unprefixed": True}
# A file the launcher runs from the roms directory (ROCKNIX's
# roms/pico-8) or an emulator folder (RetroBat's emulators/pico8)
# is relative to it, and says so.
return {**moved, "root": tree} if tree else moved
def platform_layouts(
emu_name: str, profile: dict, standalone_cores: set[str]
) -> list[tuple[dict, bool]]:
"""The layouts a platform gives an emulator: (profile, standalone?) each,
with the files read in a roms folder placed there (content_layout)."""
return [
(content_layout(emu_name, view, standalone, standalone_cores), standalone)
for view, standalone in _build_layouts(emu_name, profile, standalone_cores)
]
def _build_layouts(
emu_name: str, profile: dict, standalone_cores: set[str]
) -> list[tuple[dict, bool]]:
"""The layouts a platform gives an emulator: (profile, standalone?) each.
@@ -3073,7 +3297,14 @@ def platform_layouts(
for system in own:
family.setdefault(system, set()).update(entry_launch_systems(f, index) - own)
def bindings_of(entry: dict) -> dict[str, tuple[str, str]]:
# The systems the launcher records name: a launch for one of them reads
# the folder its record gives, every other launch the folder the records
# naming none give.
named_systems = frozenset().union(*(
h.systems for h in _handed(standalone_cores) if h.emulator in names
)) if per_system else frozenset()
def launch_systems(entry: dict) -> frozenset[str]:
systems: frozenset[str] = frozenset()
if per_system:
own = entry_launch_systems(entry, {})
@@ -3087,12 +3318,53 @@ def platform_layouts(
systems = systems.union(*(
index.get(MACHINE_KEY + _norm_system_id(s), set()) for s in own
))
return systems
def bindings_for(systems: frozenset[str]) -> dict[str, tuple[str, str]]:
if systems not in by_systems:
by_systems[systems] = standalone_bindings_for(
emu_name, profile, standalone_cores, systems
)
return by_systems[systems]
def bindings_of(entry: dict) -> dict[str, tuple[str, str]]:
return bindings_for(launch_systems(entry))
# The layout folders a search setting stands for (standalone_pools):
# bound, the launcher passes the setting and the default is not read.
from launchers import pool_folders as _pool_folders # noqa: PLC0415
pool_folders = {v.strip("/") for v in _pool_folders(profile).values()} - {""}
def passed_setting(entry: dict) -> bool:
layout = str(standalone_layout_path(entry, profile) or "")
bindings = bindings_of(entry)
return any(
folder in bindings and (layout == folder or layout.startswith(folder + "/"))
for folder in pool_folders
)
def destinations(entry: dict) -> list[tuple[str, str] | None]:
"""Each place the entry's launches read it from, in launch order.
An entry of a system a record names is read where that record puts
it. One also launched for systems no record names is read, for those
launches, where the records naming none put it: EmuELEC starts
AdvanceMAME with dir_rom roms/arcade for arcade and roms/mame for
mame and cps1-3 (advmame.sh:26-30), and an arcade set is read in both.
"""
systems = launch_systems(entry)
found = [standalone_destination(entry, profile, bindings_for(systems))]
# A system the platform's list or machines put the entry under
# stands for the entry's own ids: XRoar's coco3 is launched as coco.
own = entry_launch_systems(entry, {})
launched = (systems - own) | (own & named_systems) if systems != own else systems
if launched & named_systems and launched - named_systems:
generic = standalone_destination(entry, profile, bindings_for(frozenset()))
if generic not in found:
found.append(generic)
return found
layout_entries = [
f for f in profile.get("files") or []
if isinstance(f, dict) and standalone_layout_path(f, profile) is not None
@@ -3110,22 +3382,18 @@ def platform_layouts(
if not isinstance(f, dict) or standalone_layout_path(f, profile) is None:
files.append(f)
continue
placed = standalone_destination(f, profile, bindings_of(f))
if placed is None or placed[0] == "outside":
places = [p for p in destinations(f) if p is not None and p[0] != "outside"]
if not places:
files.append({**f, "unplaced": OUTSIDE_BIOS_FOLDER})
continue
tree, path = placed
moved = {**f, "standalone_path": path,
"layout_path": standalone_layout_path(f, profile)}
if tree == "install":
# Below the roms root inside the install tree (AmberELEC's
# /storage/roms): a plain dest the platform prefix skips.
files.append({**moved, "unprefixed": True})
continue
# A file the launcher runs from the roms directory (ROCKNIX's
# roms/pico-8) or an emulator folder (RetroBat's emulators/pico8)
# is relative to it, and says so.
files.append({**moved, "root": tree} if tree else moved)
moved = f
if f.get("bundled") and passed_setting(f):
# The copy installed with the emulator sits where the setting
# pointed before the launcher moved it: RetroBat passes MAME
# -hash bios/mame/hash (Mame64.Generator.cs:172, 177-178), and
# the hash/ beside mame.exe is no longer read.
moved = {k: v for k, v in f.items() if k != "bundled"}
files.extend(_placed_entry(moved, profile, placed) for placed in places)
standalone = {**profile, "files": files}
dual = {c.removeprefix(DUAL_MODE_PREFIX) for c in standalone_cores
if c.startswith(DUAL_MODE_PREFIX)}
@@ -3136,13 +3404,401 @@ def platform_layouts(
return [(standalone, True)]
LIBRETRO_RUNNERS = frozenset({"libretro", "retroarch", "retroarch32", "retrorun"})
def _core_key(name: str) -> str:
"""A core name as two platforms spell it alike: mame2003-plus, mame2003_plus."""
return str(name).lower().replace("-", "_")
# Set on a platform config built for one board (generate_pack, verify
# --target): a core a roms folder offers on other boards only is not placed
# there.
TARGET_KEY = "_target"
def _branch_holds(branch: str, board: str) -> bool:
"""Whether one `VARIABLE PATTERN` branch of a device case admits a board.
ROCKNIX files a board under the DEVICE value its target scraper reads,
lowercased. A branch on any other variable (PREFER_GLES) is no board
condition, and admits every board.
"""
variable, _, pattern = branch.strip().partition(" ")
if variable != "DEVICE" or not pattern.strip():
return True
import fnmatch # noqa: PLC0415
return any(
fnmatch.fnmatchcase(board.upper(), p.strip().upper()) for p in pattern.split("|")
)
def when_admits(when: str, board: str) -> bool:
"""Whether an offer's `when` holds on a board: alternatives joined by
"; ", each the branches it is nested under joined by ", "."""
return any(
all(_branch_holds(branch, board) for branch in alternative.split(", "))
for alternative in when.split("; ")
)
def offer_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]:
"""The boards on which each roms folder offers each core, by
(core key, folder), None where every board does.
ROCKNIX writes a core under a `case "${DEVICE}"` branch for the devices
it builds (`when`), and a default for a named device in board_defaults
(DEVICE=RK3326). Boards are the platform's targets, aliases included.
"""
platform = str(config.get("_key") or "")
targets = list_available_targets(
platform, str(Path(__file__).resolve().parent.parent / "platforms")
) if platform else []
names = {t["name"]: [t["name"], *t.get("aliases", [])] for t in targets}
def admitted(test: Callable[[str], bool]) -> set[str]:
return {n for board, spelled in names.items() if test(board) for n in spelled}
every = admitted(lambda _board: True)
found: dict[tuple[str, str], set[str]] = {}
for row in config.get("_rom_folders") or []:
folder = str(row.get("folder") or "")
offers = row.get("offers") or []
offered = {(o.get("emulator"), _core_key(o.get("core") or "")) for o in offers}
choices: list[tuple[dict, set[str]]] = []
if row.get("core") and (row.get("emulator"), _core_key(row["core"])) not in offered:
choices.append((row, every))
for key, spec in (row.get("board_defaults") or {}).items():
branch = str(key).replace("=", " ", 1)
choices.append((spec, admitted(functools.partial(_branch_holds, branch))))
for offer in offers:
when = str(offer.get("when") or "")
choices.append((offer, admitted(functools.partial(when_admits, when))
if when else every))
for choice, boards in choices:
if choice.get("core") and choice.get("emulator") in LIBRETRO_RUNNERS:
found.setdefault((_core_key(choice["core"]), folder), set()).update(boards)
return {
pair: None if not names or boards >= every else frozenset(boards)
for pair, boards in found.items()
}
def content_folder_boards(config: dict) -> dict[tuple[str, str], frozenset[str] | None]:
"""Each (core key, roms folder) a platform launches a libretro core for,
with the boards it does so on, None for every board."""
pairs: set[tuple[str, str]] = set()
for core, systems in (config.get("libretro_systems") or {}).items():
pairs |= {(_core_key(core), str(s)) for s in systems or []}
for system in (config.get("systems") or {}).values():
if isinstance(system, dict) and system.get("native_id"):
pairs |= {(_core_key(c), str(system["native_id"])) for c in system.get("cores") or []}
for record in config.get("launchers") or []:
if record.get("kind") == "package" and record.get("build") == "libretro":
package = str(record.get("emulator", ""))
if package.startswith("lr-mess"):
# Built with SUBTARGET=mess (lr-mess2016.sh:31): the MESS
# drivers alone, none of the arcade sets of the core it
# shares a repository with.
continue
core = _core_key(package.removeprefix("lr-"))
pairs |= {(core, str(s)) for s in record.get("systems") or []}
# Pairs from the platform's own lists hold on every board, an offer on
# the boards its frontend writes it for.
return {
**{pair: on for pair, on in offer_boards(config).items() if pair not in pairs},
**{pair: None for pair in pairs},
}
def content_folder_tags(config: dict) -> set[str]:
"""The roms folders a platform launches each libretro core for, and the
ROM search paths its commands hand emulators and cores, as tags.
A core reading its BIOS sets beside the game (MAME 2003's osd_get_path
gives FILETYPE_ROM the content directory) reads them in the folder of
the system it is launched for. The folders come from the platform's own
lists: ``libretro_systems``, every core a folder of its rom folders file
offers (its default, its board defaults, ``offers``), the cores a system
offers under its own name, and the systems a RetroPie package registers.
A platform with no roms root, or one keeping no folder per system
(RetroArch, Lakka), gives none.
"""
if config.get("inherits_from") == "emulatorjs":
# EmulatorJS writes the BIOS a frontend hands it and the game to
# the root of one filesystem (data/src/emulator.js:845, 990, 1054):
# RomM's firmware folder is beside the content.
return {CONTENT_SYSTEM_TAG}
tags = {CONTENT_SCOPE_TAG}
if outer_layout(config, ROMS_ROOT) is None:
return tags
rows = config.get("_rom_folders") or []
folders = {str(r.get("folder")) for r in rows if r.get("folder")}
boards = content_folder_boards(config)
target = config.get(TARGET_KEY)
pairs = {pair for pair, on in boards.items() if not target or on is None or target in on}
from launchers import _roms_place # noqa: PLC0415
def place(folder: str) -> list:
return list(_roms_place(config, folder) or ())
# Without a board, a core a folder offers on some boards only carries
# them, for a manifest the installer narrows to one.
tags |= {
CONTENT_FOLDER_PREFIX + json.dumps([
c, f, place(f),
None if target or (offered_on := boards.get((c, f))) is None else sorted(offered_on),
])
for c, f in pairs if f in folders
}
for row in rows:
for search in row.get("searched_by") or []:
for read in search.get("reads") or []:
if read in folders:
tags.add(ROM_SEARCH_PREFIX + json.dumps([
str(search.get("core") or search["emulator"]), place(read),
str(row["folder"]), sorted(search.get("machines") or []),
bool(search.get("any_machine")), str(search.get("source_ref", "")),
"libretro" if search.get("core") else "standalone",
]))
return tags
# The machines ES-DE runs from a folder whose command starts the game itself
# (%BASENAME%), by the folder's system: its BIOS root, the driver source
# files of its board, or a device its machines carry. A system not listed
# holds any machine.
ANY_MACHINE_POPULATIONS: dict[str, tuple[str, tuple[str, ...]]] = {
"neogeo": ("bios", ("neogeo",)),
"stv": ("bios", ("stvbios",)),
"cps": ("source", ("capcom/cps1.cpp", "capcom/cps2.cpp", "capcom/cps3.cpp")),
"cps1": ("source", ("capcom/cps1.cpp",)),
"cps2": ("source", ("capcom/cps2.cpp",)),
"cps3": ("source", ("capcom/cps3.cpp",)),
"model2": ("source", ("sega/model2.cpp",)),
"model3": ("source", ("sega/model3.cpp",)),
"daphne": ("device_source", ("devices/machine/ld",)),
"laserdisc": ("device_source", ("devices/machine/ld",)),
"gameandwatch": ("source", ("handheld/",)),
"lcdgames": ("source", ("handheld/",)),
}
@functools.lru_cache(maxsize=8)
def _arcade_relation(profile_key: str) -> dict | None:
"""games/arcade/<profile>.json: the BIOS and device sets each game set
loads, from the -listxml of the version the profile pins."""
path = Path(__file__).resolve().parent.parent / "games" / "arcade" / f"{profile_key}.json"
if not path.is_file():
return None
with path.open(encoding="utf-8") as f:
return json.load(f)
def rom_search_sets(
profile_key: str, system: str, machines: Iterable[str], any_machine: bool,
) -> frozenset[str]:
"""The sets a command reads from the ROM search path it passes.
The machines it starts, the BIOS sets on their romof chain and the
device sets with ROMs they instantiate, as the -listxml records them.
A command starting the game itself reads them for each machine its
folder holds (ANY_MACHINE_POPULATIONS).
"""
return _rom_search_sets(profile_key, system, tuple(sorted(machines)), any_machine)
@functools.lru_cache(maxsize=256)
def _rom_search_sets(
profile_key: str, system: str, machines: tuple[str, ...], any_machine: bool,
) -> frozenset[str]:
relation = _arcade_relation(profile_key)
if relation is None:
return frozenset()
bios, devices = relation.get("bios") or {}, relation.get("devices") or {}
# A clone reads the ROMs it shares with its parent from the parent's
# archive: the search path is the set and every ancestor
# (src/emu/driver.cpp:31-38, src/emu/romload.cpp:67-84 at mame0289).
parents = relation.get("parents") or {}
sources = relation.get("sources") or {}
members: set[str] = set(machines)
kind, keys = ANY_MACHINE_POPULATIONS.get(system, ("all", ())) if any_machine else ("", ())
if kind == "bios":
members |= {g for k in keys for g in bios.get(k) or []} | set(keys)
elif kind == "source":
members |= {g for src, sets in sources.items() if src.startswith(keys) for g in sets}
elif kind == "device_source":
carried = {d for src, sets in sources.items() if src.startswith(keys) for d in sets}
members |= {g for d in carried for g in devices.get(d) or []}
def used(users: list[str]) -> bool:
return kind == "all" or not members.isdisjoint(users)
found = {b for b, users in bios.items() if used(users)}
found |= {p for p, users in parents.items() if used(users)}
found |= {d for d, users in devices.items() if used(users)}
return frozenset(found | members)
def content_layout(
emu_name: str, view: dict, standalone: bool, standalone_cores: Iterable[str],
) -> dict:
"""The layout with each file read in a roms folder placed in that folder.
A libretro entry read beside the content (``load_from: content_dir``)
goes to the folder of each system the platform launches the core for,
and is named as read outside the BIOS folder where it knows none. An
entry in the folder a passed ROM search path stands for (the root of a
standalone layout, a ``libretro_pools`` folder) also goes to each folder
a command passes for a machine that reads it, and a standalone entry no
launcher record places goes there only. Outside a platform (no
CONTENT_SCOPE_TAG) the view is left as it is.
"""
tags = [t for t in standalone_cores if t.startswith(CONTENT_TAG_PREFIXES)]
if CONTENT_SYSTEM_TAG in tags and not standalone:
files = [
_without_libretro_load(f)
if isinstance(f, dict) and _content_load(f) == "content_dir"
and f.get("category") != "game_data" else f
for f in view.get("files") or []
]
return {**view, "files": files}
if CONTENT_SCOPE_TAG not in tags:
return view
names = {_core_key(n) for n in {emu_name, *(str(c) for c in view.get("cores") or [])}}
files = view.get("files") or []
out: list = []
changed = False
searches = [
json.loads(t[len(ROM_SEARCH_PREFIX):])
for t in tags if t.startswith(ROM_SEARCH_PREFIX)
]
build = "standalone" if standalone else "libretro"
searches = [s for s in searches if _core_key(s[0]) in names and s[6] == build]
def search_reads(name: str) -> list[tuple[str, str]]:
stem = name.rsplit(".", 1)[0]
return sorted({
tuple(where) for _emu, where, system, machines, any_machine, _ref, _build in searches
if where and stem in rom_search_sets(emu_name, system, machines, any_machine)
})
def roms_entry(entry: dict, tree: str, folder: str, rel: str) -> dict:
# Below the roms root inside the install tree (EmuELEC's
# /storage/roms): a plain dest the platform prefix skips, as a
# standalone entry placed there (_placed_entry).
where: dict[str, object] = (
{"unprefixed": True} if tree == "install" else {"root": ROMS_ROOT}
)
return {**entry, **where, "path": f"{folder}/{rel}", "layout_path": rel}
if not standalone:
# A place keeps the boards its core is offered on there, every board
# when one folder offers it everywhere.
on_boards: dict[tuple, set[str] | None] = {}
for core, _folder, where, on in (
json.loads(t[len(CONTENT_FOLDER_PREFIX):])
for t in tags if t.startswith(CONTENT_FOLDER_PREFIX)
):
if core not in names or not where:
continue
place = tuple(where)
known = on_boards.get(place, set())
on_boards[place] = None if on is None or known is None else known | set(on)
folders = sorted(on_boards)
# The folders a passed `-rompath` replaces the build's own search
# path with stand for these: libretro MAME hands MAME
# <system>/mame/bios unless the content's command line names
# another (retro_init.cpp Set_Path_Option, execute_game_cmd).
from launchers import pool_folders # noqa: PLC0415
pools = set(pool_folders({"standalone_pools": view.get("libretro_pools")}).values())
for f in files:
if not isinstance(f, dict):
out.append(f)
continue
if _content_load(f) != "content_dir" or f.get("category") == "game_data":
# Game data read beside the content is the game's own.
out.append(f)
parent, _, rel = str(f.get("path") or "").rpartition("/")
if searches and parent in pools and rel:
reads = search_reads(rel)
changed |= bool(reads)
out.extend(roms_entry(f, tree, folder, rel) for tree, folder in reads)
continue
changed = True
plain = _without_libretro_load(f)
if not folders:
out.append({**plain, "unplaced": OUTSIDE_BIOS_FOLDER})
continue
rel = str(f.get("path") or f.get("name") or "")
out.extend(
{**roms_entry(plain, tree, folder, rel),
**({"boards": sorted(on)} if (on := on_boards[(tree, folder)]) is not None else {})}
for tree, folder in folders
)
return {**view, "files": out} if changed else view
pools = {str(v).strip("/") for v in (view.get("standalone_pools") or {}).values()}
if not searches or "" not in pools:
return view
for f in files:
layout = (
(f.get("layout_path") or standalone_layout_path(f, view)) if isinstance(f, dict) else None
)
if not layout or "/" in layout:
out.append(f)
continue
reads = search_reads(layout)
if f.get("unplaced") != OUTSIDE_BIOS_FOLDER:
# A set a launcher record placed stays there: EmuDeck's
# mame.ini rompath is read when Steam ROM Manager starts MAME
# with no `-rompath` (tools/launchers/mame.sh), and ES-DE's
# commands read the folders they pass.
out.append(f)
held = {(f.get("root") or "", f.get("standalone_path") or "")}
extra = [
_placed_entry(f, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
]
extra = [e for e in extra if (e.get("root") or "", e["standalone_path"]) not in held]
changed |= bool(extra)
out.extend(extra)
continue
if not reads:
out.append(f)
continue
changed = True
placed = {k: v for k, v in f.items() if k != "unplaced"}
out.extend(
_placed_entry(placed, view, (tree, f"{folder}/{layout}")) for tree, folder in reads
)
return {**view, "files": out} if changed else view
def _content_load(entry: dict) -> str:
load_from = entry.get("load_from") or ""
if isinstance(load_from, dict):
load_from = load_from.get("libretro") or ""
return str(load_from)
def _without_libretro_load(entry: dict) -> dict:
"""The entry without the libretro build's load_from: its folder is now its path."""
load_from = entry.get("load_from")
rest = {k: v for k, v in entry.items() if k != "load_from"}
if isinstance(load_from, dict) and load_from.get("standalone"):
rest["load_from"] = {"standalone": load_from["standalone"]}
return rest
# What identifies a profile entry's content, carried unchanged wherever the
# entry travels (cross-reference report, core extras, second-pass copies).
# Each copy once kept its own subset: np2kai's bios.rom lost min_size and
# validation on the way and resolved to an IBM PCjr ROM of the same name.
PROFILE_IDENTITY_FIELDS = (
"sha1", "md5", "sha256", "crc32", "size", "min_size", "max_size",
"validation", "aliases", "unsourceable",
"size_multiple", "validation", *sorted(CONTENT_CHECKS), "aliases", "unsourceable",
)
@@ -3308,6 +3964,11 @@ def _platform_profiles(
}
index = upstream_profile_index(profiles)
platform = str(config.get("_key") or "")
dual_names = {str(c) for c in config.get("dual_mode_cores") or []}
def build_modes(p: dict) -> set[str]:
kind = str(p.get("type", ""))
return {mode for mode in ("standalone", "libretro") if mode in kind}
def designated(name: str) -> set[str]:
# A build the platform compiles itself (built_by) is what its
@@ -3319,10 +3980,21 @@ def _platform_profiles(
p for p in index.get(name, ())
if platform and platform in (profiles[p].get("built_by") or [])
}
if own:
return own
preferred = preferred_profile(index, name)
return {preferred} if preferred is not None else set()
if not own:
return {preferred} if preferred is not None else set()
# The own builds stand for the modes they are built in only.
# Batocera builds LRPS2 as pcsx2_libretro.so and launches
# standalone PCSX2 under the same name.
own_modes = set().union(*(build_modes(profiles[p]) for p in own))
if (
name in dual_names
and preferred is not None
and preferred not in own
and not build_modes(profiles[preferred]) & own_modes
):
own.add(preferred)
return own
result = {profile for c in core_set for profile in designated(c)}
# A name the platform launches both ways designates its libretro
+5 -1
View File
@@ -965,7 +965,11 @@ def run_once(args: argparse.Namespace, system_dir: Path, scratch: Path, state_ou
result["exit"] = exit_description(proc.returncode)
places = [(str(system_dir.resolve()), "<system>"), (str(save_dir.resolve()), "<save>")]
if args.content:
places.append((str(Path(args.content).resolve().parent), "<content>"))
folder = Path(args.content).resolve().parent
# MAME prints the folder above the content's too ("Parent path").
places.append((str(folder), "<content>"))
if folder.parent != folder.parent.parent:
places.append((str(folder.parent), "<content>/.."))
places.append((str(ROOT), "<repo>"))
for line in result.get("logs", []):
line["text"] = host_paths_hidden(line["text"], places)
+47 -2
View File
@@ -42,6 +42,7 @@ from common import (
load_database,
load_emulator_profiles,
load_platform_config,
content_fits,
name_match_size_ok,
parse_md5_list,
require_platform,
@@ -55,9 +56,11 @@ from common import (
from hashing import parse_hash_list
from launchers import (
LauncherLayer,
bound_launchers,
catalogued_model_files,
declared_destinations,
held_record,
launcher_unproven,
name_settings,
set_by,
setting_readers,
@@ -247,6 +250,7 @@ def _resolve_source(
sha1s = [sha1s]
return any(
name_match_size_ok(file_entry, db_files.get(sha1, {}).get("size"))
and content_fits(file_entry, db_files.get(sha1, {}).get("path", ""))
and _record_carries(sha1, db_files.get(sha1, {}), declared)
for sha1 in sha1s
)
@@ -1093,6 +1097,8 @@ def _settle_launcher_places(
# The --json key of the launcher reads category, beside the emulator keys.
LAUNCHER_READS_KEY = "_launcher_reads_not_held"
# The --json key of the launcher records a config file does not prove.
LAUNCHER_UNPROVEN_KEY = "_launcher_unproven"
# A package record names no file: it records what a package builds.
_NAMELESS_KINDS = frozenset({"package"})
@@ -1236,7 +1242,9 @@ def launcher_reads_not_held(
rows: list[dict] = []
for platform, config in configs.items():
by_key: dict[str, dict] = {}
for record in config.get("launchers") or []:
# A record resting on a config file it cannot prove reads nothing
# yet: it is reported apart (launcher_unproven).
for record in bound_launchers(config, profiles):
names = launcher_file_names(record)
if not names:
continue
@@ -1329,6 +1337,25 @@ def launcher_reads_not_held(
return rows
def print_launcher_unproven(rows: list[dict]) -> None:
"""The launcher records resting on a config file the code does not prove.
Neither a pack, a manifest nor a severity reads them: each is listed
with the links it lacks.
"""
if not rows:
return
platforms = sorted({r["platform"] for r in rows})
noun = "platform" if len(platforms) == 1 else "platforms"
print(f"\nLauncher records unproven: {len(rows)} across {len(platforms)} {noun}")
for platform in platforms:
print(f"\n{platform}")
for row in (r for r in rows if r["platform"] == platform):
print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}")
for link in row["missing"]:
print(f" missing {link}")
def print_launcher_reads(rows: list[dict]) -> None:
"""The launcher reads gap category, after the profile gaps.
@@ -1647,8 +1674,25 @@ def main() -> None:
db, all_profiles, registry, emulator or "",
)
unproven = [
row for row in launcher_unproven(
{
name: load_platform_config(name, args.platforms_dir)
for name in (selected or list_registered_platforms(args.platforms_dir))
},
all_profiles,
)
if not emulator or any(
emulator in LauncherLayer._profiles_named(part, all_profiles, set(all_profiles))
for part in row["emulator"].split(", ")
)
]
if args.json:
print(json.dumps({**report, LAUNCHER_READS_KEY: launcher_reads}, indent=2))
print(json.dumps(
{**report, LAUNCHER_READS_KEY: launcher_reads, LAUNCHER_UNPROVEN_KEY: unproven},
indent=2,
))
else:
if emulator:
scope = emulator
@@ -1658,6 +1702,7 @@ def main() -> None:
scope = "all emulators"
print_report(report, scope, show_clean=bool(args.emulator))
print_launcher_reads(launcher_reads)
print_launcher_unproven(unproven)
if __name__ == "__main__":
+6 -1
View File
@@ -543,7 +543,12 @@ def build_systems(
def build_arcade(directory: Path) -> dict[str, dict]:
if not directory.is_dir():
return {}
return {path.stem: _load_json(path) for path in sorted(directory.glob("*.json"))}
# The driver sources and the clone parents place a search path's sets at
# build time (common.rom_search_sets): the installer reads none of them.
return {
path.stem: {k: v for k, v in _load_json(path).items() if k not in ("sources", "parents")}
for path in sorted(directory.glob("*.json"))
}
# --- Writing ----------------------------------------------------------------
+7 -1
View File
@@ -8,7 +8,8 @@ Each table sits between `<!-- generated: NAME -->` and
`<!-- /generated: NAME -->`. What install.py knows is written from it: the
options and their arguments from its parser, the event kinds and their keys
from EVENT_KEYS, the exit codes from its sys.exit calls, the RETROBIOS_PAD
values and each route's keys from TUI_ROUTES. The prose cells (what an option
values and each route's keys from TUI_ROUTES, the handheld launchers from
sitehandheld.LAUNCHERS. The prose cells (what an option
does, when an event comes) are kept as written, matched by their row. A row
install.py gains has no prose yet: the generator names it and writes nothing,
and the row is added by hand inside the markers, its first cell holding the
@@ -45,6 +46,7 @@ import zipfile
from pathlib import Path, PurePosixPath
from typing import Callable
import sitehandheld
from artifacts import write_text_atomic
ROOT = Path(__file__).resolve().parent.parent
@@ -622,6 +624,10 @@ def render(page: str) -> str:
"card-markers": lambda _body: _table(["On the card", "System", "Files go to"],
card_marker_rows()),
"line-menu": lambda _body: line_menu(),
# Where each handheld launcher goes, written from the site's own
# description of it (sitehandheld.LAUNCHERS).
"handheld": lambda _body: "\n".join(sitehandheld.table_rows()),
"handheld-downloads": lambda _body: "\n".join(sitehandheld.download_rows()),
}
seen = []
with contextlib.ExitStack() as stack:
+94 -3
View File
@@ -39,6 +39,10 @@ sys.path.insert(0, os.path.dirname(__file__))
from alternatives import core_file_spares, settle_sets, slot_set_keys
from common import resolve_platform_cores as _platform_cores
from common import (
ROMS_ROOT,
TARGET_KEY,
_core_key,
content_folder_boards,
OUTER_ROOTS,
outer_layout,
installed_data_refs,
@@ -895,6 +899,8 @@ def generate_pack(
Returns the path to the generated ZIP, or None on failure.
"""
config = load_platform_config(platform_name, platforms_dir)
if target_name:
config = {**config, TARGET_KEY: target_name}
if zip_contents is None:
zip_contents = {}
if emu_profiles is None:
@@ -4091,8 +4097,20 @@ def _data_root_target(system: str, text: str) -> str | None:
return None
def _one_content(held: list[str], entries: dict[str, dict], emulator: str) -> list[str]:
"""The one dest a copy reads when every held dest carries the same bytes.
Unchanged when the contents differ: the name then designates nothing.
"""
if len({entries[dest].get("sha1") for dest in held}) != 1:
return held
own = [dest for dest in held if emulator in (entries[dest].get("cores") or ())]
return [min(own or held, key=lambda dest: (dest.count("/"), len(dest), dest))]
def _profile_copies(
profiles: dict[str, dict], dests: list[str], declared: list[dict],
entries: dict[str, dict] | None = None,
) -> list[dict]:
"""The standalone copies the emulator profiles document: each file with
a standalone_path, into the data_root of each system that names a place.
@@ -4105,6 +4123,10 @@ def _profile_copies(
file found by content (found_by) sits wherever the folder the user set
for the scan points: Amiberry reads its ROMs from rom_path, which
amiberry.conf moves, so its name under data_root proves nothing.
``entries`` maps each dest to its manifest entry: one file carried at
two paths with the same bytes is one source, the copy whose cores name
the emulator, else the shortest path. DuckStation's ps2_scph50006.bin
sits at the BIOS root and under pcsx2/bios/ for the libretro PS2 cores.
"""
from fnmatch import fnmatch # noqa: PLC0415
@@ -4143,6 +4165,8 @@ def _profile_copies(
or entry.get("type") == "directory" or entry.get("found_by") == "content"):
continue
held = by_tail.get(entry.get("path") or entry["name"], [])
if len(held) > 1 and entries is not None:
held = _one_content(held, entries, profile_name)
if len(held) != 1:
continue
source = held[0]
@@ -4171,8 +4195,10 @@ def _standalone_copies(
whose registry entry declares none gets none."""
if not declared:
return []
dests = [entry["dest"] for entry in manifest_files if entry.get("root") != "save"]
return _placed_copies(declared, dests) + _profile_copies(profiles, dests, declared)
kept = [entry for entry in manifest_files if entry.get("root") != "save"]
dests = [entry["dest"] for entry in kept]
entries = {entry["dest"]: entry for entry in kept}
return _placed_copies(declared, dests) + _profile_copies(profiles, dests, declared, entries)
def _stable_hashes(local_path: str, db: dict) -> dict:
@@ -4841,6 +4867,8 @@ def generate_manifest(
config = load_platform_config(platform_name, platforms_dir)
if fold_case is not None:
config = {**config, "case_insensitive_fs": fold_case}
if target_name:
config = {**config, TARGET_KEY: target_name}
if zip_contents is None:
zip_contents = {}
if emu_profiles is None:
@@ -5314,6 +5342,10 @@ def generate_manifest(
**({"downloaded_cores": downloaded} if (downloaded := _downloaded_cores(
config, emu_profiles, core_names, platforms_dir,
)) else {}),
**({"offered_boards": offered} if (offered := _offered_boards(
config, emu_profiles, core_names,
[*manifest_files, *omitted_by_destination.values()],
)) else {}),
"system_cores": system_cores,
# The names the platform itself gives its systems (Batocera's psx),
# which --system accepts beside the ids.
@@ -5468,6 +5500,65 @@ def _manifest_data_directories(
return trees
def _offered_boards(
config: dict,
profiles: dict[str, dict],
core_names: dict[str, list[str]],
entries: list[dict],
) -> dict[str, list[dict]]:
"""The roms folders each profile is offered for on some boards only,
each with those boards, aliases included, where the manifest places a
file of that profile.
ROCKNIX writes uae4arm for roms/amiga under the devices it builds it for
(emulators/package.mk:188), and a board's core list names uae4arm when
another folder offers it there. The pack builder reads the board from
the config (TARGET_KEY) and `install.py --target` reads its answer here.
A manifest built for one board needs none.
"""
if config.get(TARGET_KEY):
return {}
pairs = content_folder_boards(config)
if all(on is None for on in pairs.values()):
return {}
from launchers import _roms_place # noqa: PLC0415
by_key: dict[str, set[str]] = {}
for name, claimants in upstream_profile_index(profiles).items():
by_key.setdefault(_core_key(name), set()).update(claimants)
free = {
(profile, folder) for (core, folder), on in pairs.items() if on is None
for profile in by_key.get(core, ())
}
found: dict[tuple[str, str, str], set[str]] = {}
for (core, folder), on in pairs.items():
where = _roms_place(config, folder) if on is not None else None
if where is None:
continue
for profile in by_key.get(core, ()):
if profile in core_names and (profile, folder) not in free:
found.setdefault((profile, where[0], where[1]), set()).update(on)
# An entry below the roms root names it, one in the install tree none.
trees = {ROMS_ROOT: ROMS_ROOT, None: "install"}
placed = {
(profile, trees[entry.get("root")], str(entry.get("dest", "")).rpartition("/")[0])
for entry in entries if entry.get("root") in trees
for copy in [entry, *entry.get("alternatives", [])]
for profile in copy.get("cores") or []
}
result: dict[str, list[dict]] = {}
for (profile, tree, folder), boards in sorted(found.items()):
if not any(
p == profile and t == tree and (d == folder or d.startswith(f"{folder}/"))
for p, t, d in placed
):
continue
result.setdefault(profile, []).append(
{"root": tree, "folder": folder, "boards": sorted(boards)}
)
return result
def _downloaded_cores(
config: dict,
profiles: dict[str, dict],
@@ -5799,7 +5890,7 @@ def _pack_archives(output_dir: str) -> list[str]:
fail conformance, and injecting a manifest would change published bytes.
Every name the builder gives holds `_BIOS_Pack`, then the system tag of
a --system platform pack (`_BIOS_Pack_Playstation.zip`): build_port.py
writes its launcher archives (RetroBIOS.zip) to the same dist/, and
wrote its launcher archives (RetroBIOS.zip) to the same dist/, and
taking every ZIP rewrote them with a manifest after build_port had
printed their hashes.
"""
+61 -16
View File
@@ -95,6 +95,7 @@ import siteentries
import siteinputs
import retired_files
import siteagents
import sitediagrams
import sitestarlight
import sitesteps
from siteexports import generate_exports_page, load_export_reports
@@ -127,6 +128,7 @@ from siteguides import (
import archive_build
import release_record
import sitebootstrap
import sitehandheld
import sitemeasurements
# The Starlight project, and where its pages go inside it.
@@ -415,8 +417,8 @@ def _date_line() -> str:
def _stat(value: str, label: str) -> list[str]:
return [
markup.block_open("div", 'class="rb-stat"'),
f'<span class="rb-stat-value">{value}</span>',
f'<span class="rb-stat-label">{label}</span>',
# One line, a space between: the page text read "168/168Coverage".
f'<span class="rb-stat-value">{value}</span> <span class="rb-stat-label">{label}</span>',
"</div>",
"",
]
@@ -725,9 +727,11 @@ def get_page_title(platform_name: str, display: str) -> str:
"""What a get/ page holds, by its name: the ZIP of a setup a release
publishes one for, the files of any other. "Download KNULLI" read as
the system's own download. A setup that is also an emulator (BizHawk)
names it last: "BizHawk BIOS files" is the title of its emulator page."""
names it last: "BizHawk BIOS files" is the title of its emulator page.
A profile listing no file (the RetroArch frontend) titles its page
"... emulator", which no setup title repeats."""
kind = "BIOS pack" if has_release_pack(platform_name) else "BIOS files"
if (siteinputs.current().emulators / f"{platform_name}.yml").is_file():
if (_profiles_on_disk().get(platform_name) or {}).get("files"):
return f"{kind} for {display}"
return f"{display} {kind}"
@@ -859,6 +863,7 @@ def generate_get_page(platform_name: str) -> str:
f"[Why no ZIP?](../{NO_ZIP_FAQ})",
"",
]
lines += sitehandheld.platform_block(platform_name, _REPO_ROOT)
lines += _next_block([
f"[{display}](../platforms/{platform_name}.md#install): the folder, "
"and how to run the command on the device",
@@ -886,6 +891,11 @@ def generate_get_index() -> str:
for name in names:
display = load_platform_config(name, str(siteinputs.current().platforms)).get("platform", name)
lines.append(f"- [{get_page_title(name, display)}]({name}.md)")
# The handheld app sits with the group whose tile leads to the
# handheld guide.
if any(HANDHELD_GUIDE and tile.link == HANDHELD_GUIDE.path
for tile in GROUP_TILES.get(group, ())):
lines.append(f"- [{sitehandheld.GROUP_TITLE}]({sitehandheld.GROUP_PAGE}.md)")
lines.append("")
return "\n".join(lines)
@@ -3639,13 +3649,15 @@ def _served_line(f: dict, declared_sha1: str = "") -> str:
def _launcher_refs(config: dict) -> dict[str, list[str]]:
"""Entry name, casefolded -> each launcher record that opens it, rendered."""
from launchers import _names as launcher_names
from launchers import bound_launchers
from sitesources import launcher_ref_markdown, list_source
# Every scraper reads its launchers in the repository and at the revision
# of the list it scrapes, so `source` pins each source_ref.
# of the list it scrapes, so `source` pins each source_ref. A record a
# config file does not prove opens nothing: it is listed apart.
source = list_source(str(config.get("source") or ""))
found: dict[str, list[str]] = {}
for record in config.get("launchers") or []:
for record in bound_launchers(config):
if not isinstance(record, dict) or not record.get("source_ref"):
continue
text = (f"{_escape_tags(str(record.get('emulator', '')))} at "
@@ -3657,6 +3669,31 @@ def _launcher_refs(config: dict) -> dict[str, list[str]]:
return found
UNPROVEN_TITLE = "Launcher records a config does not prove"
def _launcher_unproven_section(config: dict) -> list[str]:
"""The platform's launcher records resting on a config the code does not prove.
A config file is proof only when the code installing it and the code
reading it are shown: these records place no file.
"""
from launchers import launcher_unproven
from sitesources import launcher_ref_markdown, list_source
rows = launcher_unproven({str(config.get("_key") or ""): config})
if not rows:
return []
source = list_source(str(config.get("source") or ""))
body = [
f"- {_escape_tags(row['emulator'])}, `{_escape_tags(row['passes_to'] or row['kind'])}` "
f"at {launcher_ref_markdown(source, row['source_ref'])}: "
f"{_escape_tags('; '.join(row['missing']))}"
for row in rows
]
return ["", *markup.details("note", f"{UNPROVEN_TITLE} ({len(rows)})", body)]
# The hash a row shows first, when the list does not say which it checks.
_ROW_HASHES = ("sha1", "md5", "sha256", "crc32")
# An untested entry whose reason is a hash the bytes do not match.
@@ -3795,8 +3832,10 @@ def _platform_file_row(f: dict, cfg_entry: dict, hash_type: str = "",
facts.append(_inline_html(_category_evidence_md(f["category_evidence"], launched)))
path = _row_path(fname, cfg_entry)
summary = (_text_html(fname) + (f"<code>{_text_html(path)}</code>" if path else "")
+ _status_chip(f))
# Spaces between name, path and status: the summary lays them out as
# columns, and the page text read "SVI603.ROMbios/Machines/...OK".
summary = " ".join([_text_html(fname), *([f"<code>{_text_html(path)}</code>"] if path else []),
_status_chip(f)])
copy = _copy_hash(shown, hashes[shown]) if shown else ""
return (f'<details class="rb-file"><summary>{summary}</summary>'
f'{"<br>".join(facts)}</details>{copy}')
@@ -3810,14 +3849,8 @@ def _platform_file_list(rows: list[str], has_path: bool, anchor: str) -> list[st
"""
lines: list[str] = []
if len(rows) >= FILTER_ROWS:
field = f"rb-files-filter-{anchor}"
lines += [
'<div class="rb-table-filter">'
f'<label for="{field}">Filter files</label>'
f'<input id="{field}" type="search" autocomplete="off" placeholder="File, path, status, hash...">'
f'<span class="rb-table-filter-count" aria-live="polite">{len(rows):,} rows</span></div>',
"",
]
lines += [siteentries.filter_box(f"rb-files-filter-{anchor}", "files",
["File", "path", "status", "hash"], len(rows)), ""]
kind = "rb-files rb-files-path" if has_path else "rb-files"
return [*lines, f'<div class="{kind}">', *rows, "</div>"]
@@ -4512,6 +4545,10 @@ def generate_handheld_guide(guide: HandheldGuide) -> str:
"",
*_guide_download(guide.uses, display, uses, None, "## Download { #download }"),
*_offline_line(guide.uses),
f"On {sitehandheld.joined(sitehandheld.group_systems(), 'or')}: "
f"[{sitehandheld.GROUP_TITLE}]"
f"(../get/{sitehandheld.GROUP_PAGE}.md).",
"",
"## Fill the card from a computer { #install }",
"",
"On Windows, note the card's letter, like **E:**. Put its BIOS folder after "
@@ -4791,6 +4828,7 @@ def generate_platform_page(
_render_platform_systems(by_system, config_files, emulator_files,
(name, display), moved, config)
)
lines.extend(_launcher_unproven_section(config))
lines.extend(["", _date_line()])
return "\n".join(lines) + "\n"
@@ -12472,6 +12510,8 @@ def _generate(args: argparse.Namespace) -> None:
(public / "robots.txt").unlink(missing_ok=True)
# The one-line commands' bootstraps, at the site's root.
sitebootstrap.write_bootstraps(public, _REPO_ROOT)
# The handheld launchers, built from the same commit (sitehandheld).
sitehandheld.write_launchers(public, _REPO_ROOT)
images_dest = public / "assets" / "images"
images_dest.mkdir(parents=True, exist_ok=True)
@@ -12484,6 +12524,9 @@ def _generate(args: argparse.Namespace) -> None:
source = Path("docs_assets") / folder
if source.is_dir():
shutil.copytree(source, public / "assets" / dest, dirs_exist_ok=True)
# The diagrams and the drawn install steps, one SVG per layout and theme.
sitediagrams.write_diagram_files(public / sitediagrams.DIAGRAM_DIR,
{**sitediagrams.figure_files(), **sitesteps.steps_files()})
demo_dest = public / "assets" / "demo"
demo_dest.mkdir(parents=True, exist_ok=True)
for name in DEMO_ASSETS:
@@ -12820,6 +12863,8 @@ def _generate(args: argparse.Namespace) -> None:
get_dir.mkdir(parents=True, exist_ok=True)
for name in platform_names:
write_if_changed(str(get_dir / f"{name}.md"), generate_get_page(name))
write_if_changed(str(get_dir / f"{sitehandheld.GROUP_PAGE}.md"),
sitehandheld.group_page(_REPO_ROOT))
write_if_changed(str(get_dir / "index.md"), generate_get_index())
print("Generating contributing page...")
+420 -25
View File
@@ -254,11 +254,327 @@ def _names(record: dict) -> list[str]:
return names
def launcher_places(config: dict) -> list[LauncherPlace]:
# How a record's passes_to names what carries the file when it names no
# config file: an option on the command line, or a libretro core option.
COMMAND_LINE = "command line"
CORE_OPTIONS = "core options"
_TAIL_WORDS = re.compile(r"\s+(?:unset|left empty)$")
_KEY_TOKEN = re.compile(r"^-{0,2}[\w.$()/\\]+$")
def config_target(record: dict) -> tuple[str, list[str]]:
"""The config a record writes its file to, and the keys it names there.
passes_to spells them as describe_keys does: "settings.ini [BIOS]
SearchDirectory, [BIOS] PathNTSCU, PathNTSCJ unset", "command line
-hard", "core option pcsx2_bios", "hatarib_tos = hatarib/<value>". A
part that reads as prose ("only if the file exists") names no key. When
passes_to names no file ("romlist coco"), the file is the one the record
installs and the whole of passes_to is the key.
"""
# A parenthesis says how the file is passed, unless a config variable
# opens it: $(FILE_PATH) is amiberry's.
text = re.sub(r"(?<!\$)\([^()]*\)", "", str(record.get("passes_to") or "")).strip()
head, _, rest = text.partition(" ")
if text.startswith(COMMAND_LINE + " "):
flag = text[len(COMMAND_LINE):].split()[0]
return COMMAND_LINE, [flag]
if text.startswith("core option "):
return CORE_OPTIONS, [text[len("core option "):].split()[0]]
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 # noqa: PLC0415
installed = str((record.get("installs") or {}).get("path") or "").rsplit("/", 1)[-1]
cited = [
ref_path(part).rsplit("/", 1)[-1]
for part in config_ref(str(record.get("source_ref") or ""))
if not is_feature_ref(part)
]
if "." in installed or (installed and not cited):
return installed, [text]
if installed and cited:
return cited[0], [text]
if record.get("build") == "libretro" and record.get("kind") == "core_option":
return CORE_OPTIONS, [head]
return "", []
keys: list[str] = []
section = ""
for piece in re.split(r",\s*", rest):
piece = _TAIL_WORDS.sub("", piece.strip())
# A section opens anywhere in a piece: "BIOS9Path [DSi] FirmwarePath".
for chunk in re.split(r"(\[[^\]]+\])", piece):
chunk = chunk.strip()
if not chunk:
continue
if chunk.startswith("[") and chunk.endswith("]"):
section = chunk
continue
# "A = B = <value>" sets every key before the value.
names = [p.strip() for p in re.split(r"\s*=\s*", chunk)]
if len(names) > 1:
names = names[:-1]
for name in names:
if not _KEY_TOKEN.match(name):
continue
key = f"{section} {name}" if section else name
if key not in keys:
keys.append(key)
return head, keys
def _read_keys(read: dict) -> dict[str, str]:
"""Each key a config_reads entry says the build reads, to its source_ref."""
found: dict[str, str] = {}
for entry in read.get("keys") or []:
spelled = entry.get("key")
for key in spelled if isinstance(spelled, list) else [spelled]:
if key:
found[str(key)] = str(entry.get("source_ref") or "")
return found
def _handle_refs(profile: dict) -> dict[str, str]:
"""The handles a profile names with the code that reads them."""
found: dict[str, str] = {}
for item in profile.get("standalone_directories") or []:
if isinstance(item, dict) and item.get("source_ref"):
handle = str(item.get("handle") or "").partition(" = ")[0]
found[handle] = str(item["source_ref"])
for handle, value in (profile.get("standalone_pools") or {}).items():
if isinstance(value, dict) and value.get("source_ref"):
found[str(handle)] = str(value["source_ref"])
return found
def directory_handles(profile: dict) -> list[str]:
"""standalone_directories as handle strings, a {handle, source_ref} item
by its handle."""
return [
str(item.get("handle") or "") if isinstance(item, dict) else str(item)
for item in profile.get("standalone_directories") or []
]
def pool_folders(profile: dict) -> dict[str, str]:
"""standalone_pools as handle to subfolder, a {folder, source_ref} value
by its folder."""
return {
str(handle): str(value.get("folder") or "") if isinstance(value, dict) else str(value)
for handle, value in (profile.get("standalone_pools") or {}).items()
}
def _reads_apply(read: dict, profile: dict, platform: str) -> bool:
"""Whether a config_reads entry describes the build ``platform`` ships.
An entry naming platforms is read at their pin_build revision or its
revision. One that names none is read at the profile's pin, the build
of every platform no entry names and with no pin_build of its own or
one pinning the same commit.
"""
named = [str(p) for p in read.get("platforms") or []]
if named:
return platform in named
# A platform an entry names has its build read there, not at the pin.
if any(platform in (r.get("platforms") or []) for r in profile.get("config_reads") or []):
return False
pin = str(profile.get("source_commit") or "")
builds = [b for b in profile.get("pin_build") or [] if b.get("platform") == platform]
return all(pin and str(b.get("value") or "").startswith(pin[:12]) for b in builds)
def _file_matches(read_file: str, file: str, record: dict) -> bool:
"""Whether a config_reads file is the one a record writes.
The entry names the file as the build finds it: a name, a glob ("*.uae",
any file the launcher passes), a path, or the flag the launcher passes
it with (amiberry's -f).
"""
from fnmatch import fnmatch # noqa: PLC0415
spelled = read_file.rsplit("/", 1)[-1].casefold()
if file and fnmatch(file.casefold(), spelled):
return True
installed = str((record.get("installs") or {}).get("path") or "").rsplit("/", 1)[-1]
if installed and fnmatch(installed.casefold(), spelled):
return True
return read_file.startswith("-") and read_file in str(record.get("passes_to") or "").split()
@dataclass(frozen=True)
class ConfigEvidence:
"""Whether a launcher record that rests on a config holds, and why not.
``config`` holds the parts of its source_ref that cite a config, option
or feature file. A record citing none, and choosing among no listed
option values, rests on code alone and holds.
"""
config: tuple[str, ...]
missing: tuple[str, ...]
readers: tuple[str, ...] = ()
@property
def proven(self) -> bool:
return not self.missing
def _named_profiles(record: dict, profiles: Mapping[str, dict], platform: str) -> list[str]:
"""The profiles a record's emulator names, a platform's own build first."""
found = []
for part in (e.strip() for e in str(record.get("emulator", "")).split(",")):
named = [
key for key, profile in profiles.items()
if profile.get("type") not in ("alias", "launcher")
and (key == part or part in {str(c) for c in profile.get("cores") or []})
]
own = [k for k in named if platform in (profiles[k].get("built_by") or [])]
found.extend(own or [k for k in named if not profiles[k].get("built_by")])
return sorted(set(found))
def config_evidence(
record: dict, profiles: Mapping[str, dict], platform: str = ""
) -> ConfigEvidence:
"""What a record citing a config file proves, link by link.
A config file is proof only when the code that installs it and the code
that reads it are shown: (a) the platform installs the file at a path
(``installs``), (b) its launch code was read for what replaces the file
or the key (``overrides``), (c) the emulator loads that file and (d)
reads each key and opens the value (``config_reads`` of its profile, at
the build the platform ships). A feature or option file only lists the
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 # noqa: PLC0415
cited = config_ref(str(record.get("source_ref") or ""))
choices = str(record.get("choices_from") or "")
if not cited and not choices:
return ConfigEvidence((), ())
missing: list[str] = []
features = [part for part in cited if is_feature_ref(part)]
if features:
missing.append("an option list cited as source, not as choices_from")
shipped = [part for part in cited if not is_feature_ref(part)]
if shipped:
installs = record.get("installs") or {}
if not (installs.get("path") and installs.get("source_ref")):
missing.append("installs: the code that puts the config in place")
if "overrides" not in record:
missing.append("overrides: the launch code read for what replaces it")
file, keys = config_target(record)
if not keys:
missing.append("a key the config hands the file to")
readers: list[str] = []
uncovered = list(keys)
loaded = False
named = _named_profiles(record, profiles, platform)
if file == CORE_OPTIONS:
# A core option is read by the core RetroArch runs, not by the
# frontend a record names (RetroDECK's retroarch component).
named = [k for k in named if "libretro" in str(profiles[k].get("type") or "")]
for key in named or sorted(profiles):
profile = profiles[key]
handles = _handle_refs(profile)
for read in profile.get("config_reads") or []:
if not _reads_apply(read, profile, platform):
continue
if not _file_matches(str(read.get("file") or ""), file, record):
continue
loaded = True
known = _read_keys(read)
before = len(uncovered)
uncovered = [k for k in uncovered if not (known.get(k) or handles.get(k))]
if len(uncovered) < before and key not in readers:
readers.append(key)
if not loaded:
missing.append(f"config_reads: an emulator that loads {file or 'the config'}")
elif uncovered:
missing.append("config_reads: no read of " + ", ".join(uncovered))
return ConfigEvidence(tuple(cited or [choices]), tuple(missing), tuple(readers))
_DEFAULT_PROFILES: dict[str, dict] | None = None
def _profiles_or_repo(profiles: Mapping[str, dict] | None) -> Mapping[str, dict]:
"""The profiles given, else this repository's, read once."""
global _DEFAULT_PROFILES # noqa: PLW0603
if profiles is not None:
return profiles
if _DEFAULT_PROFILES is None:
from pathlib import Path # noqa: PLC0415
from common import load_emulator_profiles # noqa: PLC0415
_DEFAULT_PROFILES = load_emulator_profiles(
str(Path(__file__).resolve().parent.parent / "emulators")
)
return _DEFAULT_PROFILES
def _cites_config(record: dict) -> bool:
from scraper.shell_launchers import config_ref # noqa: PLC0415
return bool(record.get("choices_from")) or bool(config_ref(str(record.get("source_ref") or "")))
def bound_launchers(config: dict, profiles: Mapping[str, dict] | None = None) -> list[dict]:
"""The launcher records a platform's packs, manifests and reports consume.
A record resting on a config file binds only when config_evidence holds
for it. The repository's profiles are read only when a record cites one.
"""
records = [r for r in config.get("launchers") or [] if isinstance(r, dict)]
if not any(_cites_config(r) for r in records):
return records
known = _profiles_or_repo(profiles)
platform = str(config.get("_key") or "")
return [r for r in records if config_evidence(r, known, platform).proven]
def launcher_unproven(
configs: Mapping[str, dict], profiles: Mapping[str, dict] | None = None
) -> list[dict]:
"""The records resting on a config file whose evidence does not hold.
One row per record, with the config parts it cites and each missing
link. Reported apart: no severity, count or exit code reads it.
"""
rows: list[dict] = []
for platform, config in configs.items():
records = [r for r in config.get("launchers") or [] if isinstance(r, dict)]
if not any(_cites_config(r) for r in records):
continue
known = _profiles_or_repo(profiles)
for index, record in enumerate(records):
evidence = config_evidence(record, known, str(config.get("_key") or platform))
if evidence.proven:
continue
rows.append({
"platform": platform,
"index": index,
"emulator": str(record.get("emulator", "")),
"kind": str(record.get("kind", "")),
"passes_to": str(record.get("passes_to") or ""),
"source_ref": str(record.get("source_ref", "")),
"config": list(evidence.config),
"missing": list(evidence.missing),
})
return rows
def launcher_places(
config: dict, profiles: Mapping[str, dict] | None = None
) -> list[LauncherPlace]:
"""Every place a platform's launchers open a named file from."""
base = str(config.get("base_destination") or "bios")
places: list[LauncherPlace] = []
for record in config.get("launchers") or []:
for record in bound_launchers(config, profiles):
kind = record.get("kind")
if kind not in PLACE_KINDS:
continue
@@ -312,8 +628,16 @@ def launcher_places(config: dict) -> list[LauncherPlace]:
# component scripts $bios_path.
BIOS_ROOT_VARIABLES = ("$biosdir", "$home/RetroPie/BIOS", "${biosPath}", "$bios_path")
# The kinds that hand an emulator a whole directory.
HANDED_KINDS = ("links", "passes_path")
# The name a platform's launch code gives its roms root: RetroDECK's
# component scripts write $roms_path (retrodeck_launchers), the setting whose
# default is the roms root (config/retrodeck/retrodeck.json:5), RetroPie's
# scriptmodules $romdir (retropie_packages.sh:47-49).
ROMS_ROOT_VARIABLES = ("$roms_path", "${roms_path}", "$romdir", "${romdir}")
# The kinds that hand an emulator a whole directory. A scans_dir record sets
# the directory the emulator picks its file from: ROCKNIX writes ARMSX2's
# [Folders] Bios, EmuDeck PCSX2's.
HANDED_KINDS = ("links", "passes_path", "scans_dir")
# How a launcher record says the platform starts the emulator in a directory
# (retropie_launchers._working_directory), and the handle a profile gives
@@ -339,24 +663,46 @@ INSTALL_TREE = "install"
# A folder of neither tree, which no pack and no installer can fill.
OUTSIDE_TREE = "outside"
Place = tuple[str, str]
# The binding key of a search list standing for the whole layout: the
# directories hold the layout's files themselves (XRoar's ROMs, MAME's sets),
# never its subfolders.
SEARCHED_FILES = "*"
_HOME = re.compile(r"^(?:\$\{HOME\}|\$HOME|\$home|~)(?=/|$)")
# Flatpak sets XDG_DATA_HOME to ~/.var/app/<id>/data inside the sandbox.
_FLATPAK_DATA = re.compile(r"^~/\.var/app/[^/]+/data(?=/|$)")
def normalize_handle(token: str) -> str:
def normalize_handle(token: str, home: str = "") -> str:
"""One spelling for a path, setting or function a launcher record names.
``$home``, ``$HOME``, ``${HOME}`` and ``~`` are one directory, and a
Flatpak's data directory is its ``$XDG_DATA_HOME``.
Flatpak's data directory is its ``$XDG_DATA_HOME``. ``home`` is the
platform's home directory spelled out (``home_directory``): EmuELEC
links /storage/.local/share/flycast, Flycast's ~/.local/share/flycast.
"""
token = token.strip().strip("\"'").rstrip(",;").rstrip("/")
token = token.removesuffix("()")
home = home.rstrip("/")
if home and _below(token, home) is not None:
token = "~" + token[len(home):]
token = _HOME.sub("~", token)
return _FLATPAK_DATA.sub("$XDG_DATA_HOME", token)
_INI_KEY = re.compile(r"(\[[^\]\s]+\])\s+([^\s,;=()]+)")
def ini_keys(passes_to: str) -> frozenset[str]:
"""The INI keys a record's ``passes_to`` writes, as "[Section] Key".
A key alone is ambiguous: PCSX2 reads its BIOS folder from [Folders]
Bios and the image name from [Filenames] BIOS. A profile declares the
key it resolves a folder from in that spelling ("[Folders] Bios = bios").
"""
return frozenset(f"{section} {key}" for section, key in _INI_KEY.findall(passes_to))
def _folder_in_bios(directory: str, base: str) -> str | None:
"""A directory relative to the BIOS root, None when it lies outside."""
relative = _bios_relative(directory, base)
@@ -423,13 +769,29 @@ def native_systems(config: dict) -> dict[str, str]:
return found
def _listed_directories(raw: str) -> list[str] | None:
"""The directories of a colon-separated search path, None for one directory.
# How the launcher extractors spell the folder holding the launched game:
# RetroBat's Path.GetDirectoryName(rom) (retrobat_launchers._KNOWN), KNULLI's
# os.path.dirname(rom) and its software list folder (mameGenerator.py:113-116).
GAME_FOLDERS = ("<rom directory>", "<romDirname>", "<softDir>")
XRoar's rompath is such a list (RetroDECK writes four directories), each
entry a path or a variable spelling one. A Windows drive letter or a
backslash means a single path.
def _listed_directories(raw: str) -> list[str] | None:
"""The directories of a search path, None for one directory.
XRoar's rompath is a colon-separated list (RetroDECK writes four
directories), each entry a path or a variable spelling one. A Windows
drive letter or a backslash means a single path. MAME splits its search
paths on semicolons whatever the system (src/emu/fileio.cpp:53-58):
RetroBat passes `-rp bios;<rom directory>`, KNULLI `-rompath
<romDirname>;/userdata/bios/mame;/userdata/bios`. The game's own folder
is no folder a pack fills, so it gives no directory.
"""
if ";" in raw:
parts = [p.strip() for p in raw.split(";") if p.strip()]
kept = [p for p in parts if p not in GAME_FOLDERS]
if kept and all(not re.search(r"[\s,<>]", p) for p in kept):
return kept
return None
if ":" not in raw or "\\" in raw or re.match(r"^[A-Za-z]:", raw):
return None
parts = [p.strip() for p in raw.split(":")]
@@ -438,7 +800,9 @@ def _listed_directories(raw: str) -> list[str] | None:
return None
def handed_directories(config: dict) -> list[HandedDirectory]:
def handed_directories(
config: dict, profiles: Mapping[str, dict] | None = None
) -> list[HandedDirectory]:
"""Every whole directory a platform links or passes to a standalone build.
A record naming files (gpsp's gba_bios.bin) or one slot of a directory
@@ -449,10 +813,11 @@ def handed_directories(config: dict) -> list[HandedDirectory]:
holds <system> gives one directory per system the platform declares.
"""
base = str(config.get("base_destination") or "bios")
home = str(config.get("home_directory") or "")
natives = native_systems(config)
declared = {d.lower() for d in declared_destinations(config)}
found: list[HandedDirectory] = []
for record in config.get("launchers") or []:
for record in bound_launchers(config, profiles):
if record.get("build") != "standalone" or record.get("kind") not in HANDED_KINDS:
continue
if record.get("names") or record.get("slot"):
@@ -475,7 +840,7 @@ def handed_directories(config: dict) -> list[HandedDirectory]:
if any(re.search(r"[\s,:;]", part) for part in parts):
continue
for part in parts:
directory = normalize_handle(part)
directory = normalize_handle(part, home)
if passes_to.startswith(WORKING_DIRECTORY_PASSED):
# The program runs from the directory: what its code
# reads through getcwd(), or relative to it, is below it.
@@ -484,8 +849,8 @@ def handed_directories(config: dict) -> list[HandedDirectory]:
handles = frozenset(
handle
for token in passes_to.split()
if (handle := normalize_handle(token)) and handle != directory
)
if (handle := normalize_handle(token, home)) and handle != directory
) | ini_keys(passes_to)
folder = _folder_in_bios(part, base)
for emulator in (e.strip() for e in str(record.get("emulator", "")).split(",")):
found.append(HandedDirectory(
@@ -550,8 +915,15 @@ def folder_in_roms(directory: str, config: dict) -> str | None:
(``roms_root.path``): ROCKNIX's /storage/roms, which holds its BIOS
folder and the folders its launchers run programs from.
"""
from common import ROMS_ROOT # noqa: PLC0415
from common import ROMS_ROOT, outer_layout # noqa: PLC0415
spelled = directory.strip().rstrip("/")
for variable in ROMS_ROOT_VARIABLES:
if outer_layout(config, ROMS_ROOT) and (
spelled == variable or spelled.startswith(variable + "/")
):
rest = spelled[len(variable) + 1:]
return None if re.search(r"[\s<>$:;]", rest) else rest
return folder_in_root(directory, config, ROMS_ROOT)
@@ -701,7 +1073,13 @@ def _bind(
one after the other: openMSX's filepool, XRoar's rompath. A file in any
of them is read, so the pool gives one: the directory the platform's own
list already fills (Batocera's bios/openmsx beside bios/Machines), else
the first of the BIOS tree, else the first a pack can fill.
the first of the BIOS tree, else the first a pack can fill. A list that
already holds the folder the layout's files take without the launcher
keeps them there: KNULLI starts MAME with `-rompath`
<romDirname>;/userdata/bios/mame;/userdata/bios, and the sets at the BIOS
root stay. A pool standing for the whole layout holds its files
directly, not its folders (SEARCHED_FILES): MAME reads hash/ and
samples/ through other settings.
"""
found: dict[str, set[Place]] = {}
pooled: dict[str, list[tuple[bool, Place]]] = {}
@@ -735,11 +1113,14 @@ def _bind(
for rest, place in places or [("", (OUTSIDE_TREE, ""))]:
found.setdefault(rest, set()).add(place)
for sub, entries in pooled.items():
# The directory the platform's own list fills, else the first of the
# BIOS tree, else the first a pack fills.
# The folder the files already take, else the directory the
# platform's own list fills, else the first of the BIOS tree, else
# the first a pack fills.
unmoved = [p for _held, p in entries if p == (BIOS_TREE, sub)]
filled = [p for held, p in entries if held]
in_bios = [p for _held, p in entries if p[0] == BIOS_TREE]
found.setdefault(sub, set()).add((filled or in_bios or [p for _h, p in entries])[0])
chosen = (unmoved or filled or in_bios or [p for _h, p in entries])[0]
found.setdefault(sub or SEARCHED_FILES, set()).add(chosen)
return found
@@ -829,9 +1210,15 @@ def bound_path(path: str, bindings: dict[str, Place]) -> Place | None:
The longest subfolder that contains the path wins: a link of
kickstarts/ places kickstarts/kick13.rom even when the whole layout is
bound elsewhere.
bound elsewhere. SEARCHED_FILES covers the files at the root of the
layout alone.
"""
for sub in sorted(bindings, key=len, reverse=True):
if sub == SEARCHED_FILES:
if "/" in path:
continue
root, folder = bindings[sub]
return (root, f"{folder}/{path}" if folder else path)
if sub and not path.startswith(sub + "/"):
continue
rest = path[len(sub) + 1:] if sub else path
@@ -919,7 +1306,7 @@ class LauncherLayer:
db: dict,
declared: Iterable[str],
) -> None:
self.places = launcher_places(config)
self.places = launcher_places(config, profiles)
self.declared = set(declared)
self.declared_folded = {d.lower() for d in self.declared}
self.declared_names = {d.rsplit("/", 1)[-1] for d in self.declared}
@@ -941,7 +1328,10 @@ class LauncherLayer:
for key in self._profiles_named(emulator, profiles, relevant)
}
# RetroDECK names its frontend, retroarch, and the core option it
# writes, pcsx2_bios, names the core.
# writes, pcsx2_bios, names the core: a libretro core option
# belongs to a libretro core.
if place.build == "libretro" and place.kind == "core_option":
owners = {k for k in owners if "libretro" in str(profiles[k].get("type") or "")}
if not owners:
owners = set(setting_readers(place.passes_to, profiles, relevant))
for key in sorted(owners):
@@ -1072,7 +1462,9 @@ class LauncherLayer:
# core asked for it: the pack puts a file there either way.
reported_at: dict[str, dict] = {}
for _emulator, _standalone, _entry, report in candidates:
if report.get("in_repo"):
# A file the layout reads outside the BIOS tree fills no
# destination of it.
if report.get("in_repo") and not report.get("unplaced"):
destination = sanitize_pack_path(report.get("path") or report.get("name", ""))
reported_at.setdefault(destination, report)
by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]] = {}
@@ -1116,6 +1508,9 @@ class LauncherLayer:
continue
if isinstance(filled, dict):
added.append(filled)
# The launcher hands the emulator that file from the BIOS
# tree: read outside it no more.
settled.update(id(report) for _c, report in matched if report.get("unplaced"))
if place.stands_for_default:
# The emulator opens the launcher's file instead of its
# own name, so a copy under that name is read by nobody:
+7 -1
View File
@@ -508,7 +508,13 @@ def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) ->
record = json.loads(proc.stdout)
except ValueError:
record = None
return proc.returncode, record, proc.stderr.strip()[-1500:]
# A traceback spells the checkout and the scratch folders: a record read
# on another machine names them by role.
places = [(str(work), "<work>"), (str(layout.root), "<dest>"), (str(ROOT), "<repo>")]
error = proc.stderr.strip()
for prefix, name in sorted(places, key=lambda place: -len(place[0])):
error = error.replace(prefix, name)
return proc.returncode, record, error[-1500:]
def probe_argv(core: dict, choice: CoreChoice, content: campaign.Content, load: Path,
+215 -39
View File
@@ -10,7 +10,7 @@ from collections.abc import Iterable
from common import PROFILE_IDENTITY_FIELDS, _norm_system_id, entry_system_ids
from alternatives import core_file_spares, required_only_spares, set_fields
from common import archive_members, holds_required_members
from common import archive_members, contents_members, holds_required_members
from common import declared_root, expand_platform_declared_names, platform_declarations
from common import load_emulator_profiles
from common import resolution_is_hash_exact
@@ -19,7 +19,7 @@ from common import resolve_platform_cores
from common import core_system_dirs, platform_layouts, system_dir_path
from common import standalone_set as platform_standalone_set
from common import OUTER_ROOTS, outer_layout, sanitize_pack_path
from common import size_fits
from common import declares_shape, shape_fits, size_fits
from 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
@@ -513,6 +513,7 @@ def _agnostic_scan_extras(
extras_prefix: str,
standalone_set: set[str] | None = None,
taken: dict[str, dict] | None = None,
all_profiles: dict | None = None,
) -> list[dict]:
"""Every interchangeable candidate a filename-agnostic core accepts.
@@ -521,6 +522,8 @@ def _agnostic_scan_extras(
The directory is the delicate part: anchoring it on a single
filename walked into another emulator's tree, so the profile's own
files have to agree before the scan follows an ambiguous name.
``all_profiles`` are the profiles a placeholder's directory is proven
from, ``profiles`` when not given.
"""
extras: list[dict] = []
files_db = db.get("files", {})
@@ -564,7 +567,15 @@ def _agnostic_scan_extras(
agnostic_votes.get(directory + "/", 0) + 1
)
for profile, standalone in platform_layouts(emu_name, profile, standalone_set or set()):
own = profile
for profile, standalone in platform_layouts(emu_name, own, standalone_set or set()):
# A layout copies each entry in order (a launcher's folder, a
# system directory): its files are looked up as the profile's
# own, or a bound layout scans nothing (KNULLI's bios/ps2).
origin = {
id(view): entry
for view, entry in zip(profile.get("files", []), own.get("files", []))
}
for f in profile.get("files", []):
if not is_profile_agnostic and not f.get("agnostic"):
continue
@@ -591,7 +602,7 @@ def _agnostic_scan_extras(
# the flag icons of an Android package walked into a PS2 pack.
if f.get("category", "bios") != "bios":
continue
if not (f.get("size") or f.get("min_size") or f.get("max_size")):
if not declares_shape(f):
continue
# The free name is the BIOS directory's: a shader, a sound or a
# font the emulator reads from its resources tree has a fixed
@@ -614,24 +625,45 @@ def _agnostic_scan_extras(
companion_ext, image = _companion_of(profile, fname)
path_prefix = (
resolved_dirs.get(id(image), "") if image
else resolved_dirs.get(id(f), "")
resolved_dirs.get(id(origin.get(id(image), image)), "") if image
else resolved_dirs.get(id(origin.get(id(f), f)), "")
)
if not path_prefix:
# A placeholder (<bios>.bin) resolves to nothing and anchors no
# directory. The folders where the system's other profiles
# resolve hashed files of that shape do, those folders only:
# LRPS2 and PCEE2 are made of placeholders, and on Batocera,
# where no other libretro PS2 core anchors pcsx2/bios/, the
# pack held nothing there. A companion (<bios>.nvm) looks
# where its image is proven: RetroBat's pcsx2/bios/ had
# scph39001.bin and its .nvm only at the BIOS root.
exact_dirs: frozenset[str] = frozenset()
anchor = image if image else f
if not path_prefix and "<" in str(anchor.get("name", "")):
exact_dirs = placeholder_directories(
anchor, emu_name, profile, db, all_profiles or profiles
)
if not path_prefix and not exact_dirs:
continue
# A name matching one file identifies it. A name matching several
# identifies nothing on its own, so the profile's other files have
# to agree on the directory before the scan walks it.
ambiguous = id(f) in named_only and len(by_name.get(fname, [])) > 1
ambiguous = (
id(origin.get(id(f), f)) in named_only
and len(by_name.get(fname, [])) > 1
)
if ambiguous and agnostic_votes.get(path_prefix, 0) < 2:
continue
# Scan DB for all files under this prefix matching size
for sha1, entry in files_db.items():
path = entry.get("path", "")
if not path.startswith(path_prefix):
if exact_dirs:
if ("/" not in path or path.rsplit("/", 1)[0] not in exact_dirs
or "/.variants/" in path):
continue
elif not path.startswith(path_prefix):
continue
if not companion_ext and not size_fits(f, entry.get("size", 0)):
if not companion_ext and not shape_fits(f, path, entry.get("size", 0)):
continue
scan_name = entry.get("name", "")
if not scan_name:
@@ -640,6 +672,12 @@ def _agnostic_scan_extras(
stem, _, ext = scan_name.rpartition(".")
if not stem or ext.lower() != companion_ext.lower():
continue
# Read only beside the image the core selected, so a
# companion counts only next to an image the image's
# own test accepts: Namco System 246 .nvm and .mec
# dumps sit beside no PS2 BIOS.
if not _image_beside(path, stem, image, files_db):
continue
scan_name = f"{stem}.{companion_ext}"
# Into the directory the seed entry names, not the root:
# yaps2 reads its BIOS from pcsx2/bios/.
@@ -676,9 +714,16 @@ def _agnostic_scan_extras(
"agnostic_scan": True,
}
extra["claim_order"] = (4, 0, emu_name)
if not _take(extra, full_dest, seen_dests, taken):
continue
extras.append(extra)
if _take(extra, full_dest, seen_dests, taken):
extras.append(extra)
else:
# The image another core's scan placed is this core's
# too, and so are the companions it reads beside it:
# Recalbox's libretro PCSX2 opens <bios>.erom next to
# the images LRPS2 placed, which LRPS2 never reads.
held = taken.get(full_dest) if taken is not None else None
if held is None or held.get("sha1") != sha1:
continue
extras.extend(_companion_extras(
_companions(path, scan_name, _companion_extensions(profile, fname), files_db),
folder, extras_prefix, seen_dests, profile, emu_name, f, taken,
@@ -686,6 +731,32 @@ def _agnostic_scan_extras(
return extras
def placeholder_directories(
seed: dict, emu_name: str, profile: dict, db: dict, all_profiles: dict,
) -> frozenset[str]:
"""The folders that hold the dumps a placeholder entry accepts.
Each folder where another profile of the same system resolves a hashed
file of the seed's shape by content: PCSX2 proves bios/Sony/PlayStation 2/.
Only that folder, not the ones below it (its DVD firmware).
"""
systems = set(profile.get("systems", []))
directories: set[str] = set()
for other_name, other in all_profiles.items():
if other_name == emu_name or not systems & set(other.get("systems", [])):
continue
for f in other.get("files", []):
if not isinstance(f, dict) or not any(f.get(h) for h in ("sha1", "md5", "sha256", "crc32")):
continue
if f.get("size") and not size_fits(seed, f["size"]):
continue
local, status = resolve_local_file({**f, "source_profile": other_name}, db)
if (local and "/" in local and resolution_is_hash_exact(status)
and shape_fits(seed, local)):
directories.add(local.rsplit("/", 1)[0])
return frozenset(directories)
def _placeholder_scan(
files: list[dict], emu_name: str, profile: dict, db: dict, standalone: bool,
all_profiles: dict | None = None,
@@ -699,33 +770,28 @@ def _placeholder_scan(
(its DVD firmware). Nothing proven, nothing scanned.
"""
files_db = db.get("files", {})
systems = set(profile.get("systems", []))
extras: list[dict] = []
for seed in files:
name = str(seed.get("name", ""))
if "<" not in name or seed.get("category", "bios") != "bios":
continue
if not (seed.get("size") or seed.get("min_size") or seed.get("max_size")):
if not declares_shape(seed):
continue
directories: set[str] = set()
for other_name, other in (all_profiles or load_emulator_profiles("emulators")).items():
if other_name == emu_name or not systems & set(other.get("systems", [])):
continue
for f in other.get("files", []):
if not any(f.get(h) for h in ("sha1", "md5", "sha256", "crc32")):
continue
if f.get("size") and not size_fits(seed, f["size"]):
continue
local, status = resolve_local_file({**f, "source_profile": other_name}, db)
if local and "/" in local and resolution_is_hash_exact(status):
directories.add(local.rsplit("/", 1)[0])
# <bios>.nvm is read beside the image the core selected, never on
# its own: its files come with each scanned image (_companions).
if _companion_of(profile, name)[1] is not None:
continue
directories = placeholder_directories(
seed, emu_name, profile, db,
all_profiles or load_emulator_profiles("emulators"),
)
layout = (seed.get("standalone_path") if standalone else None) or seed.get("path") or ""
folder = layout.rsplit("/", 1)[0] if "/" in layout else ""
for sha1, entry in sorted(files_db.items(), key=lambda kv: kv[1].get("path", "")):
path = entry.get("path", "")
if "/" not in path or path.rsplit("/", 1)[0] not in directories:
continue
if "/.variants/" in path or not size_fits(seed, entry.get("size", 0)):
if "/.variants/" in path or not shape_fits(seed, path, entry.get("size", 0)):
continue
scan_name = entry.get("name", "")
dest = f"{folder}/{scan_name}" if folder else scan_name
@@ -733,6 +799,7 @@ def _placeholder_scan(
"name": scan_name,
"destination": dest,
"sha1": sha1,
"source_name": name,
"source_system": seed.get("system"),
"region": seed.get("region"),
})
@@ -766,16 +833,34 @@ def expand_agnostic_entries(
db.get("indexes", {}).get("by_name", {}), set(), "",
{emu_name} if standalone else set(),
)
# A placeholder is answered by files found in its own folder: PCEE2's
# eeprom.dat, scanned at the root, said nothing about pcsx2/bios/.
covered = {e["destination"].rsplit("/", 1)[0] if "/" in e["destination"] else "" for e in scanned}
# A placeholder is answered by the files its own scan found in its own
# folder: PCEE2's eeprom.dat, scanned at the root, said nothing about
# pcsx2/bios/, and its COH-H images, scanned into pcsx2/bios/, say
# nothing about the console <bios>.bin beside them.
def answered(extras: list[dict]) -> set[tuple[str, str]]:
return {
(str(e.get("source_name", "")),
e["destination"].rsplit("/", 1)[0] if "/" in e["destination"] else "")
for e in extras
}
def is_answered(f: dict, covered: set[tuple[str, str]]) -> bool:
# A companion placeholder (<bios>.rom1) is read beside its image, so
# it is answered wherever the image placeholder is.
_ext, image = _companion_of(profile, str(f.get("name", "")))
names = {f.get("name", "")} | ({image.get("name", "")} if image else set())
return any((n, folder(f)) in covered for n in names)
covered = answered(scanned)
open_seeds = [
f for f in files if "<" in str(f.get("name", "")) and folder(f) not in covered
f for f in files
if "<" in str(f.get("name", "")) and not is_answered(f, covered)
]
scanned += _placeholder_scan(
open_seeds, emu_name, profile, db, standalone, all_profiles
)
covered = {e["destination"].rsplit("/", 1)[0] if "/" in e["destination"] else "" for e in scanned}
covered = answered(scanned)
if not scanned:
return files
concrete = [
@@ -793,7 +878,7 @@ def expand_agnostic_entries(
]
return [
f for f in files
if "<" not in str(f.get("name", "")) or folder(f) not in covered
if "<" not in str(f.get("name", "")) or not is_answered(f, covered)
] + concrete
@@ -858,6 +943,32 @@ def _companion_of(profile: dict, name: str) -> tuple[str, dict | None]:
return "", None
def _image_beside(
companion_path: str, stem: str, image: dict | None, files_db: dict
) -> bool:
"""Whether the folder of a companion holds an image it is read beside.
PCSX2 opens `<bios>.rom1`, then the BIOS path with its extension
replaced (BiosTools.cpp LoadExtraRom, CDVD.cpp cdvdLoadNVRAM): the
companion's stem is the image's name or the image's own stem. The
image has to pass the image entry's test, its size and its ROM
directory, as the scan that selected it does.
"""
if image is None:
return False
directory = companion_path.rsplit("/", 1)[0] + "/"
wanted = stem.lower()
for _sha1, entry in _files_by_directory(files_db).get(directory, ()):
name = str(entry.get("name", ""))
if name.lower() != wanted and name.rpartition(".")[0].lower() != wanted:
continue
if name.lower() == companion_path.rsplit("/", 1)[-1].lower():
continue
if shape_fits(image, entry.get("path", ""), entry.get("size", 0)):
return True
return False
def _companion_extensions(profile: dict, seed_name: str) -> set[str]:
"""Extensions the profile declares beside a free-named BIOS entry.
@@ -1336,6 +1447,8 @@ def _collect_emulator_extras(
for e in extras:
covered_names.add(e["name"])
# Destination -> the copies cores ask for there, in profile order.
copied: dict[str, list[dict]] = {}
for emu_name, profile in sorted(profiles.items()):
if profile.get("type") in ("launcher", "alias"):
continue
@@ -1351,7 +1464,7 @@ def _collect_emulator_extras(
# covered elsewhere belongs to another program's file.
# Nor is one placed outside the BIOS tree by the layout.
if (fname not in covered_names or f.get("unsourceable") or f.get("unplaced")
or f.get("root") in OUTER_ROOTS or f.get("unprefixed")):
or f.get("root") in OUTER_ROOTS):
continue
# Installed with the emulator or by the platform's package,
# as the first pass already decided for the same entry.
@@ -1381,10 +1494,16 @@ def _collect_emulator_extras(
# of the directory core files go to, which the platform may not
# declare (Recalbox has its System Cards under pcenginecd/ only,
# geargrafx reads them from the root).
full_dest = prefixed_destination(dest, extras_prefix)
# A path of the install tree outside the BIOS folder keeps no
# prefix: EmuELEC's dolphin/dolphin-emu/GBA/gba_bios.bin.
full_dest = (
sanitize_pack_path(dest) if f.get("unprefixed")
else prefixed_destination(dest, extras_prefix)
)
if full_dest in seen_dests and full_dest not in taken:
continue
if full_dest in taken and full_dest not in seen and fname not in platform_names:
if (full_dest in taken or full_dest in copied) and full_dest not in seen \
and fname not in platform_names:
# Another core's extra holds this path and only that
# extra covers the name: a pack without that core never
# reaches this copy, so this core claims nothing here.
@@ -1427,9 +1546,30 @@ def _collect_emulator_extras(
extra["contents"] = f["contents"]
if f.get("system_dir"):
extra["system_dir"] = f["system_dir"]
if f.get("unprefixed"):
extra["unprefixed"] = True
# A copy placed outside the BIOS tree resolves by its layout
# path alone, as the first pass does: EmuELEC's
# roms/mame/stvbios.zip took bios/Arcade/MAME's set by that tail.
if f.get("layout_path"):
extra["layout_path"] = f["layout_path"]
extra["claim_order"] = (2, 0, emu_name)
if _take(extra, full_dest, seen_dests, taken):
extras.append(extra)
copied.setdefault(full_dest, []).append(extra)
# Several cores reading one archive in one roms folder: the copy of the
# core the folder starts by default goes first, then the copy serving
# the most of them. Five cores AmberELEC offers for roms/arcade read
# neogeo.zip there, and the copy holding the 18 members its default
# MAME 2003-Plus requires also holds the 3 MAME 2000 requires.
defaults = _folder_defaults(config, profiles)
for full_dest, claims in copied.items():
if len(claims) > 1:
claims = sorted(claims, key=lambda c: (
not _starts_by_default(c, defaults), -_copy_serves(c, claims, db),
))
for extra in claims:
if _take(extra, full_dest, seen_dests, taken):
extras.append(extra)
extras.extend(
_archive_prefix_extras(
@@ -1533,6 +1673,42 @@ class _ClaimRanks:
)
def _folder_defaults(config: dict, profiles: dict) -> dict[str, set[str]]:
"""Roms folder -> the profiles its default core or emulator names."""
out: dict[str, set[str]] = {}
for row in config.get("_rom_folders") or []:
chosen = {str(row.get("core") or ""), str(row.get("emulator") or "")} - {""}
keys = {c.lower().replace("-", "_") for c in chosen}
out[str(row.get("folder"))] = {
name for name, profile in profiles.items()
if keys & {n.lower().replace("-", "_")
for n in (name, *(str(c) for c in profile.get("cores") or []))}
}
return out
def _starts_by_default(extra: dict, defaults: dict[str, set[str]]) -> bool:
"""Whether the extra's core is the one its roms folder starts by default."""
layout = str(extra.get("layout_path") or "")
destination = str(extra.get("destination") or "")
if not layout or not destination.endswith("/" + layout):
return False
folder = destination[: -len(layout) - 1].removeprefix("roms/")
return extra.get("source_profile") in defaults.get(folder, set())
def _copy_serves(extra: dict, claims: list[dict], db: dict) -> int:
"""How many of the claims on one path the copy an extra resolves to
holds every required member of."""
wanted = [members for c in claims if (members := contents_members(c))]
if not wanted:
return 0
path, _status = resolve_local_file(extra, db, dest_hint=extra.get("destination", ""))
if not path:
return 0
return sum(1 for members in wanted if holds_required_members(path, members))
def _names_content(entry: dict) -> bool:
"""Whether a report entry declares the bytes it wants, not only a name.
+127 -2
View File
@@ -1047,6 +1047,11 @@ class ProfileReport:
new_files_elided: dict[str, int] = field(default_factory=dict)
new_hashes: list[dict] | None = None
detection_skipped: str | None = None
# config_reads refs written for a build a platform ships, each read at
# that build (pin_build) rather than at source_commit: {platform,
# revision, ref, status, detail}. A status other than BUILD_OK is review
# work.
build_refs: list[dict] = field(default_factory=list)
# Skips that say the profile cannot be checked as written: a repository
# that no longer answers, no pin to read, a death the forge contradicts.
@@ -1070,6 +1075,7 @@ class ProfileReport:
+ len(self.orphaned)
+ len(self.stale_prose or ())
+ len(self.moved_repos)
+ sum(1 for ref in self.build_refs if ref["status"] != "BUILD_OK")
)
@@ -1603,6 +1609,84 @@ def moved_repositories(
return moved
def shipped_build_holders(profile: dict) -> dict[int, dict]:
"""The source_ref holders of config_reads entries naming platforms, by id.
Such an entry describes the build those platforms ship, so its refs are
read at their pin_build revision, never at source_commit.
"""
found: dict[int, dict] = {}
for read in profile.get("config_reads") or []:
if not isinstance(read, dict) or not read.get("platforms"):
continue
found[id(read)] = read
for key in read.get("keys") or []:
if isinstance(key, dict):
found[id(key)] = read
return found
def build_revision(profile: dict, platform: str) -> str | None:
"""The emulator revision a platform's pin_build entry names, None when
its value is no revision (a URL, a package name)."""
for build in profile.get("pin_build") or []:
if build.get("platform") != platform:
continue
value = str(build.get("value") or "").strip()
return value if value and re.fullmatch(r"[\w.+-]+", value) else None
return None
def _check_build_refs(
profile: dict,
deferred: list[tuple[Citation, dict]],
views: list[RepoView],
fetch: Callable[[upstream.Repo, str, str], list[str] | None],
) -> list[dict]:
"""Each deferred config_reads ref read at the build of its platforms.
The file must exist at that revision and every cited line lie inside
it. The entry declares no value to anchor on, so this is the check a
ref past the end of its file fails (BUILD_GONE), not a content match.
"""
results: list[dict] = []
for citation, read in deferred:
for platform in read.get("platforms") or []:
# A closed build is named by its binary: an address ref is
# skipped below, a source path cannot exist at a sha256.
revision = (str(read.get("revision") or read.get("binary_sha256") or "")
or build_revision(profile, str(platform)))
row = {"platform": str(platform), "revision": revision or "",
"ref": citation.ref, "field": citation.field}
if revision is None:
results.append({**row, "status": "BUILD_UNREAD",
"detail": "no pin_build revision for this platform"})
continue
problems: list[str] = []
for part in split_source_ref(citation.ref):
role, path = ref_role(part.path)
if " " in path:
# A project word in front (`ROCKNIX patches/x.patch:4`):
# a file of the platform's tree, read with the record.
continue
lines = next(
(found for view in views
if (not role or view.field == role)
and (found := fetch(view.repo, revision, path)) is not None),
None,
)
if lines is None:
problems.append(f"{part.path} absent at {revision[:12]}")
elif (part.end or part.start or 0) > len(lines):
problems.append(f"{part.raw} past the end ({len(lines)} lines)")
results.append({
**row,
"status": "BUILD_GONE" if problems else "BUILD_OK",
"detail": "; ".join(problems),
})
return results
def build_report(
name: str, profile: dict, cache_dir: str, offline: bool = False,
text: str | None = None,
@@ -1621,7 +1705,13 @@ def build_report(
)
modes = {mode for _, mode, _ in declared_repositories(profile) if mode}
refs = []
at_build = shipped_build_holders(profile)
deferred: list[tuple[Citation, dict]] = []
for citation in collect_citations(profile, text):
if citation.kind == "ref" and id(citation.holder) in at_build:
# Written for the build a platform ships: read at pin_build.
deferred.append((citation, at_build[id(citation.holder)]))
continue
if citation.kind == "ref":
entry = citation.entry
display = str(entry.get("name") or "") or citation.field
@@ -2204,6 +2294,8 @@ def build_report(
)
return result
report.build_refs = _check_build_refs(profile, deferred, views, fetch_from)
staged = []
for entry_name, ref, tokens, hashes, ref_parts, citation in refs:
flags = [self_checked(part, tokens) for part in ref_parts]
@@ -2335,6 +2427,14 @@ def format_report(report: ProfileReport, changed_only: bool = False) -> str:
lines.append(f" {len(report.entries)} refs: {summary}")
for line in report.stale_prose or ():
lines.append(f" prose under an older pin: {line}")
for ref in report.build_refs:
if changed_only and ref["status"] == "BUILD_OK":
continue
detail = f": {ref['detail']}" if ref["detail"] else ""
lines.append(
f" {ref['status']} at {ref['platform']} build "
f"{ref['revision'][:12] or '-'} {ref['ref']}{detail}"
)
lines.append(f" {report.needs_review()} to review")
return "\n".join(lines)
@@ -3582,10 +3682,11 @@ def bump_commit(
if pending_recale(report, accept_changed, text):
return False
document = yaml.safe_load(text)
if document.get("built_by"):
if document.get("built_by") and not document.get("pin_follows"):
# The pin is the commit a platform builds (recalbox gsplus.mk, the
# mame0258 its package fetches), not a point on a moving branch:
# HEAD is a build nobody ships under this name.
# HEAD is a build nobody ships under this name. A build of the
# branch tip (RetroPie's advmame) is HEAD, and follows it.
print(
f"{path.stem}: pinned to the build {', '.join(document['built_by'])} "
"ships, advanced by hand",
@@ -3644,6 +3745,8 @@ def bump_commit(
expected = dict(document)
expected["source_commit"] = report.head
new_text = _set_pin(text, document, "source_commit", report.head, "profiled_date")
if document.get("pin_follows") and report.head:
new_text, expected = _follow_config_reads(new_text, expected, document, report.head)
if upstream_moves:
expected["upstream_commit"] = report.upstream_head
new_text = _set_pin(
@@ -3700,6 +3803,28 @@ def cites_primary(report: ProfileReport) -> bool:
return not parts or any(part.repo is None for part in parts)
def _follow_config_reads(
text: str, expected: dict, document: dict, head: str
) -> tuple[str, dict]:
"""A config_reads entry read at the pin moves with a pin that follows the
branch tip: RetroPie installs advmame from the tip, so the build its
advmame.rc is read at is the pin itself."""
pin = str(document.get("source_commit") or "")
reads = document.get("config_reads") or []
if not pin or not any(isinstance(r, dict) and r.get("revision") == pin for r in reads):
return text, expected
text = re.sub(
r'^(\s*revision:\s*)(["\']?)' + re.escape(pin) + r"\2\s*$",
lambda m: f"{m.group(1)}{m.group(2)}{head}{m.group(2)}",
text, flags=re.M,
)
expected = {**expected, "config_reads": [
{**r, "revision": head} if isinstance(r, dict) and r.get("revision") == pin else r
for r in reads
]}
return text, expected
def _set_pin(text: str, document: dict, field: str, value: str, after: str) -> str:
"""Write *field* as *value*, replacing its line or adding one after *after*."""
current = document.get(field)
+1
View File
@@ -380,6 +380,7 @@ def _command_for(
f"scripts.scraper.{scraper}_scraper",
"-o",
f"platforms/{subject}.yml",
*(str(a) for a in entry.get("rescrape_args") or ()),
]
if area == "targets":
+141 -12
View File
@@ -11,6 +11,14 @@ idea per line, plain words (owner, 2026-11-10). The maintainer writes
what changed, and that text is appended as given once it holds none of the
REFUSED phrases.
The notes end with the people to thank and the full changelog, from the
previous release's record commit (the first commit release.json gave the
previous tag) to the new tag. The thanks name everyone who helped since the
repository started, read with gh: a login is only ever the one GitHub links
to the work, never one guessed from a git author name. The owner, bots and
spam are left out (LEFT_OUT). --thanks FILE passes a checked list instead
of the one gh gives.
Usage:
python scripts/release_notes.py --whats-new tmp/whats-new.md --output notes.md
"""
@@ -18,8 +26,11 @@ Usage:
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from collections.abc import Callable
from pathlib import Path
import release_record
@@ -34,7 +45,12 @@ from common import (
from siteguides import install_command
REPO = "Abdess/retrobios"
OWNER = "Abdess"
SITE = "https://abdess.github.io/retrobios/"
# The handheld app is served by the site, built from its own commit, never
# attached to a release. The installer's handheld section opens on the
# download of every system.
HANDHELD_PAGE = "wiki/installer/#on-a-handheld-the-retrobios-port"
def _size(count: int) -> str:
@@ -79,14 +95,16 @@ def without_pack(platforms_dir: str) -> list[str]:
def no_pack_paragraph(platforms_dir: str) -> list[str]:
"""One paragraph naming the setups served by the command alone."""
"""One paragraph naming the setups served by the command alone. The
packs published are the most downloaded ones (wiki/release-process.md,
"Which platforms get a pack")."""
names = without_pack(platforms_dir)
if not names:
return []
listed = ", ".join(names[:-1]) + f" and {names[-1]}" if len(names) > 1 else names[0]
return [
(f"No ZIP for {listed}. The command above installs them."
" Add `--dry-run` to see what it would do."),
("Only the most used setups have a pack, to keep the release small."
f" For {listed}, use the command above."),
"",
]
@@ -119,31 +137,126 @@ def refused_words(text: str) -> list[str]:
return [phrase for phrase in REFUSED if phrase in lowered]
def render(record: dict, platforms_dir: str, whats_new: str) -> str:
Run = Callable[[list[str]], str]
def _run(argv: list[str]) -> str:
return subprocess.run(argv, capture_output=True, text=True, check=True).stdout
def previous_record_commit(tag: str, run: Run | None = None) -> str:
"""The commit that recorded the release before *tag*: the oldest commit
of the run of release.json changes that name the previous tag."""
run = run or _run
shas = run(["git", "log", "--format=%H", "--", "release.json"]).split()
previous, base = None, None
for sha in shas:
recorded = json.loads(run(["git", "show", f"{sha}:release.json"])).get("tag")
if previous is None:
if recorded != tag:
previous, base = recorded, sha
elif recorded == previous:
base = sha
else:
break
if base is None:
raise ValueError(f"release.json records no release before {tag}")
return base
# Accounts that never helped: the owner's own, GitHub's placeholder for a
# deleted account, and spam (issue 32 by Bappo0 and pull request 67 by
# prakashmagat50-byte, both empty or garbage).
LEFT_OUT = frozenset(("Abdess", "Abdess76", "ghost", "Bappo0", "prakashmagat50-byte"))
def _person(login: str | None) -> str | None:
"""The login to thank, None for the owner, a bot, a deleted account,
spam, or work GitHub links to no account."""
if not login or login in LEFT_OUT or login.endswith("[bot]") or login.startswith("app/"):
return None
return login
def _logins(text: str) -> set[str]:
"""One login per line, as `gh api --paginate --jq` prints them."""
return {person for line in text.splitlines() if (person := _person(line.strip()))}
def _authors(text: str) -> set[str]:
"""The authors of a `gh pr list` or `gh issue list --json author`."""
return {person for item in json.loads(text)
if not (item.get("author") or {}).get("is_bot")
and (person := _person((item.get("author") or {}).get("login")))}
def gather_thanks(run: Run | None = None, repo: str = REPO) -> list[str]:
"""Everyone who helped since the repository started, each named once:
commit authors as the commits API links them to an account and every
pull request author, merged or not, then issue authors, then whoever
commented on an issue or a pull request."""
run = run or _run
code = _logins(run(["gh", "api", "--paginate", f"repos/{repo}/commits",
"--jq", ".[] | .author.login // empty"]))
code |= _authors(run(["gh", "pr", "list", "-R", repo, "--state", "all",
"--limit", "10000", "--json", "number,author"]))
reports = _authors(run(["gh", "issue", "list", "-R", repo, "--state", "all",
"--limit", "10000", "--json", "number,author"])) - code
helped = set()
for path in (f"repos/{repo}/issues/comments", f"repos/{repo}/pulls/comments"):
helped |= _logins(run(["gh", "api", "--paginate", path, "--jq", ".[] | .user.login"]))
helped -= code | reports
lines = []
for label, people in (("Code and data", code), ("Reports", reports),
("Help in issues", helped)):
if people:
names = [f"@{login}" for login in sorted(people, key=str.casefold)]
listed = names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}"
lines.append(f"- **{label}**: {listed}.")
return lines
def changelog_url(base: str, tag: str, repo: str = REPO) -> str:
return f"https://github.com/{repo}/compare/{base[:9]}...{tag}"
def closing_lines(thanks: list[str], changelog: str) -> list[str]:
"""The Thanks section, left out when nobody is to thank, and the full
changelog line."""
# Folded: the lists run to a hundred names. GitHub renders the markdown
# inside only with a blank line on each side of it.
lines = (["### Thanks", "", "<details>",
"<summary>Everyone who helped since the start</summary>", "",
*thanks, "", "</details>", ""]
if thanks else [])
return [*lines, f"**Full changelog**: {changelog}", ""]
def render(record: dict, platforms_dir: str, whats_new: str,
closing: list[str] | None = None) -> str:
packs = record.get("packs", {})
folders = _extract_folders(record, platforms_dir)
tag = str(record.get("tag", ""))
lines = [
"### Install in one command",
"### Get the BIOS files",
"",
"It finds the setup and its BIOS folder, then downloads only what is missing.",
"Paste this in a terminal. It finds the setup and installs the missing BIOS files.",
"",
"**Linux, macOS, Steam Deck**",
"```sh",
install_command("sh"),
"```",
"",
"**Windows (PowerShell)**",
"**Windows**",
"```powershell",
install_command("powershell"),
"```",
"",
(f"**On a handheld**: copy the `RetroBIOS` file for the system to the card"
f" ([which one]({SITE}wiki/installer/#on-a-handheld-the-retrobios-port))."),
f"**On a handheld**: [get the app for the system]({SITE}{HANDHELD_PAGE}).",
"",
"### Or download a pack",
"### Full packs",
"",
"Extract it into the BIOS folder.",
"Large downloads, for a device without internet. Extract into the BIOS folder.",
"",
]
if any(len(pack["assets"]) > 1 for pack in packs.values()):
@@ -170,6 +283,7 @@ def render(record: dict, platforms_dir: str, whats_new: str) -> str:
*no_pack_paragraph(platforms_dir),
whats_new.strip(),
"",
*(closing or []),
]
return "\n".join(lines)
@@ -182,6 +296,8 @@ def main() -> int:
help="what changed since the previous release, written by hand")
parser.add_argument("--platforms-dir", default="platforms",
help="registry read for each pack's extract folder (default: %(default)s)")
parser.add_argument("--thanks", type=Path,
help="checked Thanks lines to print instead of the ones gh gives")
parser.add_argument("--output", required=True, type=Path,
help="notes file to write, passed to gh release create --notes-file")
args = parser.parse_args()
@@ -201,7 +317,20 @@ def main() -> int:
" changed and how it was checked, not a verdict on other projects or a"
" promise the gap analysis contradicts", file=sys.stderr)
return 1
write_text_atomic(str(args.output), render(record, args.platforms_dir, whats_new))
try:
base = previous_record_commit(record["tag"])
if args.thanks:
thanks = [line for line in args.thanks.read_text(encoding="utf-8").splitlines()
if line.strip()]
else:
thanks = gather_thanks()
except (subprocess.CalledProcessError, ValueError, KeyError, OSError) as exc:
detail = getattr(exc, "stderr", "") or exc
print(f"Error: cannot gather the thanks: {str(detail).strip()}. Pass a checked list"
" with --thanks FILE", file=sys.stderr)
return 1
closing = closing_lines(thanks, changelog_url(base, record["tag"]))
write_text_atomic(str(args.output), render(record, args.platforms_dir, whats_new, closing))
print(f"Wrote {args.output} for {record['tag']}, {len(record['packs'])} packs")
return 0
+162
View File
@@ -0,0 +1,162 @@
"""The PS2 ROM directory test the PCSX2 family runs on every BIOS candidate.
A BIOS image starts with a table of 16-byte entries (a 10-byte name, a
16-bit extended info size, a 32-bit file size) whose first entry is RESET.
``LoadBiosVersion`` (pcsx2/ps2/BiosTools.cpp) reads the file 16 bytes at a
time from its start until an entry named RESET, then walks the table from
there, adding up the entry sizes rounded to 16 bytes to find where each
file of the ROM lies, and reads the 14 bytes of ROMVER at its offset. The
image is a BIOS when the walk met ROMVER.
The forks differ in how they compare the names and in what an unreadable
read does, so a profile declares how its code reads the table (``romdir:``
on the entry) and ``romdir_accepts`` runs that same walk. Stdlib only:
install.py carries a copy of the walk.
"""
from __future__ import annotations
import struct
from dataclasses import dataclass
ENTRY_SIZE = 16
NAME_SIZE = 10
# `for (i = 0; i < 512 * 1024; i++)` in every LoadBiosVersion.
SEARCH_ENTRIES = 512 * 1024
ROMVER_SIZE = 14
EXTINFO_SIZE = 15
# What a read the code cannot complete does, by fork.
REJECT = "rejects" # wxWidgets streams throw (pxStreams.cpp, EndOfStream)
ENDS_WALK = "ends_walk" # the walk breaks, the result stands
IGNORED = "ignored" # AetherSX2 zero-fills romver and counts it found
SPEC_KEYS = frozenset({
"reset_compare", "missing_reset", "terminated_names", "extinfo", "unreadable_romver",
"truncated_walk", "offset_width", "refused_serials", "zones", "refused_zones",
})
@dataclass(frozen=True)
class Romdir:
"""What a walk that met ROMVER read: its 14 bytes and the EXTINFO serial."""
romver: bytes
serial: str
def _name_is(name: bytes, wanted: bytes, compared: int) -> bool:
"""strncmp(name, wanted, compared) == 0 over a 10-byte field."""
a = name[:compared]
b = (wanted + b"\x00")[:compared]
for x, y in zip(a, b.ljust(len(a), b"\x00")):
if x != y:
return False
if x == 0:
return True
return True
def walk(data: bytes, spec: dict) -> Romdir | None:
"""The ROM directory walk one fork's LoadBiosVersion runs, or None.
``reset_compare`` is the length strncmp compares RESET over: 5 in the
wxWidgets and AetherSX2 code, which takes any name starting with RESET,
sizeof(fileName) (10) after, which wants RESET and a NUL.
``terminated_names`` stops the walk at a name with no NUL in its 10
bytes (strnlen check of the later code). ``missing_reset`` says what
512 Ki entries read without RESET do: ``rejects`` where the code throws
(wxWidgets), ``ends_walk`` where the loop just ends and the walk starts
at the last entry read. ``extinfo`` reads 15 bytes at
the EXTINFO offset + 0x10 and ends the walk when they are not there.
``unreadable_romver`` and ``truncated_walk`` say what a ROMVER read and
a next-entry read past the end of the file do: ``rejects``,
``ends_walk`` or, for ROMVER, ``ignored``. ``offset_width`` is the
width of the offset sum: 32 where it is a uint (wxWidgets code), 64
where it is an s64.
"""
size = len(data)
reset_compare = int(spec.get("reset_compare", NAME_SIZE))
terminated = bool(spec.get("terminated_names", True))
extinfo = bool(spec.get("extinfo", True))
unreadable = spec.get("unreadable_romver", ENDS_WALK)
truncated = spec.get("truncated_walk", ENDS_WALK)
missing_reset = spec.get("missing_reset", ENDS_WALK)
offset_mask = (1 << int(spec.get("offset_width", 64))) - 1
pos = 0
for _ in range(SEARCH_ENTRIES):
if pos + ENTRY_SIZE > size:
return None
name = data[pos:pos + NAME_SIZE]
pos += ENTRY_SIZE
if _name_is(name, b"RESET", reset_compare):
break
else:
if missing_reset == REJECT:
return None
entry = data[pos - ENTRY_SIZE:pos]
offset = 0
romver: bytes | None = None
serial = ""
while True:
name = entry[:NAME_SIZE]
if name[0] == 0 or (terminated and b"\x00" not in name):
break
if extinfo and _name_is(name, b"EXTINFO", NAME_SIZE):
start = offset + 0x10
if start + EXTINFO_SIZE > size:
break
serial = data[start:start + EXTINFO_SIZE].split(b"\x00", 1)[0].decode("latin-1")
if _name_is(name, b"ROMVER", NAME_SIZE):
if offset + ROMVER_SIZE > size:
if unreadable == REJECT:
return None
if unreadable == ENDS_WALK:
break
romver = bytes(ROMVER_SIZE)
else:
romver = data[offset:offset + ROMVER_SIZE]
(file_size,) = struct.unpack_from("<I", entry, 12)
offset += file_size if file_size % 0x10 == 0 else (file_size + 0x10) & 0xFFFFFFF0
offset &= offset_mask
if pos + ENTRY_SIZE > size:
if truncated == REJECT:
return None
break
entry = data[pos:pos + ENTRY_SIZE]
pos += ENTRY_SIZE
if romver is None:
return None
return Romdir(romver, serial)
def zone_code(romver: bytes) -> str:
"""The zone characters LoadBiosVersion switches on: ROMVER[4], and [5]
where the code reads it to tell COH-H (T then Z) from T10K."""
return romver[4:6].decode("latin-1")
def romdir_accepts(data: bytes, spec: dict) -> bool:
"""Whether a candidate passes the profile's ROM directory test.
Past the walk, ``refused_serials`` turns away an EXTINFO serial
(ARMSX2's NOT_PS2_BIOS_STAMPS), and ``zones``/``refused_zones`` keep or
drop an image by its ROMVER zone, as a scan that wants a COH-H board
or passes one over does. A zone is written as the code tests it: ``J``
is ROMVER[4], ``TZ`` ROMVER[4] and [5].
"""
found = walk(data, spec)
if found is None:
return False
if found.serial in set(spec.get("refused_serials") or ()):
return False
code = zone_code(found.romver)
def matches(zones: list | None) -> bool:
return any(code.startswith(str(z)) for z in zones or ())
if spec.get("zones") and not matches(spec["zones"]):
return False
return not matches(spec.get("refused_zones"))
+23 -2
View File
@@ -578,8 +578,10 @@ def _append_new_entries(text: str, files: list[dict], original: str) -> str:
return text
lines = []
profile_type = str(existing_data.get("type") or "")
for fe in new_entries:
lines.append(f"\n - name: {_yaml_scalar(fe['name'])}")
lines.extend(set_path_lines(profile_type, fe["name"]))
lines.append(f" required: {str(fe['required']).lower()}")
lines.append(" category: bios_zip")
if fe.get("source_ref"):
@@ -715,10 +717,27 @@ def _rewrite_systems(section: str, systems: dict[str, list[str]]) -> str:
return "\n".join(out)
def _format_device_entry(name: str, device: dict, role: str) -> str:
def set_path_lines(profile_type: str, name: str) -> list[str]:
"""Where each build of a MAME profile reads a set it lists.
The libretro build searches the content folder, then <system>/mame/bios
and <system>/mame/roms (libretro-internal/retro_init.cpp,
Set_Path_Option), never the system folder itself. The standalone build
reads the top of its rompath.
"""
if "libretro" not in profile_type:
return []
lines = [f' path: "mame/bios/{name}"']
if "standalone" in profile_type:
lines.append(f' standalone_path: "{name}"')
return lines
def _format_device_entry(name: str, device: dict, role: str, profile_type: str = "") -> str:
"""One generated device entry, in the field order of the written ones."""
lines = [
f" - name: {_zip_scalar(name)}",
*set_path_lines(profile_type, name),
" required: false",
" category: bios_zip",
*_system_lines(device.get("systems") or []),
@@ -779,7 +798,9 @@ def merge_mame_devices(
name = f"{set_name}.zip"
existing = entries.get(name)
if not existing:
new_blocks[name] = _format_device_entry(name, device, role)
new_blocks[name] = _format_device_entry(
name, device, role, str(profile.get("type") or "")
)
report["added"].append(set_name)
continue
if any(e.get("category") != "bios_zip" for e in existing):
+55 -29
View File
@@ -7,7 +7,7 @@ runs the script its standalone_emulators table names (/usr/bin/<name>.sh,
installed from the package). Those scripts, and the configs their packages
install, say which file under /storage/roms/bios is opened: yabasanshiro.sh
tests saturn_bios.bin and passes it with -b, Hatari's default config names
tos.img, the atari800 core is built to read a config naming its OS ROMs.
tos.img.
runemu.py is read with ast, the scripts with shell_launchers' readers. An
extractor whose construct is gone raises instead of returning nothing.
@@ -26,7 +26,9 @@ try:
from .shell_launchers import (
LauncherPatternMissing,
Script,
config_placement,
describe_keys,
evidence_fields,
settings,
source_ref,
)
@@ -35,7 +37,9 @@ except ImportError:
from shell_launchers import ( # type: ignore[no-redef]
LauncherPatternMissing,
Script,
config_placement,
describe_keys,
evidence_fields,
settings,
source_ref,
)
@@ -45,8 +49,8 @@ RUNEMU = "packages/amberelec/sources/scripts/runemu.py"
RETROARCH_CFG = "packages/games/tools/retroarch/sources/retroarch.cfg"
RETRORUN = "packages/games/tools/retrorun/retrorun.sh"
HATARI_CONFIG = "packages/games/emulators/hatarisa/config/conf/Atari-ST-default.cfg"
ATARI800_CONFIG = "packages/amberelec/config/distribution/configs/atari800.cfg"
ATARI800_PATCH = "packages/games/libretro/atari800/patches/atari800-01-add-emuelec-platform.patch"
# The first-boot copy of every package's /usr/config into /storage/.config.
USERCONFIG = "packages/sysutils/systemd/scripts/userconfig-setup"
AMIBERRY_PACKAGE = "packages/games/emulators/amiberry/package.mk"
AMIBERRY_CONFIGS = "packages/games/emulators/amiberry/config/conf"
FREEJ2ME = (
@@ -103,16 +107,35 @@ class Runemu:
return path, line
def _evidence(
read: Read, record: Launcher, target: str, keys: list[str],
start: Script | None = None, source_name: str = "",
) -> Launcher:
"""A config record with the steps that put its file at ``target``: the
first-boot copy of /usr/config, then the start script's own copy."""
setup = Script(USERCONFIG, read(USERCONFIG))
placements = [config_placement(setup, target, required=False, sources=("/usr/config/",))]
if start is not None:
placements.append(
config_placement(start, target, keys, source_name=source_name, required=False)
)
fields = evidence_fields(placements)
record.installs = fields["installs"]
record.kept_if_present = fields["kept_if_present"]
record.overrides = fields["overrides"]
return record
def retroarch(read: Read) -> list[Launcher]:
"""system_directory of the retroarch.cfg the retroarch package installs."""
found = [s for s in settings(read(RETROARCH_CFG)) if s.key == "system_directory"]
if len(found) != 1:
raise LauncherPatternMissing(RETROARCH_CFG, "one system_directory")
return [Launcher(
return [_evidence(read, Launcher(
emulator="retroarch", build="libretro", kind="passes_path", names=[],
search_dir=found[0].value, passes_to="retroarch.cfg system_directory",
fails_when_missing=False, source_ref=source_ref([(RETROARCH_CFG, [found[0].line])]),
)]
), "/storage/.config/retroarch/retroarch.cfg", ["system_directory"])]
def retrorun(read: Read) -> list[Launcher]:
@@ -170,10 +193,12 @@ def hatari(read: Read, runemu: Runemu) -> list[Launcher]:
path, table_line = runemu.script("HATARISA")
script = Script(path, read(path))
name = posixpath.basename(HATARI_CONFIG)
copied, _ = script.find(rf"^\s*cp\s+\S*/{re.escape(name)}\s", f"cp of {name}")
copied, copy = script.find(
rf"^\s*cp\s+\S*/{re.escape(name)}\s+\"?(\$\{{?\w+\}}?)", f"cp of {name}"
)
passed, _ = script.find(r"\shatari\s+--configfile\s", "hatari --configfile")
files, lines = _bios_files(HATARI_CONFIG, read(HATARI_CONFIG))
return [Launcher(
return [_evidence(read, Launcher(
emulator="HATARISA", build="standalone", kind="fixed_name",
names=[n for _k, n in files], case_insensitive=False, search_dir=BIOS,
passes_to=describe_keys(name, tuple(k for k, _n in files)),
@@ -181,24 +206,8 @@ def hatari(read: Read, runemu: Runemu) -> list[Launcher]:
source_ref=source_ref([
(RUNEMU, [table_line]), (path, [copied, passed]), (HATARI_CONFIG, lines),
]),
)]
def atari800(read: Read) -> list[Launcher]:
"""The ROM keys of the config the atari800 core is built to read."""
patch = Script(ATARI800_PATCH, read(ATARI800_PATCH))
line, found = patch.find(r'DEFAULT_CFG_NAME="\\"([^"\\]+)\\""', "DEFAULT_CFG_NAME")
built = found.group(1)
if not built.endswith("/" + ATARI800_CONFIG.split("/config/", 1)[1]):
raise LauncherPatternMissing(ATARI800_PATCH, f"DEFAULT_CFG_NAME naming {ATARI800_CONFIG}")
files, lines = _bios_files(ATARI800_CONFIG, read(ATARI800_CONFIG))
return [Launcher(
emulator="atari800", build="libretro", kind="fixed_name",
names=[n for _k, n in files], case_insensitive=False, search_dir=BIOS,
passes_to=describe_keys(posixpath.basename(ATARI800_CONFIG), tuple(k for k, _n in files)),
fails_when_missing=False,
source_ref=source_ref([(ATARI800_PATCH, [line]), (ATARI800_CONFIG, lines)]),
)]
), script.expand(copy.group(1), copied, set()),
[f"[{s}] {k}" if s else k for (s, k), _n in files], script, name)]
def yabasanshiro(read: Read, runemu: Runemu) -> list[Launcher]:
@@ -279,6 +288,15 @@ def amiberry(read: Read, runemu: Runemu) -> list[Launcher]:
installed = re.sub(r"^\$\{INSTALL\}", "", link.link)
path, table_line = runemu.script("AMIBERRY")
script = Script(path, read(path))
# A WHDLoad archive is booted by --autoload, which builds its own setup
# over the config: the kickstart records hold for the other content.
autoload = [n for n, text in script.code() if re.search(r"amiberry .*--autoload", text)]
if not autoload:
raise script.missing("WHDLoad boot with --autoload")
content = (
"content not booted with --autoload, a WHDLoad .lha or .zip "
f"({posixpath.basename(path)}:{', '.join(map(str, autoload))})"
)
launchers = [Launcher(
emulator="AMIBERRY", build="standalone", kind="links", names=[],
case_insensitive=False, search_dir=BIOS,
@@ -314,19 +332,23 @@ def amiberry(read: Read, runemu: Runemu) -> list[Launcher]:
else:
test = _shell_test(script, condition_line)
condition = test
launchers.append(Launcher(
target = re.search(r'"?(\$\{?\w+\}?)"?\s*$', line)
if target is None:
raise script.missing(f"destination of the copy at line {number}")
launchers.append(_evidence(read, Launcher(
emulator="AMIBERRY", build="standalone", kind="fixed_name",
slot=copied.group(1).removesuffix("-default.uae").removeprefix("Amiga"),
names=[found[0].value.removeprefix("$(FILE_PATH)/")], case_insensitive=False,
search_dir=BIOS,
passes_to=f"{copied.group(1)} kickstart_rom_file, $(FILE_PATH) = {rom_path[0].value}",
fails_when_missing=False,
depends_on_option=condition,
depends_on_option=f"{condition}, {content}",
source_ref=source_ref([
(RUNEMU, [table_line]), (path, [condition_line, number]),
(config, [rom_path[0].line, found[0].line]),
]),
))
), script.expand(target.group(1), number, set()), ["kickstart_rom_file"],
script, copied.group(1)))
if len(launchers) == 1:
raise script.missing("cp of a default .uae config")
return launchers
@@ -420,9 +442,13 @@ def easyrpg(read: Read) -> list[Launcher]:
def extract_launchers(read: Read) -> list[dict[str, Any]]:
"""Every launcher record, read through `read(repo-relative path)`."""
runemu = Runemu(read)
# The atari800.cfg AmberELEC ships names the OS ROMs, but the core opens
# it only under its atari800_cfg option, off by default, and finds the
# ROMs by a scan of the content folder (libretro-atari800 atari.c:512-516,
# 537, libretro_core_options.h:1203): no record reads it.
launchers = [
*retroarch(read), *retrorun(read), *mame(runemu),
*atari800(read), *scummvm(read), *freej2me(read), *easyrpg(read),
*scummvm(read), *freej2me(read), *easyrpg(read),
*amiberry(read, runemu), *hatari(read, runemu), *pico8(read, runemu),
*piemu(read, runemu), *yabasanshiro(read, runemu),
]
+16
View File
@@ -205,6 +205,7 @@ def build_index(
if n not in bios_names and not e.isdevice and e.runnable and (e.has_roms or e.disks)
}
bios: dict[str, set[str]] = {}
parents: dict[str, set[str]] = {}
devices: dict[str, set[str]] = {}
missing: dict[str, str] = {}
for name, entry in games.items():
@@ -218,17 +219,32 @@ def build_index(
break
if current in bios_names and parent.has_roms:
bios.setdefault(archive(current, current), set()).add(name)
elif current not in bios_names and parent.has_roms:
# A clone's ROM shared with its parent is looked up in the
# parent's archive too: MAME's search path is the set and
# every ancestor (src/emu/driver.cpp:31-38,
# src/emu/romload.cpp:67-84 at mame0289).
parents.setdefault(archive(current, current), set()).add(name)
current = parent.romof
for device in set(entry.devices) & device_roms:
devices.setdefault(device, set()).add(name)
with_bios = {g for members in bios.values() for g in members}
# The source file of each game and device set: what a launcher that
# starts whatever set a folder holds selects a folder's machines by
# (ES-DE runs MAME on any CPS-2 set of roms/cps2).
sources: dict[str, set[str]] = {}
for name, entry in sets.items():
if entry.source and (name in games or name in device_roms):
sources.setdefault(entry.source, set()).add(archive(name, name))
return {
"bios": {k: sorted(v) for k, v in sorted(bios.items())},
"parents": {k: sorted(v) for k, v in sorted(parents.items())},
"devices": {k: sorted(v) for k, v in sorted(devices.items())},
"chd": sorted(n for n, e in games.items() if e.disks),
"missing_parents": dict(sorted(missing.items())),
"no_bios": sorted(set(games) - with_bios - set(missing)),
"bios_sets": sorted(bios_names),
**({"sources": {k: sorted(v) for k, v in sorted(sources.items())}} if sources else {}),
"counts": {
"sets": len(sets),
"games": len(games),
+8 -1
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import inspect
import json
import re
import sys
@@ -391,10 +392,16 @@ def scraper_cli(
parser.add_argument("--dry-run", action="store_true", help="Show scraped data")
parser.add_argument("--output", "-o", help="Output YAML file")
parser.add_argument("--json", action="store_true", help="Output as JSON")
takes_revision = "revision" in inspect.signature(scraper_class).parameters
if takes_revision:
parser.add_argument(
"--revision",
help="Read this branch head or commit instead of the revision the platform file pins",
)
args = parser.parse_args()
try:
scraper = scraper_class()
scraper = scraper_class(revision=args.revision) if takes_revision else scraper_class()
reqs = scraper.fetch_requirements()
except (OSError, ValueError, RuntimeError) as e:
_exit_on_scrape_error(e)
+23 -1
View File
@@ -1119,10 +1119,32 @@ def patched_paths(read: Callable[[str], str], patches: tuple[str, ...] = PATH_PA
return launchers
# Generators whose command line hands the emulator /userdata/bios folders as
# search paths: MAME's `-rompath` and `-samplepath` (mame/mameGenerator.py).
SEARCH_PATH_GENERATORS = ("mame/mameGenerator.py",)
def search_paths(cg: Configgen) -> list[Launcher]:
"""Every /userdata/bios path a generator's command line names, read as
KNULLI's generic reader reads its fork of the same generator."""
try:
from .knulli_launchers import GenericSites, bios_sites # noqa: PLC0415
except ImportError:
from knulli_launchers import GenericSites, bios_sites # type: ignore[no-redef] # noqa: PLC0415
# A boot disk image the command line names (the Macintosh's
# /userdata/bios/<boot_disk>.img) is a file, no search path.
return [
launcher
for path in SEARCH_PATH_GENERATORS
for launcher in bios_sites(cg, GenericSites(path, "passes_path"))
if re.match(r"command line -\w", launcher.passes_to or "")
]
EXTRACTORS: tuple[Callable[[Configgen], list[Launcher]], ...] = (
duckstation, duckstation_legacy, hatari, xemu, melonds, mupen64plus,
x16emu, gsplus, lexaloffle, environment_directories, config_directories,
core_file_options, working_directories,
core_file_options, working_directories, search_paths,
)
+13 -2
View File
@@ -37,14 +37,25 @@ class Launcher:
device: str | None = None
# The machines the platform offers under the record's systems.
machines: list[str] | None = None
# The platform systems the record is written for, none for every one.
systems: list[str] | None = None
# For a record citing a config: where the platform's code puts it
# ({path, source_ref}), whether that leaves a file already there, and
# the launch code rewriting its keys ([] when none does).
installs: dict[str, str] | None = None
kept_if_present: bool | None = None
overrides: list[str] | None = None
# The feature or option file listing the values the option written takes.
choices_from: str | None = None
def entry(self) -> dict[str, Any]:
"""The platform YAML form, in a fixed key order, unset keys left out."""
order = (
"emulator", "build", "kind", "slot", "names", "expands",
"emulator", "systems", "build", "kind", "slot", "names", "expands",
"case_insensitive", "search_dir", "passes_to",
"fails_when_missing", "fails_scope", "depends_on_option",
"device", "machines", "source_ref",
"device", "machines", "installs", "kept_if_present", "overrides",
"choices_from", "source_ref",
)
return {key: getattr(self, key) for key in order if getattr(self, key) is not None}
+51 -12
View File
@@ -44,6 +44,8 @@ BIOS = "${biosPath}"
EMULATION_BIOS = "${emulationPath}/bios"
STORAGE = "${storagePath}"
FLATPAK_DATA = "${HOME}/.var/app/"
# The function every EmuScript installs its Flatpak config with.
CONFIG_EMU_FP = "functions/configEmuFP.sh"
# EmuScripts file names that differ from the emulator profile they set up.
# The platform and target scrapers both read them here.
@@ -95,6 +97,31 @@ def _is_bios(value: str) -> bool:
return any(value == root or value.startswith(root + "/") for root in (BIOS, EMULATION_BIOS))
def with_evidence(tree: RepoTree, script: Script, record: Launcher, config: str) -> Launcher:
"""A record citing a shipped config, with the steps that install it.
configEmuFP rsyncs the repository's configs/<app> over the Flatpak's:
the _init call overwrites (keeping a .bak), every other call passes
--ignore-existing and leaves the user's file in place.
"""
fp = Script(CONFIG_EMU_FP, tree.read(CONFIG_EMU_FP))
rsync_line, _ = fp.find(r"^\s*rsync .*\$emudeckBackend/configs/", "rsync of the configs")
keep_line, _ = fp.find(r'overwrite="--ignore-existing"', "--ignore-existing")
calls = {n for n, line in script.code() if re.match(r"\s*configEmuFP\s", line)}
if not calls:
raise script.missing("configEmuFP call")
variable = script.assignment_ending("/" + config)
if variable is None:
raise script.missing(f"config variable for {config}")
record.installs = {
"path": script.expand(variable.value, variable.line, set()),
"source_ref": source_ref([(script.path, calls), (fp.path, {keep_line, rsync_line})]),
}
record.kept_if_present = True
record.overrides = []
return record
def _repo_config(script: Script, path: str) -> str:
"""The repository copy of a Flatpak config EmuDeck installs."""
if not path.startswith(FLATPAK_DATA):
@@ -268,7 +295,8 @@ def ares(tree: RepoTree) -> list[Launcher]:
raise LauncherPatternMissing(path, f"Firmware path under {old}")
for system, found in entries.items():
folder = posixpath.commonpath([posixpath.dirname(t) for _, t, _ in found])
records.append(
records.append(with_evidence(
tree, script,
Launcher(
emulator="ares",
build="standalone",
@@ -281,16 +309,20 @@ def ares(tree: RepoTree) -> list[Launcher]:
search_dir=folder,
passes_to="settings.bml "
+ ", ".join(f"{system}/Firmware/{k}" for k, _, _ in found),
)
)
),
posixpath.basename(path),
))
return records
def melonds(tree: RepoTree) -> list[Launcher]:
"""melonDS.ini paths set by changeLine, melonDS.toml paths shipped and rewritten by sed."""
name = "emuDeckMelonDS.sh"
records = setter_records(tree, name, option_key="ExternalBIOSEnable")
script = _script(tree, name)
records = [
with_evidence(tree, script, record, str(record.passes_to or "").split(" ", 1)[0])
for record in setter_records(tree, name, option_key="ExternalBIOSEnable")
]
# A config whose BIOS keys the setters write again keeps their values.
set_by_setters = {file for file, _, _, value, _ in setters(script) if _is_bios(value)}
for file, old, new, sed_lines in sed_rewrites(script, "melonDS_init"):
@@ -306,22 +338,29 @@ def melonds(tree: RepoTree) -> list[Launcher]:
continue
folder = posixpath.commonpath([posixpath.dirname(t) for _, t in found])
config = posixpath.basename(path)
option = next((s for s in settings(tree.read(path)) if s.key == "ExternalBIOSEnable"), None)
if option is None:
raise LauncherPatternMissing(path, "ExternalBIOSEnable")
shipped = {s.key: s for s in settings(tree.read(path))}
if "ExternalBIOSEnable" not in shipped or "ConsoleType" not in shipped:
raise LauncherPatternMissing(path, "ExternalBIOSEnable and ConsoleType")
option, console = shipped["ExternalBIOSEnable"], shipped["ConsoleType"]
# The DS keys are read under ExternalBIOSEnable, the DSi keys only
# when the console is a DSi (ConsoleType 1).
record = Launcher(
emulator="melonds",
build="standalone",
kind="fixed_name",
names=[posixpath.relpath(t, folder) for _, t in found],
source_ref=source_ref(
[(path, {option.line, *(s.line for s, _ in found)}), (script.path, sed_lines)]
),
source_ref=source_ref([
(path, {option.line, console.line, *(s.line for s, _ in found)}),
(script.path, sed_lines),
]),
search_dir=folder,
passes_to=describe_keys(config, tuple((s.section, s.key) for s, _ in found)),
depends_on_option=f"ExternalBIOSEnable = {option.value} in the shipped {config}",
depends_on_option=(
f"[DS] keys: ExternalBIOSEnable = true, {option.value} in the shipped {config}; "
f"[DSi] keys: ConsoleType = 1, {console.value} in the shipped {config}"
),
)
records.append(record)
records.append(with_evidence(tree, script, record, config))
if len(records) < 2:
raise script.missing("melonDS.toml BIOS paths rewritten by sed")
return records
+141 -65
View File
@@ -14,7 +14,7 @@ from __future__ import annotations
import posixpath
import re
from collections.abc import Callable
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from .configgen_launchers import Launcher
@@ -22,6 +22,8 @@ from .rocknix_launchers import fixed_paths
from .shell_launchers import (
LauncherPatternMissing,
Link,
config_placement,
evidence_fields,
RepoTree,
Script,
describe_keys,
@@ -38,6 +40,12 @@ EMULATORS = f"{SX05RE}/emulators"
LIBRETRO = f"{SX05RE}/libretro"
RETROARCH_MK = f"{SX05RE}/libretro_base/retroarch/package.mk"
BIOS_ROOT = "/storage/roms/bios"
EMUELEC_MK = f"{SX05RE}/emuelec/package.mk"
# The copy of every package's /usr/config into /storage/.config at each boot,
# an existing file kept (cp -i answered by false).
USERCONFIG = "packages/sysutils/systemd/scripts/userconfig-setup"
# The roms root that holds it (packages/sx05re/libretro_base/retroarch/package.mk:112,117).
ROMS_ROOT = "/storage/roms"
_EMU_TEST = re.compile(r'\$\{?EMU\}?"?\s*==?\s*"([^"]+)"')
_ARM = re.compile(r'^\s*((?:"[^"]+"\|?)+)\)\s*$')
@@ -102,6 +110,54 @@ class Runs:
return (RUN_EMU, set(self.of(name).lines))
def _storage_path(tree: RepoTree, target: str) -> str:
"""target with the /emuelec link resolved to the folder it points at.
The emuelec package links /emuelec to /storage/.config/emuelec, where
the first-boot copy of /usr/config lands.
"""
mk = _read(tree, EMUELEC_MK)
_line, link = mk.find(r"ln -sf (/storage/\S+) \$\{INSTALL\}(/emuelec)$", "/emuelec link")
if target == link.group(2) or target.startswith(link.group(2) + "/"):
return link.group(1) + target[len(link.group(2)):]
return target
def _evidence(
record: Launcher,
script: Script,
target: str,
keys: list[str],
source_name: str = "",
rewrites: Iterable[int] = (),
tree: RepoTree | None = None,
installed: Iterable[tuple[str, Iterable[int]]] = (),
) -> Launcher:
"""A config record with the lines that put its file in place: the
first-boot copy of /usr/config when ``tree`` is given, then the start
script's own. ``installed`` are the package.mk lines putting the file
in /usr/config.
``rewrites`` are lines the extractor read as rewriting the record's
values without naming their keys (advmame.sh's sed of /roms/mame).
"""
placements = []
if tree is not None:
setup = _read(tree, USERCONFIG)
placements.append(config_placement(
setup, _storage_path(tree, target), required=False, sources=("/usr/config/",)
))
placement = config_placement(script, target, keys, source_name=source_name,
required=not placements or not placements[0].install)
placement.overrides |= set(rewrites)
placements.append(placement)
fields = evidence_fields(placements, installed)
record.installs = fields["installs"]
record.kept_if_present = fields["kept_if_present"]
record.overrides = fields["overrides"]
return record
def _read(tree: RepoTree, path: str) -> Script:
return Script(path, tree.read(path))
@@ -315,7 +371,7 @@ def duckstation(tree: RepoTree, runs: Runs) -> list[Launcher]:
name = posixpath.basename(script.path)
lines = {found[k].line for k in (folder_key, *file_keys) if k in found}
unset = describe_keys("", file_keys).strip()
return [
return [_evidence(
Launcher(
emulator=runs.emulator(name),
build="standalone",
@@ -326,8 +382,13 @@ def duckstation(tree: RepoTree, runs: Runs) -> list[Launcher]:
),
search_dir=found[folder_key].value,
passes_to=f"settings.ini [BIOS] SearchDirectory (-settings), {unset} unset",
)
]
),
script,
script.expand("${CONFIG_DIR}/settings.ini", run_line, set()),
[f"[{s}] {k}" for s, k in (folder_key, *file_keys)],
tree=tree,
installed=[(mk.path, {mk_line})],
)]
YABASANSHIRO_SCRIPTS = (
@@ -471,7 +532,7 @@ def hatari(tree: RepoTree, runs: Runs) -> list[Launcher]:
mk = _read(tree, f"{package}/package.mk")
mk_line, _ = mk.find(r"cp -R \$\{PKG_DIR\}/config/\* ", "config install")
name = posixpath.basename(script.path)
return [
return [_evidence(
Launcher(
emulator=runs.emulator(name),
build="standalone",
@@ -483,12 +544,26 @@ def hatari(tree: RepoTree, runs: Runs) -> list[Launcher]:
),
search_dir=value.search_dir,
passes_to=f"{describe_keys(copy.group(1), value.keys)} (--configfile)",
)
]
),
script,
script.expand("${" + copy.group(2) + "}", copy_line, set()),
[f"[{s}] {k}" if s else k for s, k in value.keys],
source_name=copy.group(1),
)]
_ADVMAME_SYSTEM = re.compile(r'^\s*if \[\[ "\$\{1\}" = "([\w-]+)" \]\]; then$')
_ADVMAME_SED = re.compile(r'^\s*sed -i "s\|([^|]+)\|([^|]+)\|g" \$\{CONFIG_DIR\}/advmame\.rc$')
def advancemame(tree: RepoTree, runs: Runs) -> list[Launcher]:
"""Folder keys of the advmame.rc package.mk installs, one per device branch."""
"""Folder keys of the advmame.rc package.mk installs, one per device branch.
A key under the roms root is one too: dir_rom is /storage/roms/mame. The
start script rewrites the config for the system it is launched for
(advmame.sh:26-30): /roms/mame becomes /roms/arcade for arcade, so that
system reads its own record.
"""
package = f"{EMULATORS}/advancemame"
mk = _read(tree, f"{package}/package.mk")
installs = [
@@ -501,8 +576,8 @@ def advancemame(tree: RepoTree, runs: Runs) -> list[Launcher]:
by_value: dict[tuple[tuple[str, str], ...], list[tuple[str, set[int], int]]] = {}
for mk_line, file in installs:
path = f"{package}/config/{file}"
keys = [s for s in settings(tree.read(path), separator=" ") if _under(s.value)]
if not keys:
keys = [s for s in settings(tree.read(path), separator=" ") if _under(s.value, ROMS_ROOT)]
if not any(_under(s.value) for s in keys):
raise LauncherPatternMissing(path, f"key naming a folder under {BIOS_ROOT}")
value = tuple((s.key, s.value) for s in keys)
by_value.setdefault(value, []).append((path, {s.line for s in keys}, mk_line))
@@ -511,25 +586,47 @@ def advancemame(tree: RepoTree, runs: Runs) -> list[Launcher]:
((value, configs),) = by_value.items()
script = _read(tree, f"{package}/bin/advmame.sh")
run_line, _ = script.find(r"^\s*(?:\w+=\S+ )*advmame ", "advmame start")
test_line, test = script.find(_ADVMAME_SYSTEM.pattern, "system test", end=run_line)
sed_line, sed = script.find(_ADVMAME_SED.pattern, "system rewrite", test_line + 1, test_line + 1)
name = posixpath.basename(script.path)
refs = [
runs.ref(name),
*((path, lines) for path, lines, _ in configs),
(mk.path, {mk_line for _, _, mk_line in configs}),
(script.path, {run_line}),
]
return [
Launcher(
emulator=runs.emulator(name),
build="standalone",
kind="passes_path",
names=[],
source_ref=source_ref(refs),
search_dir=folder,
passes_to=f"advmame.rc {key}",
)
for key, folder in value
]
def refs(*lines: int) -> str:
return source_ref([
runs.ref(name),
*((path, lines) for path, lines, _ in configs),
(mk.path, {mk_line for _, _, mk_line in configs}),
(script.path, {run_line, *lines}),
])
target = script.expand("${CONFIG_DIR}/advmame.rc", run_line, set())
def proved(record: Launcher, key: str) -> Launcher:
return _evidence(record, script, target, [key], rewrites={sed_line}, tree=tree,
installed=[(mk.path, {mk_line for _, _, mk_line in configs})])
records = []
for key, folder in value:
rewritten = folder.replace(sed.group(1), sed.group(2))
if rewritten != folder:
# Every system but the one the script rewrites the key for, and
# that system with the rewritten folder.
records.append(proved(Launcher(
emulator=runs.emulator(name), build="standalone", kind="passes_path", names=[],
source_ref=refs(test_line, sed_line), search_dir=folder,
passes_to=f"advmame.rc {key}",
depends_on_option=f"system != {test.group(1)}",
), key))
records.append(proved(Launcher(
emulator=runs.emulator(name), build="standalone", kind="passes_path", names=[],
source_ref=refs(test_line, sed_line), search_dir=rewritten,
passes_to=f"advmame.rc {key}", systems=[test.group(1)],
), key))
continue
records.append(proved(Launcher(
emulator=runs.emulator(name), build="standalone", kind="passes_path", names=[],
source_ref=refs(), search_dir=folder, passes_to=f"advmame.rc {key}",
), key))
return records
def mame(tree: RepoTree, runs: Runs) -> list[Launcher]:
@@ -566,42 +663,11 @@ def mame(tree: RepoTree, runs: Runs) -> list[Launcher]:
)
if not records:
raise script.missing(f"copy into {BIOS_ROOT}")
ini = next((r for r in records if r.names == ["mame*"]), None)
if ini is None:
raise script.missing("copy of mame.ini")
option_path = f"{package}/config/MAME/MAME.opt"
option = next(
(s for s in settings(tree.read(option_path)) if s.key == "mame_read_config"), None
)
if option is None:
raise LauncherPatternMissing(option_path, "mame_read_config")
ini_path = f"{package}/config/ini/mame.ini"
# MAME reads from the folders its *path options name and writes to its
# *_directory ones.
folders = [
(s, [p for p in s.value.split(";") if _under(p)])
for s in settings(tree.read(ini_path), separator=" ")
if s.key.endswith("path")
]
folders = [(s, parts) for s, parts in folders if parts]
if not folders:
raise LauncherPatternMissing(ini_path, f"path under {BIOS_ROOT}")
for setting, parts in folders:
for part in parts:
records.append(
Launcher(
emulator=emulator,
build="libretro",
kind="passes_path",
names=[],
source_ref=source_ref(
[(ini_path, {setting.line}), (option_path, {option.line})]
) + f", {ini.source_ref}",
search_dir=part.rstrip("/"),
passes_to=f"mame.ini {setting.key}",
depends_on_option=f"mame_read_config = {option.value}",
)
)
# mame.ini hands the core no folder: MAME.opt turns on
# mame_mame_paths_enable, so the core passes no path option
# (libretro mame src/osd/libretro/libretro-internal/retro_init.cpp:554-555),
# and the ini MAME would read sits under a working directory no launcher
# sets (src/emu/emuopts.cpp:49). Only the copies are the launcher's.
return records
@@ -616,6 +682,16 @@ def scummvm(tree: RepoTree, runs: Runs) -> list[Launcher]:
core_line, core = script.find(r"-L /tmp/cores/(\w+)_libretro\.so", "libretro start")
arm_line, arm = script.find(r'^\s*"(\w+)"\)', "setup arm", core_line)
copy_line, copy = script.find(r"^\s*cp (\S+) (\S+)$", "copy into the BIOS folder", arm_line)
launched = sorted({
m.group(1) for _, line in runs.script.code()
if (m := re.search(rf"\b{re.escape(name)} (\w+)", line))
})
if not launched:
raise runs.script.missing(f"start of {name} with an action")
action = f"{name} {arm.group(1)}"
if arm.group(1) not in launched:
# The copy runs from the setup action, never from a launch.
action += f", an action no launch runs ({RUN_EMU.rsplit('/', 1)[-1]} passes {', '.join(launched)})"
used = {copy_line}
source = script.expand(copy.group(1), copy_line, used)
target = script.expand(copy.group(2), copy_line, used)
@@ -641,7 +717,7 @@ def scummvm(tree: RepoTree, runs: Runs) -> list[Launcher]:
search_dir=posixpath.dirname(source),
passes_to=target,
fails_when_missing=False,
depends_on_option=f"{name} {arm.group(1)}",
depends_on_option=action,
),
]
+12 -4
View File
@@ -1001,6 +1001,14 @@ def boot_disks(
emulator = (
", ".join(_caller_cores(cg, spec.caller)) if spec.caller else cg.emulator(module)
)
if spec.caller and spec.feature[:2] == ("libretro", "cores"):
# The option is offered for one core of the system: es_features
# lists it under that core, the other cores the generator serves
# never see it (KNULLI's macintosh offers mame alone).
core = spec.feature[2]
if core not in emulator.split(", "):
src.fail(f"es_features offers the option for {core}, which the generator does not serve")
emulator = core
found = 0
for chain in ast.walk(src.tree):
if not (
@@ -1054,10 +1062,10 @@ def boot_disks(
expands={option: values}, case_insensitive=False, search_dir=cg.bios,
passes_to=f"command line {flag}", fails_when_missing=False,
depends_on_option=f"{option} ({' and '.join(tests)})",
source_ref=", ".join([
src.ref([*spans, src.span(statement), _lines(added)]),
f"{ES_FEATURES}:{lines[0]}-{lines[1]}" if not listed else "",
]).rstrip(", "),
# The values the menu offers come from es_features.yml;
# the generator writing the choice is the evidence.
choices_from=None if listed else f"{ES_FEATURES}:{lines[0]}-{lines[1]}",
source_ref=src.ref([*spans, src.span(statement), _lines(added)]),
))
if not found:
src.fail("names no BIOS file from an option value")
+4
View File
@@ -453,6 +453,10 @@ def release_profile(
name = f"{set_name}.zip"
entry: dict[str, Any] = {
"name": name,
# The libretro build searches the content folder, then
# <system>/mame/bios and <system>/mame/roms (retro_init.cpp,
# Set_Path_Option): the system folder itself is not read.
"path": f"mame/bios/{name}",
"required": settled_required(known.get(name, {}), data),
"category": "bios_zip",
}
+167 -14
View File
@@ -14,6 +14,11 @@ import bisect
import re
from collections.abc import Callable, Iterator
try:
from .shell_launchers import is_feature_ref, split_ref
except ImportError:
from shell_launchers import is_feature_ref, split_ref # type: ignore[no-redef]
GENERATORS = "emulatorLauncher/Generators"
FEATURES = ".emulationstation/es_features.cfg"
@@ -1254,6 +1259,11 @@ def xemu(sources: dict[str, Source]) -> list[Record]:
)
flash = src.find(r'isOptSet\("(xemu_flashrom)"\)', "xemu_flashrom")
# The flashrom is written outside a Chihiro launch only.
chihiro_set = src.find(r"(_chihiro) = \(([^;]+)\);", "Chihiro test")
chihiro_guard = src.find_all(
rf"if \(!{chihiro_set.group(1)}\)", "flashrom guard", end=flash.start()
)[-1]
flash_default = src.find(
r'ini\.WriteValue\("([\w.]+)", "(flashrom_path)", "\'" \+ Path\.Combine\(flashromPath, "([^"]+)"\)',
"flashrom default",
@@ -1267,7 +1277,10 @@ def xemu(sources: dict[str, Source]) -> list[Record]:
"core_option",
_unique([flash_default.group(3), *choices]),
source_ref(
(src.path, [src.lines(flash.start(), flash_default.end())]),
(src.path, [
src.lines(chihiro_set.start(), chihiro_set.end()),
src.lines(chihiro_guard.start(), flash_default.end()),
]),
(features.path, [choice_lines]),
),
case_insensitive=True,
@@ -1277,7 +1290,7 @@ def xemu(sources: dict[str, Source]) -> list[Record]:
f" default {flash_default.group(3)}"
),
fails_when_missing="path written without an existence check",
depends_on_option=flash.group(1),
depends_on_option=f"{flash.group(1)}, not ({chihiro_set.group(2)})",
)
)
@@ -1855,13 +1868,27 @@ def _root_writes(src: Source, emulator: str) -> list[Record]:
if root_reach is None:
continue
method = root_reach[0]
# A folder below the root, `string x = Path.Combine(root, "cdb")`
# that the method creates or tests as a directory. A file below it
# is a guarded write's, read by _guarded_write.
folders = {root.group(1): ("bios", root)}
for sub in re.compile(
rf"string (\w+) = Path\.Combine\({root.group(1)}, ((?:{STRING}, )*{STRING})\);"
).finditer(src.text, root.end(), method[1]):
if re.search(
rf"\b(?:\w*CreateDirectory|Directory\.Exists)\({sub.group(1)}\)",
src.text[sub.end() : method[1]],
):
folders[sub.group(1)] = ("/".join(["bios", *_strings(sub.group(2))]), sub)
names = "|".join(map(re.escape, folders))
for write in re.compile(
rf'(\w+)\.WriteValue\("([^"]*)", "([^"]+)", (?:"\'" \+ )?{root.group(1)}(?: \+ "\'")?\);'
rf'(\w+)\.WriteValue\("([^"]*)", "([^"]+)", (?:"\'" \+ )?({names})(?: \+ "\'")?\);'
).finditer(src.text, root.end(), method[1]):
reached = _conditions(src, write.start())
if reached is None:
continue
writer, section, key = write.groups()
writer, section, key, held = write.groups()
folder, declared = folders[held]
target = f"[{section}] {key}" if section else key
records.append(
_record(
@@ -1875,12 +1902,14 @@ def _root_writes(src: Source, emulator: str) -> list[Record]:
[
*reached[2],
src.lines(root.start(), root.end()),
*([src.lines(declared.start(), declared.end())]
if declared is not root else []),
src.lines(write.start(), write.end()),
],
)
),
search_dir="bios",
passes_to=f"{_config_name(src, method, writer)} {target} = bios",
search_dir=folder,
passes_to=f"{_config_name(src, method, writer)} {target} = {folder}",
fails_when_missing=False,
depends_on_option=", ".join(reached[1]) or None,
)
@@ -2363,11 +2392,7 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record
gate = src.find(
rf'if \(SystemConfig\.isOptSet\("{option}"\)', f"{option} gate", method[0], override.start()
)
gate_block = src.block_at(gate.end())
if not gate_block[0] < override.start() < gate_block[1]:
raise LauncherPatternMissing(
src.path, f"{option} block around line {src.line(override.start())}"
)
gate_block = _gate_span(src, gate, override)
write = re.compile(
rf'(\w+)\.WriteValue\("([^"]*)", "([^"]+)", ([^;\n]*\b{var}\b[^;\n]*)\);'
).search(code, override.end(), method[1])
@@ -2377,6 +2402,8 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record
guarded = re.compile(rf"if \(File\.Exists\({var}\)[^\n]*\)\s*$").search(
code, method[0], write.start()
)
flag = None if guarded else _flag_guard(code, var, method[0], write.start())
guarded = guarded or flag
skipped = re.findall(
rf'SystemConfig\["{option}"\] != "(\w+)"', code[gate.start() : write.end()]
)
@@ -2384,8 +2411,13 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record
target = f"{config} [{section}] {key}" if section else f"{config} {key}"
suffix = ", only if the file exists" if guarded else ", written without an existence check"
fails = f"{key} not written" if guarded else "path written without an existence check"
write_span = src.lines(_statement_start(src, write.start()), write.end())
write_span = src.lines(
flag.start() if flag else _statement_start(src, write.start()), write.end()
)
choices, choice_lines = feature_choices(features, emulator, option)
fallback = _fallback_names(src, var, gate_block[1], write.start())
if fallback is not None:
fails = f"{', then '.join(fallback[0])}, instead, else {fails}"
records = []
default = list(
re.compile(rf'string {var} = Path\.Combine\({_BIOS_ROOT}, "([^"]+)"\);').finditer(
@@ -2424,9 +2456,71 @@ def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record
depends_on_option=option,
)
)
if fallback is not None:
names, span = fallback
unset = f"{default[-1].group(1)} absent with {option} unset" if default else None
chosen = f"the {option} file absent" + (
f", {option} not {' or '.join(skipped)}" if skipped else ""
)
records.append(
_record(
emulator,
"standalone",
"names_searched",
names,
_path_parts(src, span, write_span),
case_insensitive=True,
search_dir="bios",
passes_to=f"{target} = <first found>{suffix}",
fails_when_missing=f"{key} not written" if guarded else fails,
depends_on_option=" or ".join(c for c in (unset, chosen) if c),
)
)
return records + _root_writes(src, emulator)
def _gate_span(src: Source, gate: re.Match[str], override: re.Match[str]) -> tuple[int, int]:
"""The span an option gate governs: its block, or the one statement a
braceless if runs, which must be the override."""
paren = gate.start() + len("if ")
after = paren + len(_call_args(src, paren)) + 2
if re.match(r"\s*\{", src.text[after:]):
block = src.block_at(after)
else:
block = (after, _statement_end(src, after))
if not block[0] < override.start() < block[1]:
raise LauncherPatternMissing(
src.path, f"option block around line {src.line(override.start())}"
)
return block
def _flag_guard(code: str, var: str, start: int, end: int) -> re.Match[str] | None:
"""A write under `if (flag)` where flag holds File.Exists of the path."""
flag = re.compile(rf"bool (\w+) = [^;\n]*\bFile\.Exists\({var}\)[^;\n]*;").search(
code, start, end
)
if flag is None or not re.compile(rf"if \({flag.group(1)}\)\s*$", re.M).search(
code, flag.end(), end
):
return None
return flag
def _fallback_names(
src: Source, var: str, start: int, end: int
) -> tuple[list[str], tuple[int, int]] | None:
"""Names tried in bios, first existing one kept, when the chosen file is absent."""
found = re.compile(
rf"if \(([^\n]*!File\.Exists\({var}\)[^\n]*)\)\s*"
rf"{var} = new\[\] \{{ (?P<names>(?:{STRING}(?:, )?)+) \}}\.Select\((?P<arg>\w+) => "
rf"Path\.Combine\({_BIOS_ROOT}, (?P=arg)\)\)\.FirstOrDefault\(File\.Exists\) \?\? {var};"
).search(_code(src), start, end)
if found is None:
return None
return _strings(found.group("names")), src.lines(found.start(), found.end())
OPTION_PATHS = {
f"{GENERATORS}/Kronos.Generator.cs": "kronos",
f"{GENERATORS}/SSF.Generator.cs": "ssf",
@@ -3336,7 +3430,11 @@ def mame(sources: dict[str, Source]) -> list[Record]:
raise LauncherPatternMissing(own.path, "MAME folder arguments")
records = _covered(
own,
[_with_conditions(record, conditions) for record, conditions in found],
[
split
for record, conditions in found
for split in _per_emulator(own, _with_conditions(record, conditions))
],
# The bezel artwork folder is read by the launcher, not passed.
skip=(_BIOS_GUARD, r"ConfigureBezels\("),
)
@@ -3424,6 +3522,42 @@ def xroar(sources: dict[str, Source]) -> list[Record]:
return _covered(src, records)
_EMULATOR_BRANCH = re.compile(r"([^\s;<>]+) when (\w+), else ([^\s;<>]+)")
def _per_emulator(src: Source, record: Record) -> list[Record]:
"""A directory chosen by the emulator the generator runs, one record each.
Mame64.Generator.cs sets `bool hbmame = emulator == "hbmame";` and passes
`-sp bios/hbmame/samples` for it, bios/mame/samples for mame64. A choice
on any other condition is left as it reads.
"""
rendered = str(record.get("search_dir", ""))
branch = _EMULATOR_BRANCH.fullmatch(rendered)
if branch is None:
return [record]
chosen, flag, default = branch.groups()
declared = re.search(rf'bool {flag} = emulator == "([\w.-]+)";', _code(src))
if declared is None:
return [record]
ref = str(record["source_ref"])
if not ref.startswith(src.path + ":"):
raise LauncherPatternMissing(src.path, f"source of the directory choice {rendered!r}")
spans = [
(int(first), int(last or first))
for first, _, last in (s.partition("-") for s in ref[len(src.path) + 1:].split(", "))
]
spans.append(src.lines(declared.start(), declared.end()))
prefix = str(record["passes_to"]).removesuffix(rendered).strip()
out = []
for emulator, directory in ((declared.group(1), chosen), (record["emulator"], default)):
split = {k: v for k, v in record.items() if k != "source_ref"}
split.update(emulator=emulator, search_dir=directory, passes_to=f"{prefix} {directory}")
split["source_ref"] = _path_parts(src, *spans)
out.append(split)
return out
_SYSTEM_BRANCH = re.compile(r'(\S+), or (\S+) when system == "([\w.-]+)"')
@@ -3850,4 +3984,23 @@ def extract_launchers(texts: dict[str, str]) -> list[Record]:
if missing:
raise LauncherPatternMissing(missing[0], "source file")
sources = {path: Source(path, text) for path, text in texts.items()}
return [record for extractor in EXTRACTORS for record in extractor(sources)]
return [
_choices_apart(record) for extractor in EXTRACTORS for record in extractor(sources)
]
def _choices_apart(record: Record) -> Record:
"""The es_features.cfg part of a record's source_ref, moved to choices_from.
The feature file lists the values a menu option offers. The generator
writing the choice is the record's evidence, never the list.
"""
parts = split_ref(str(record["source_ref"]))
listed = [p for p in parts if is_feature_ref(p)]
if not listed:
return record
code = [p for p in parts if not is_feature_ref(p)]
if not code:
raise LauncherPatternMissing(listed[0], "generator code beside the option list")
moved = {k: v for k, v in record.items() if k != "source_ref"}
return {**moved, "choices_from": ", ".join(listed), "source_ref": ", ".join(code)}
+31 -3
View File
@@ -12,6 +12,7 @@ import json
import re
import urllib.error
import urllib.request
from pathlib import Path
try:
from .base_scraper import (
@@ -39,6 +40,7 @@ except ImportError:
from retrobat_launchers import extract_launchers
PLATFORM_NAME = "retrobat"
PLATFORM_FILE = Path(__file__).resolve().parents[2] / "platforms" / "retrobat.yml"
LAUNCHER_REPO = "RetroBat-Official/emulatorlauncher"
SOURCE_URL = (
@@ -132,6 +134,28 @@ def launcher_revision(url: str) -> str:
return found.group(1)
def pinned_revision(platform_file: Path = PLATFORM_FILE) -> str:
"""The emulatorLauncher commit platforms/retrobat.yml was read from.
A rescrape reads this commit unless told to move, so a change to an
extractor shows in the diff alone, without upstream's commits since.
"""
from common import yaml_load
with platform_file.open(encoding="utf-8") as fh:
source = str((yaml_load(fh) or {}).get("source") or "")
return launcher_revision(source)
def resolve_revision(revision: str | None) -> str:
"""The commit to read: the pin when None, a branch's head, or a sha."""
if revision is None:
return pinned_revision()
if re.fullmatch(r"[0-9a-f]{40}", revision):
return revision
return fetch_branch_head(LAUNCHER_REPO, revision)
def fetch_launchers(rev: str) -> list[dict]:
"""Launcher records read from the generators at the commit the BIOS list comes from."""
texts = {
@@ -160,10 +184,14 @@ SYSTEM_SLUG_MAP = {
class Scraper(BaseScraper):
"""Scraper for RetroBat batocera-systems.json."""
def __init__(self, url: str | None = None) -> None:
# batocera-systems.json is read from master: the commit read is recorded.
def __init__(self, url: str | None = None, revision: str | None = None) -> None:
# The BIOS list and the generators are read at one commit, the one
# platforms/retrobat.yml pins unless a revision moves it (--revision
# master reads the branch head). The commit read is recorded.
if url is None:
url = SOURCE_URL.format(rev=fetch_branch_head(LAUNCHER_REPO, "master"))
url = SOURCE_URL.format(rev=resolve_revision(revision))
elif revision is not None:
raise ValueError("pass a url or a revision, not both")
super().__init__(url=url)
self._parsed: dict | None = None
+68 -13
View File
@@ -30,7 +30,13 @@ except ImportError:
BIOS = "$bios_path"
PLACEHOLDER = "RETRODECKBIOSDIR"
# The roms folder in the same presets: GZDoom's IWADSearch.Directories holds
# RETRODECKROMSDIR/doom (gzdoom/rd_assets/rd_config/gzdoom.ini:9), which
# gzdoom/component_prepare.sh:27 rewrites to $roms_path.
ROMS_PLACEHOLDER = "RETRODECKROMSDIR"
CORE_OPTIONS = "retroarch/rd_assets/rd_config/retroarch-core-options.cfg"
# XRoar ROM lists RetroDECK's xroar.conf defines that no machine looks up.
UNREAD_ROMLISTS = frozenset({"coco1", "coco1e", "coco1e_ext", "coco2", "coco2_ext", "coco2b"})
# The component that runs libretro cores.
LIBRETRO_COMPONENT = "retroarch"
# Values of a core option that name a file rather than a setting.
@@ -282,7 +288,11 @@ class Component:
)
def _preset(self, script: Script, number: int, words: list[str]) -> None:
"""`sed -i "s#RETRODECKBIOSDIR#${bios_path}#g" "$cfg"` on a preset copied just above."""
"""`sed -i "s#RETRODECKBIOSDIR#${bios_path}#g" "$cfg"` on a preset copied just above.
Each line naming the BIOS or the roms folder is a record: a search
list can mix them (XRoar's rompath, GZDoom's IWAD directories).
"""
target = words[-1]
substitutions = self._substitutions(script, target)
copied = None
@@ -293,6 +303,19 @@ class Component:
if copied is None:
raise LauncherPatternMissing(f"{script.path}:{number}", f"no preset copied to {target}")
preset = f"{self.name}/rd_assets/rd_config/{copied[1]}"
# The reset copies the preset over the user's file, then fills its
# placeholders: that is the install, and nothing keeps an older file.
evidence: dict[str, Any] = {
"installs": {
"path": target,
"source_ref": source_ref(
[(script.path, copied[0])]
+ [(script.path, line) for _v, line in substitutions.values()]
),
},
"kept_if_present": False,
"overrides": self.launch_rewrites(target),
}
text = self.read(preset)
if text is None:
raise LauncherPatternMissing(preset, "preset is missing")
@@ -302,40 +325,67 @@ class Component:
stripped = line.strip()
if re.fullmatch(r"\[[^\]]+\]", stripped):
section = stripped
if PLACEHOLDER not in stripped or stripped.startswith("#"):
if stripped.startswith("#") or not any(
p in stripped for p in (PLACEHOLDER, ROMS_PLACEHOLDER)
):
continue
setting = re.match(r"^([\w.$()-]+)\s*(?:=|\s)\s*(.+)$", stripped)
if setting is None:
raise LauncherPatternMissing(f"{preset}:{line_no}", f"placeholder in {stripped}")
named = [p for p in substitutions if p in stripped]
if PLACEHOLDER not in stripped and not named:
# A roms placeholder the script leaves as written.
continue
key, value = setting.group(1), _unquote(setting.group(2))
for placeholder, variable in substitutions.items():
for placeholder, (variable, _line) in substitutions.items():
value = value.replace(placeholder, variable)
where = f"{section} {key}" if section else key
found += 1
applied = [(script.path, copied[0]), (script.path, number)]
found += PLACEHOLDER in stripped
applied = [(script.path, copied[0]), (script.path, number)] + [
(script.path, substitutions[p][1]) for p in named
]
self.record(
"passes_path", [], [(preset, line_no)] + applied,
search_dir=value, passes_to=f"{self.config_name(target)} {where}",
fails_when_missing=False,
fails_when_missing=False, **evidence,
)
if key == "rompath":
self.romlists(preset, text, value, applied)
self.romlists(preset, text, value, applied, evidence)
if not found:
raise LauncherPatternMissing(preset, f"no {PLACEHOLDER} line")
@staticmethod
def _substitutions(script: Script, target: str) -> dict[str, str]:
def _substitutions(script: Script, target: str) -> dict[str, tuple[str, int]]:
"""Each placeholder sed rewrites in ``target``: (variable, line)."""
found = {}
for line in script.lines:
for line_no, line in enumerate(script.lines, 1):
for m in re.finditer(r"s#(RETRODECK\w+)#\$\{?(\w+)\}?#g[\"']?\s+\"([^\"]+)\"", line):
if m.group(3) == target:
found[m.group(1)] = f"${m.group(2)}"
found[m.group(1)] = (f"${m.group(2)}", line_no)
return found
def launch_rewrites(self, target: str) -> list[str]:
"""The sed lines of the component launcher rewriting ``target``."""
path = f"{self.name}/component_launcher.sh"
text = self.read(path)
if text is None:
return []
return [
source_ref([(path, number)])
for number, line in enumerate(text.splitlines(), 1)
if re.search(r"\bsed\b.*\s-i\b", line) and target in line
]
def romlists(
self, preset: str, text: str, rompath: str, applied: list[tuple[str, int]]
self, preset: str, text: str, rompath: str, applied: list[tuple[str, int]],
evidence: dict[str, Any],
) -> None:
"""XRoar's `romlist NAME=a,b,@other`: the names tried for each ROM, in order."""
"""XRoar's `romlist NAME=a,b,@other`: the names tried for each ROM, in order.
A list no XRoar machine or cartridge looks up is no read: coco1,
coco1e, coco1e_ext, coco2, coco2_ext and coco2b are defined by XRoar
(src/xroar.c:663-670) and named by nothing else.
"""
lists: dict[str, tuple[int, list[str]]] = {}
for line_no, line in enumerate(text.splitlines(), 1):
found = re.match(r"^romlist\s+([\w-]+)=(.*)$", line.strip())
@@ -358,10 +408,12 @@ class Component:
return list(dict.fromkeys(names))
for name, (line_no, _items) in lists.items():
if name in UNREAD_ROMLISTS:
continue
self.record(
"names_searched", expand(name, (name,)), [(preset, line_no)] + applied,
slot=name, search_dir=rompath, passes_to=f"romlist {name}",
fails_when_missing=False,
fails_when_missing=False, **evidence,
)
def read_launcher(self) -> None:
@@ -463,6 +515,7 @@ def core_options(read: Read) -> list[Launcher]:
]
if not copied:
raise LauncherPatternMissing(prepare_path, "the core options preset is never copied")
target = _words(prepare.splitlines()[copied[0] - 1].strip())[-1]
records = []
for line_no, line in enumerate(text.splitlines(), 1):
found = re.match(r'^([\w.-]+)\s*=\s*"([^"]*)"$', line.strip())
@@ -472,6 +525,8 @@ def core_options(read: Read) -> list[Launcher]:
records.append(Launcher(
emulator=LIBRETRO_COMPONENT, build="libretro", kind="core_option", names=[value],
passes_to=f"core option {key}", fails_when_missing=False,
installs={"path": target, "source_ref": source_ref([(prepare_path, copied[0])])},
kept_if_present=False, overrides=[],
source_ref=source_ref([(CORE_OPTIONS, line_no), (prepare_path, copied[0])]),
))
if not records:
+43 -1
View File
@@ -32,6 +32,9 @@ SECTIONS = ("emulators", "libretrocores", "ports")
PACKAGES_SCRIPT = "retropie_packages.sh"
BIOSDIR = "$biosdir"
# The roms root (retropie_packages.sh:47-49): MAME's mame.ini lists rom,
# sample and artwork folders below it (scriptmodules/emulators/mame.sh:133-136).
ROMDIR = "$romdir"
# The package whose config every lr- core runs under.
LIBRETRO_FRONTEND = "retroarch"
# The launch scripts copied next to an emulator spell the directory out.
@@ -91,6 +94,11 @@ class Launcher:
passes_to: str | None = None
fails_when_missing: bool | str | None = None
depends_on_option: str | None = None
# For a record citing a config: where the platform's code puts it, whether
# that leaves a file already there, and the launch code rewriting it.
installs: dict[str, str] | None = None
kept_if_present: bool | None = None
overrides: list[str] | None = None
lines: list[tuple[str, int]] = field(default_factory=list, repr=False)
def entry(self) -> dict[str, Any]:
@@ -98,7 +106,8 @@ class Launcher:
order = (
"emulator", "package", "repo", "systems", "build", "kind", "slot",
"names", "case_insensitive", "search_dir", "passes_to",
"fails_when_missing", "depends_on_option", "source_ref",
"fails_when_missing", "depends_on_option", "installs", "kept_if_present",
"overrides", "source_ref",
)
return {key: getattr(self, key) for key in order if getattr(self, key) is not None}
@@ -464,6 +473,31 @@ class Scripts:
return results
# The character each program splits a search list on, read in its code.
# AdvanceMAME strtoks dir_rom on file_dir_separator(), ':' on Linux, in all
# three builds RetroPie ships (advance/linux/file.c:138-141 and
# advance/osd/fileio.c:696-699 at 96237a5, 685-688 at advancemame-1.4,
# 640-643 in advancemame-0.94.0.tar.gz). MAME's path_iterator splits on ';'
# whatever the system (src/emu/fileio.cpp:56, 64, 112 at mame0289).
LIST_SEPARATORS = {"advmame": ":", "advmame-0.94": ":", "advmame-1.4": ":"}
DEFAULT_LIST_SEPARATOR = ";"
def _search_list_in_roms(event: "Event", separator: str = DEFAULT_LIST_SEPARATOR) -> bool:
"""An iniSet whose value is a list of folders below the roms root.
One folder alone is where a program writes (cfg_directory, nvram_directory
and the others MAME's mame.ini sets): a list is where it searches, split
on the separator the program reads it with.
"""
if len(event.words) < 3 or len(event.words[2]) != 1:
return False
parts = [p for p in event.words[2][0].split(separator) if p]
return len(parts) > 1 and all(
p.startswith(ROMDIR + "/") or p.startswith("${romdir}/") for p in parts
)
def _mentions_bios(text: str) -> bool:
return BIOSDIR in text or "${biosdir}" in text or BIOS_SPELLED in text
@@ -541,6 +575,14 @@ class PackageReader:
if command == "addEmulator":
self._add_emulator(event)
return
if command == "iniSet" and not _mentions_bios(event.raw):
# A search path below the roms root: MAME reads its samples from
# samplepath $romdir/mame/samples;$romdir/arcade/samples.
if _search_list_in_roms(
event, LIST_SEPARATORS.get(self.package.id, DEFAULT_LIST_SEPARATOR)
):
self._ini_set(event)
return
if not _mentions_bios(event.raw):
return
if command in HOUSEKEEPING:
+149 -28
View File
@@ -18,6 +18,7 @@ from dataclasses import dataclass
try:
from .configgen_launchers import Launcher
from .shell_launchers import config_placement, evidence_fields
from .shell_launchers import (
LauncherPatternMissing,
Link,
@@ -30,6 +31,7 @@ try:
)
except ImportError:
from configgen_launchers import Launcher
from shell_launchers import config_placement, evidence_fields # type: ignore[no-redef]
from shell_launchers import (
LauncherPatternMissing,
Link,
@@ -46,6 +48,9 @@ DEVICES = f"{ROCKNIX}/devices"
STANDALONE = f"{ROCKNIX}/packages/emulators/standalone"
RETROARCH = f"{ROCKNIX}/packages/emulators/libretro/retroarch"
BIOS_ROOT = "/storage/roms/bios"
CONFIG_ROOT = "/storage/.config"
# The first-boot step copying every package's /usr/config to /storage/.config.
USERCONFIG = f"{ROCKNIX}/packages/sysutils/systemd/scripts/userconfig-setup"
Lines = list[tuple[str, set[int]]]
@@ -186,6 +191,38 @@ def bios_keys(tree: RepoTree, paths: list[str], root: str = BIOS_ROOT) -> list[t
return keys
def with_evidence(
tree: RepoTree,
record: Launcher,
target: str,
keys: list[str],
start: Script | None = None,
writers: tuple[str, ...] = (),
source_name: str = "",
) -> Launcher:
"""A config record with the steps that put its file at ``target``.
The first boot copies /usr/config to /storage/.config, leaving a file
already there. A start script can copy or generate it again, and its
sed lines rewriting one of the record's keys are the overrides.
"""
setup = Script(USERCONFIG, tree.read(USERCONFIG))
placements = [config_placement(setup, target, required=False, sources=("/usr/config/",))]
if start is not None:
placements.append(config_placement(
start, target, keys, writers, source_name, required=False
))
fields = evidence_fields(placements)
record.installs = fields["installs"]
record.kept_if_present = fields["kept_if_present"]
record.overrides = fields["overrides"]
return record
def _keys(value: FixedPaths) -> list[str]:
return [f"[{section}] {key}" if section else key for section, key in value.keys]
def config_records(
tree: RepoTree,
emulator: str,
@@ -193,10 +230,17 @@ def config_records(
file: str,
passes_to_suffix: str = "",
depends_on_option: str | None = None,
target: str = "",
start: Script | None = None,
unread: Callable[[tuple[str, str]], bool] = lambda key: False,
) -> list[Launcher]:
"""fixed_name records for the bios paths of a config installed per device."""
"""fixed_name records for the bios paths of a config installed per device.
``unread`` drops the keys the shipped configs leave the emulator
reading no file from.
"""
configs = device_configs(tree, package, file)
keys = bios_keys(tree, [c.path for c in configs])
keys = [k for k in bios_keys(tree, [c.path for c in configs]) if not unread(k)]
name = posixpath.basename(file)
def read(path: str, text: str) -> tuple[object, set[int]]:
@@ -206,7 +250,8 @@ def config_records(
for device, value, refs in per_device(tree, configs, f"{package}/package.mk", read):
assert isinstance(value, FixedPaths)
described = describe_keys(name, value.keys)
records.append(
records.append(with_evidence(
tree,
Launcher(
emulator=emulator,
build="standalone",
@@ -219,8 +264,11 @@ def config_records(
),
device=device,
depends_on_option=depends_on_option,
)
)
),
target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}",
_keys(value),
start,
))
return records
@@ -241,7 +289,8 @@ def retroarch(tree: RepoTree) -> list[Launcher]:
for device, value, refs in per_device(tree, configs, f"{RETROARCH}/package.mk", read):
assert isinstance(value, tuple)
values = dict(value)
records.append(
records.append(with_evidence(
tree,
Launcher(
emulator="retroarch",
build="libretro",
@@ -251,8 +300,10 @@ def retroarch(tree: RepoTree) -> list[Launcher]:
search_dir=values["system_directory"],
passes_to="retroarch.cfg " + ", ".join(f'{k} = "{v}"' for k, v in value),
device=device,
)
)
),
f"{CONFIG_ROOT}/retroarch/retroarch.cfg",
[k for k, _ in value],
))
return records
@@ -275,6 +326,19 @@ def amiberry(tree: RepoTree) -> list[Launcher]:
)
used: set[int] = {test_line, then_line, else_line, other_line, sed_line}
root = script.expand("${" + sed.group(2) + "}", sed_line, used)
written = re.search(r'"?(\$\{?\w+\}?)"?\s*$', script.lines[then_line - 1])
if written is None:
raise script.missing("destination of the config copy")
target = script.expand(written.group(1), then_line, set())
# A WHDLoad archive is booted by --autoload, which builds its own setup
# (kickstart included) over the config: the record holds for floppies.
autoload = [n for n, line in script.code() if re.search(r"amiberry .*--autoload", line)]
if not autoload:
raise script.missing("WHDLoad boot with --autoload")
content = (
"content not booted with --autoload, a WHDLoad .lha or .zip "
f"({posixpath.basename(script.path)}:{', '.join(map(str, autoload))})"
)
records = []
for config, condition in (
(then.group(1), f"game name matches {test.group(1)}"),
@@ -290,7 +354,8 @@ def amiberry(tree: RepoTree) -> list[Launcher]:
raise LauncherPatternMissing(path, f"key naming a file under {sed.group(1)}")
value, lines = fixed_paths(found, keys, path)
slot = re.fullmatch(r"Amiga(\w+)-default\.uae", config)
records.append(
records.append(with_evidence(
tree,
Launcher(
emulator="amiberry",
build="standalone",
@@ -300,9 +365,13 @@ def amiberry(tree: RepoTree) -> list[Launcher]:
slot=slot.group(1) if slot else config,
search_dir=value.search_dir,
passes_to=f"{describe_keys(config, value.keys)} (amiberry -f)",
depends_on_option=condition,
)
)
depends_on_option=f"{condition}, {content}",
),
target,
_keys(value),
script,
source_name=config,
))
mk = Script(f"{package}/package.mk", tree.read(f"{package}/package.mk"))
links = mk.links(BIOS_ROOT, fixed={"INSTALL": ""})
if not links:
@@ -375,7 +444,11 @@ def hatari(tree: RepoTree) -> list[Launcher]:
if not keys:
raise LauncherPatternMissing(path, f"key naming a file under {BIOS_ROOT}")
value, lines = fixed_paths(found, keys, path)
return [
copied = re.search(r'"?(\$\{?\w+\}?)"?\s*$', script.lines[copy_line - 1])
if copied is None:
raise script.missing("destination of the default config copy")
return [with_evidence(
tree,
Launcher(
emulator="hatari",
build="standalone",
@@ -384,8 +457,12 @@ def hatari(tree: RepoTree) -> list[Launcher]:
source_ref=source_ref([(path, lines), (script.path, {copy_line, run_line})]),
search_dir=value.search_dir,
passes_to=f"{describe_keys(copy.group(1), value.keys)} (--configfile)",
)
]
),
script.expand(copied.group(1), copy_line, set()),
_keys(value),
script,
source_name=copy.group(1),
)]
def melonds(tree: RepoTree) -> list[Launcher]:
@@ -406,7 +483,22 @@ def melonds(tree: RepoTree) -> list[Launcher]:
rf"^\s*{test.group(1)}=\$\(get_setting (\w+) ", f"setting read into {test.group(1)}"
)
condition = f"{setting.group(1)} = {test.group(2)} sets ExternalBIOSEnable=1, otherwise 0"
records = config_records(tree, "melonds", package, "melonDS.ini", depends_on_option=condition)
configs = [c.path for c in device_configs(tree, package, "melonDS.ini")]
# melonDS opens the DSi BIOS and firmware keys only under
# DSiExternalBIOSEnable, off unless a config sets it.
dsi_external = any(
s.key == "DSiExternalBIOSEnable" and s.value not in ("", "0")
for path in configs for s in settings(tree.read(path))
)
def unread(key: tuple[str, str]) -> bool:
return not dsi_external and key[1] in ("DSiBIOS9Path", "DSiBIOS7Path", "DSiFirmwarePath")
conf_line, conf = script.find(r'^\s*CONF_DIR="([^"]+)"', "CONF_DIR")
records = config_records(
tree, "melonds", package, "melonDS.ini", depends_on_option=condition,
target=f"{conf.group(1)}/melonDS.ini", start=script, unread=unread,
)
for record in records:
record.source_ref += (
f", {source_ref([(script.path, {setting_line, test_line, enable_line})])}"
@@ -420,7 +512,10 @@ def dsperate(tree: RepoTree) -> list[Launcher]:
f"{package}/scripts/start_dsperate.sh", tree.read(f"{package}/scripts/start_dsperate.sh")
)
run_line, _ = script.find(r"/usr/bin/dsperate --config ", "dsperate --config")
records = config_records(tree, "dsperate", package, "dsperate.ini", " (--config)")
records = config_records(
tree, "dsperate", package, "dsperate.ini", " (--config)",
target=script.expand("${DSPERATE_INI}", run_line, set()), start=script,
)
for record in records:
record.source_ref += f", {source_ref([(script.path, {run_line})])}"
return records
@@ -434,7 +529,10 @@ def xemu(tree: RepoTree) -> list[Launcher]:
copy_line, _ = script.find(
r'cp -r "\$\{SOURCE_DIR\}/\$\{XEMU_INI\}"', "xemu.toml copy at launch"
)
records = config_records(tree, "xemu", package, "xemu.toml", " (copied at each launch)")
records = config_records(
tree, "xemu", package, "xemu.toml", " (copied at each launch)",
target=script.expand("${CONF_DIR}/${XEMU_INI}", copy_line, set()), start=script,
)
for record in records:
record.source_ref += f", {source_ref([(script.path, {copy_line})])}"
return records
@@ -452,7 +550,9 @@ def nanoboyadvance(tree: RepoTree) -> list[Launcher]:
mk_line, _ = Script(mk_path, tree.read(mk_path)).find(
r"config/config\.toml", "config.toml install"
)
return [
start_path = f"{package}/scripts/start_nanoboyadvance.sh"
return [with_evidence(
tree,
Launcher(
emulator="nanoboyadvance",
build="standalone",
@@ -461,8 +561,14 @@ def nanoboyadvance(tree: RepoTree) -> list[Launcher]:
source_ref=source_ref([(path, lines), (mk_path, {mk_line})]),
search_dir=value.search_dir,
passes_to=describe_keys("config.toml", value.keys),
)
]
# NanoBoyAdvance exits when its BIOS cannot be read
# (src/platform/sdl/main.cpp:180-185 at the build ROCKNIX ships).
fails_when_missing=True,
),
f"{CONFIG_ROOT}/nanoboyadvance/config.toml",
_keys(value),
Script(start_path, tree.read(start_path)),
)]
def mednafen(tree: RepoTree) -> list[Launcher]:
@@ -486,7 +592,9 @@ def mednafen(tree: RepoTree) -> list[Launcher]:
modules: dict[str, list[Setting]] = {}
for setting in firmware:
modules.setdefault(setting.key.split(".", 1)[0], []).append(setting)
return [
home = script.expand("${MEDNAFEN_HOME}", gen_line, set())
return [with_evidence(
tree,
Launcher(
emulator="mednafen",
build="standalone",
@@ -501,9 +609,12 @@ def mednafen(tree: RepoTree) -> list[Launcher]:
slot=module,
search_dir=folder.value,
passes_to="mednafen.cfg " + ", ".join(s.key for s in group),
)
for module, group in modules.items()
]
),
f"{home}/mednafen.cfg",
[s.key for s in group],
script,
writers=("mednafen_gen_config.sh",),
) for module, group in modules.items()]
def yabasanshiro(tree: RepoTree) -> list[Launcher]:
@@ -549,6 +660,8 @@ def directory_records(
file: str,
folder_key: tuple[str, str],
file_keys: tuple[tuple[str, str], ...],
target: str = "",
start: str = "",
) -> list[Launcher]:
"""scans_dir records: the config hands a directory and leaves the file keys empty."""
configs = device_configs(tree, package, file)
@@ -568,7 +681,8 @@ def directory_records(
records = []
for device, folder, refs in per_device(tree, configs, f"{package}/package.mk", read):
passes = f"{name} [{folder_key[0]}] {folder_key[1]} = {folder}, {unset} unset"
records.append(
records.append(with_evidence(
tree,
Launcher(
emulator=emulator,
build="standalone",
@@ -578,8 +692,11 @@ def directory_records(
search_dir=folder,
passes_to=passes,
device=device,
)
)
),
target,
[f"[{s}] {k}" for s, k in (folder_key, *file_keys)],
Script(start, tree.read(start)) if start else None,
))
return records
@@ -591,6 +708,8 @@ def duckstation(tree: RepoTree) -> list[Launcher]:
"settings.ini",
("BIOS", "SearchDirectory"),
(("BIOS", "PathNTSCU"), ("BIOS", "PathNTSCJ"), ("BIOS", "PathPAL")),
f"{CONFIG_ROOT}/duckstation/settings.ini",
f"{STANDALONE}/duckstation-sa/scripts/start_duckstation.sh",
)
@@ -602,6 +721,8 @@ def armsx2(tree: RepoTree) -> list[Launcher]:
"ARMSX2/inis/PCSX2.ini",
("Folders", "Bios"),
(("Filenames", "BIOS"),),
f"{CONFIG_ROOT}/ARMSX2/inis/PCSX2.ini",
f"{STANDALONE}/armsx2-sa/scripts/start_armsx2.sh",
)
+1 -1
View File
@@ -36,7 +36,7 @@ SETUP_KEYS = (
)
ROW_KEYS = (
"folder", "name", "aliases", "extensions", "files", "core", "emulator", "source_ref",
"board_defaults", "arcade", "note",
"board_defaults", "offers", "arcade", "searched_by", "note",
)
+162 -1
View File
@@ -24,6 +24,7 @@ Formats, by the shape of the source:
from __future__ import annotations
import html
import json
import re
import shlex
@@ -45,6 +46,44 @@ def _board(core: str | None, emulator: str | None, source_ref: str) -> dict:
return {k: str(v) for k, v in out.items() if v}
def _offers(choices: list[dict], core: str | None, emulator: str | None) -> list[dict]:
"""Every (emulator, core) a folder can start, in the list's order, or
none when the default is the only one.
A core written under several branches of a device case keeps the
conditions it is written under, and none once a branch is the `*)` one
beside another or no branch at all: every build then offers it.
"""
found: dict[tuple[str, str], dict] = {}
whens: dict[tuple[str, str], set[str]] = {}
lines: dict[tuple[str, str], list[str]] = {}
for choice in choices:
pair = (str(choice.get("emulator") or ""), str(choice.get("core") or choice.get("emulator") or ""))
if not pair[1]:
continue
whens.setdefault(pair, set()).add(str(choice.get("when") or ""))
ref = str(choice.get("source_ref") or "")
if ref and pair in found and found[pair].get("source_ref", "").split(":")[0] == ref.split(":")[0]:
lines[pair].append(ref.rsplit(":", 1)[-1])
if pair not in found:
found[pair] = {k: str(v) for k, v in {**choice, "core": pair[1]}.items()
if v and k != "when"}
lines[pair] = []
out = []
for pair, offer in found.items():
if lines[pair] and offer.get("source_ref"):
offer["source_ref"] = ",".join([offer["source_ref"], *lines[pair]])
conditions = whens[pair]
if "" not in conditions and not (
len(conditions) > 1 and any(w.endswith(" *") for w in conditions)):
offer = {**offer, "when": "; ".join(sorted(conditions))}
offer = {k: offer[k] for k in ("emulator", "core", "when", "source_ref") if k in offer}
out.append(offer)
if [(o.get("emulator", ""), o["core"]) for o in out] == [(emulator or "", core or emulator or "")]:
return []
return out
def _top_key_lines(text: str) -> dict[str, int]:
"""First line of each top-level YAML key."""
out: dict[str, int] = {}
@@ -167,7 +206,7 @@ def _all_lines(text: str, pattern: str) -> dict[str, list[int]]:
for number, line in enumerate(text.splitlines(), 1):
match = re.search(pattern, line)
if match:
out.setdefault(match.group(1).strip(), []).append(number)
out.setdefault(html.unescape(match.group(1)).strip(), []).append(number)
return out
@@ -285,6 +324,9 @@ def _xml_rows(text: str, key: str, path: str, params: dict) -> list[dict]:
"core": core or emulator,
"emulator": emulator,
"source_ref": _ref(key, path, row["line"]),
"offers": _offers(
[{"emulator": e, "core": c} for e, cores in emulators for c, _d in cores or [(e, False)]],
core, emulator),
"arcade": _is_arcade(system.findtext("hardware"), platform),
"note": row.get("note"),
})
@@ -321,6 +363,9 @@ def es_json(spec: dict, fetcher: Fetcher) -> list[dict]:
"core": core or emulator,
"emulator": emulator,
"source_ref": _ref(key, path, row["line"]),
"offers": _offers(
[{"emulator": e, "core": c} for e, cores in emulators for c, _d in cores or [(e, False)]],
core, emulator),
"arcade": _is_arcade(system.get("hardware"), system.get("platform")),
"note": row.get("note"),
})
@@ -469,6 +514,12 @@ def elec_conf(spec: dict, fetcher: Fetcher) -> list[dict]:
"emulator": pick["emulator"] if pick else None,
"source_ref": "; ".join(refs),
"board_defaults": board_defaults,
"offers": _offers([
{"emulator": c["emulator"], "core": c["core"],
"when": ", ".join(f"{v} {p}".strip() for v, p in c["branches"]),
"source_ref": _ref(key, package, c["line"])}
for c in mine
], pick["core"] if pick else None, pick["emulator"] if pick else None),
"arcade": values.get("SYSTEM_HARDWARE") == "arcade" or None,
"note": note,
})
@@ -522,6 +573,100 @@ def _alternative_emulators(text: str, function: str) -> dict[str, tuple[str, int
return out
_ROMPATH_OPTIONS = ("-rompath", "-rp")
def _core_words(command: str) -> tuple[str, list[str]] | None:
"""The core and the words of the content RetroArch hands it.
ES-DE starts the libretro MAME core with a quoted command line as its
content (`-L .../mame_libretro.so "apple2e -rompath \\"...\\" ..."`): popen
runs it through the shell (es-core/src/utils/PlatformUtil.cpp:231, 257),
and the core splits the content on spaces and quotes when it is no file
(retro_init.cpp parse_cmdline, mmain2).
"""
core = _RA_CORE.search(command)
if core is None:
return None
try:
args = shlex.split(command)
at = args.index("-L")
content = shlex.split(args[at + 2]) if at + 2 < len(args) else []
except ValueError:
return None
return core.group(1), content
def _searched_by(commands: list[tuple[str, str, int | None]], key: str, path: str) -> list[dict]:
"""The ROM folders each emulator's commands pass it, by emulator and core.
ES-DE starts standalone MAME with `-rompath %GAMEDIR%\\;%ROMPATH%/<system>`
and a machine, or %BASENAME% where the game is the machine. The command
line outranks mame.ini. The libretro MAME core gets the same option in
the command line it is handed as content, after the machine. %GAMEDIR%
is the game's own folder, no folder a pack fills.
"""
found: dict[tuple[str, str], dict] = {}
for _label, command, line in commands:
libretro = _core_words(command)
if libretro is not None:
core, words = libretro
if words[:1] == [core]:
# A first word naming the core is dropped (mmain2).
words = words[1:]
name = "retroarch"
at = next((i for i, w in enumerate(words) if w in _ROMPATH_OPTIONS), None)
machine = words[0] if words and at else ""
else:
emulator = _EMULATOR.search(command)
if emulator is None:
continue
core, name = "", emulator.group(1).lower()
words = command.replace("\\;", ";").split()
at = next((i for i, w in enumerate(words) if w in _ROMPATH_OPTIONS), None)
machine = words[at + 2] if at is not None and at + 2 < len(words) else ""
if at is None or at + 1 >= len(words):
continue
reads = [
folder for part in words[at + 1].split(";")
if (folder := _strip_prefix(part, ["%ROMPATH%/", "%ROMPATH%\\"]))
]
if not reads:
continue
record = found.setdefault((name, core), {"emulator": name, "core": core, "reads": [],
"machines": [], "any_machine": False,
"lines": []})
record["reads"] += [r for r in reads if r not in record["reads"]]
if not machine or machine.startswith("%"):
record["any_machine"] = True
elif machine not in record["machines"]:
record["machines"].append(machine)
record["lines"].append(line)
rows = []
for record in found.values():
row = {"emulator": record["emulator"]}
if record["core"]:
row["core"] = record["core"]
row["reads"] = record["reads"]
if record["machines"]:
row["machines"] = record["machines"]
if record["any_machine"]:
row["any_machine"] = True
row["source_ref"] = _ref(key, path, *record["lines"])
rows.append(row)
return rows
def _command_lines(text: str) -> dict[str, list[int]]:
"""Command text -> the lines it is written on, in file order."""
out: dict[str, list[int]] = {}
for number, line in enumerate(text.splitlines(), 1):
match = re.search(r"<command\b[^>]*>([^<]*)</command>", line)
if match:
out.setdefault(match.group(1).strip(), []).append(number)
return out
@register("esde")
def esde(spec: dict, fetcher: Fetcher) -> list[dict]:
"""Each system of ES-DE's list whose path is %ROMPATH%/<folder>.
@@ -537,13 +682,22 @@ def esde(spec: dict, fetcher: Fetcher) -> list[dict]:
key, path = item["source"], item["path"]
text = _lenient_xml(fetcher.text(key, path))
lines = _first_lines(text, r"<name>([^<]+)</name>")
command_lines = _command_lines(text)
for name, rom_path, extensions, commands in _esde_systems(text, path):
folder = _strip_prefix(rom_path, ["%ROMPATH%/", "%ROMPATH%\\"])
if not name or not folder:
continue
start = lines.get(name) or 0
placed = [
(label, command, next(
(n for n in command_lines.get(command, []) if n >= start), None))
for label, command in commands
]
systems[name] = {
"folder": folder, "extensions": extensions, "commands": commands,
"ref": _ref(key, path, lines.get(name)),
"searched_by": _searched_by(placed, key, path),
"placed": [(*c, key, path) for c in placed],
}
alternatives: dict[str, tuple[str, int]] = {}
alt = params.get("alternatives")
@@ -566,6 +720,11 @@ def esde(spec: dict, fetcher: Fetcher) -> list[dict]:
else:
note = f"alternative emulator '{label}' names no command of this system"
emulator, core = _command_core(chosen[1])
offers = _offers([
{"emulator": e, "core": c, "source_ref": _ref(key_, path_, line)}
for _label, command, line, key_, path_ in system["placed"]
for e, c in [_command_core(command)] if e
], core, emulator)
extensions = system["extensions"]
if "." in extensions:
# ES-DE's "." is a file without an extension (SystemData.cpp
@@ -580,6 +739,8 @@ def esde(spec: dict, fetcher: Fetcher) -> list[dict]:
"emulator": emulator,
"source_ref": "; ".join(refs),
"note": note,
"offers": offers,
"searched_by": system["searched_by"] or None,
})
return rows
+202
View File
@@ -63,6 +63,48 @@ 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."""
@@ -394,6 +436,166 @@ def _merge_links(links: list[Link]) -> list[Link]:
return [link for link in merged if id(link) not in folded]
_COPY = re.compile(r"(?:^|[\s;&|(])(cp|rsync|install|mv)\s")
_GUARD = re.compile(r"\[\[?\s*!\s+-[fde]\s+(\S+)\s*\]")
@dataclass
class ConfigPlacement:
"""How a start script puts a config where the emulator reads it.
``install`` are the lines copying it there, ``kept_if_present`` whether
every such copy runs only when the file (or its folder) is absent, and
``overrides`` the sed lines rewriting one of the record's keys in it.
"""
script: str
path: str
install: set[int]
kept_if_present: bool
overrides: set[int]
def _bare_key(key: str) -> str:
return key.rsplit("] ", 1)[-1].rsplit("/", 1)[-1].strip()
def _guarded(script: Script, number: int, target: str) -> bool:
"""Whether a line runs only when target, or a folder above it, is absent."""
def covers(found: re.Match[str], at: int) -> bool:
guarded = script.expand(words(found.group(1))[0].text, at, set()).rstrip("/")
return target == guarded or target.startswith(guarded + "/")
line = script.lines[number - 1]
if any(covers(m, number) for m in _GUARD.finditer(line)):
return True
depth = 0
for at in range(number - 1, 0, -1):
text = script.lines[at - 1].strip()
if re.match(r"fi\b", text):
depth += 1
elif re.match(r"if\b", text):
if depth:
depth -= 1
continue
return any(covers(m, at) for m in _GUARD.finditer(text))
return False
def _quoted_glob(command: str) -> bool:
"""Whether the source of a copy holds a "*" only inside quotes."""
found = [w for w in words(command)[1:] if not w.raw.startswith("-")]
if len(found) < 2:
return False
raw = found[0].raw
return "*" in raw and "*" not in re.sub(r'"[^"]*"|\'[^\']*\'', "", raw)
def config_placement(
script: Script,
target: str,
keys: Iterable[str] = (),
writers: Iterable[str] = (),
source_name: str = "",
required: bool = True,
sources: tuple[str, ...] = (),
) -> ConfigPlacement:
"""The lines of a start script that install ``target`` and rewrite its keys.
A copy installs the target when its destination is the file or a folder
above it. ``writers`` are other commands that write the file (ROCKNIX
generates mednafen.cfg with mednafen_gen_config.sh). A copy guarded by
`[ ! -f X ]` or `[ ! -d X ]` on the target or a folder above it, or made
with cp -n or rsync --ignore-existing, leaves a file already there.
"""
install: set[int] = set()
kept = True
overrides: set[int] = set()
bare = {_bare_key(k) for k in keys} - {""}
writer = re.compile("|".join(re.escape(w) for w in writers)) if writers else None
for number, line in script.code():
if (copy := _COPY.search(line)) or (writer and writer.search(line)):
if copy:
args = []
for word in words(line[copy.start(1):])[1:]:
# The command ends at a separator or a redirection.
if word.raw in {";", "&&", "||", "|"} or re.match(r"\d*>|&>", word.raw):
break
args.append(word.text)
operands = [a for a in args if not a.startswith("-")]
if not operands:
continue
# A quoted "*" is a file named *, which no package installs:
# the copy does nothing (EmuELEC's duckstation.sh).
if _quoted_glob(line[copy.start(1):]):
continue
destination = script.expand(operands[-1], number, set()).rstrip("/")
source = script.expand(operands[0], number, set()).rstrip("/")
hits = target == destination or target.startswith(destination + "/") or (
target.startswith(f"{destination}/{source.rsplit('/', 1)[-1]}")
)
# A copy of another file into the same place is another
# record's: amiberry copies the A500 or the A1200 setup.
named = source.rsplit("/", 1)[-1]
if not hits or (source_name and "." in named and named != source_name):
continue
# A named file copied into a folder above the target is
# another file of that folder (ARMSX2's secrets.ini).
if (
not source_name and "." in named and "*" not in named
and destination != target and named != target.rsplit("/", 1)[-1]
):
continue
if sources and not source.startswith(sources):
continue
# cp -i fed by false answers no to every overwrite.
prompted = any(
a.startswith("-") and not a.startswith("--") and "i" in a[1:] for a in args
) and re.search(r"\bfalse\s*\|\s*$", line[:copy.start(1)])
skip = "-n" in args or "--ignore-existing" in args or bool(prompted)
else:
skip = False
install.add(number)
if not (skip or _guarded(script, number, target)):
kept = False
elif re.search(r"\bsed\b.*\s-i\b|\bsed -i", line) and bare:
expanded = script.expand(line, number, set())
if target in expanded or target.rsplit("/", 1)[-1] in expanded:
if any(re.search(rf"\b{re.escape(k)}\b", expanded) for k in bare):
overrides.add(number)
if not install and required:
raise script.missing(f"install of {target}")
return ConfigPlacement(script.path, target, install, kept, overrides)
def evidence_fields(
placements: Iterable[ConfigPlacement],
installed: Iterable[tuple[str, Iterable[int]]] = (),
) -> dict:
"""The installs, kept_if_present and overrides fields of a config record.
``placements`` are the steps that put the file in place, in the order
they run (a first-boot copy, then the start script). ``installed`` are
the build steps that put it where they copy it from (a package.mk copy
into /usr/config).
"""
placements = list(placements)
steps = [p for p in placements if p.install]
if not steps:
raise LauncherPatternMissing(placements[0].path if placements else "", "install")
return {
"installs": {
"path": steps[-1].path,
"source_ref": source_ref([*installed, *((p.script, p.install) for p in steps)]),
},
"kept_if_present": all(p.kept_if_present for p in steps),
"overrides": [
source_ref([(p.script, {line})]) for p in placements for line in sorted(p.overrides)
],
}
@dataclass
class Setting:
section: str
+4 -1
View File
@@ -123,7 +123,10 @@ class _Converter(HTMLParser):
self._emit(f"**{' '.join(name.split())}:**")
self._block()
return
if self.skip or tag in SKIPPED or attr.get("aria-hidden") == "true" \
# A `hidden` element is chrome the page's script shows (a filter
# box, the file picker, a setup's install chooser): a tab panel,
# hidden too, was read above.
if self.skip or tag in SKIPPED or attr.get("aria-hidden") == "true" or "hidden" in attr \
or classes & {"sr-only", "sl-anchor-link", "copy", "rb-anchor"}:
if tag not in ("br", "img", "hr", "input", "wbr"):
self.skip += 1
+115 -17
View File
@@ -9,14 +9,20 @@ A page asks for a diagram with an HTML comment on a line of its own::
<!-- image: install-flow -->
``resolve_images`` replaces the comment with the figure. The SVG is inline
so its text takes the page font and its colours come from the theme
variables in ``docs_assets/extra.css``: it follows the palette toggle, which
an ``<img>`` cannot. Presentation attributes give the same drawing a
readable default when the SVG is opened on its own.
``resolve_images`` replaces the comment with the figure. Each drawing is
an SVG file shown through ``<img>``, so the page text holds its words once:
an inline SVG put every label of both layouts, its title and its desc into
what a screen reader, a copy, a text dump or a crawler reads, next to the
prose that already says them. A file reads no stylesheet of the page, so it
is written once per theme with the colours retrobios.css gives the
``rb-d-*`` classes (``THEMES``), and the stylesheet shows the one of the
current theme. Presentation attributes give the same drawing a readable
default when the SVG is opened on its own.
Every figure carries two layouts, wide and narrow, and the stylesheet shows
one: a 720-unit drawing scaled to a phone would print 9 px text.
Every figure carries two layouts, wide and narrow, and ``<picture>`` picks
one: a 720-unit drawing scaled to a phone would print 9 px text. The
drawings are ``alt=""``: the figure says what they show once, in a
screen-reader line, and the caption under them.
"""
from __future__ import annotations
@@ -296,22 +302,112 @@ def grid(boxes: list[Box], per_row: int, total: float) -> tuple[float, float, li
return total, y - gap_y + 1, out
def svg(figure: Figure, layout: str, suffix: str) -> str:
"""One layout of *figure* as a standalone, accessible SVG element."""
width, height, body = (figure.wide if layout == "wide" else figure.narrow)()
base = f"rb-fig-{figure.image_id}{suffix}-{layout}"
def svg_document(width: float, height: float, title: str, desc: str, body: list[str],
base: str) -> str:
"""A drawing as a standalone, accessible SVG element."""
return (
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {_n(width)} {_n(height)}" '
f'width="{_n(width)}" height="{_n(height)}" role="img" '
f'aria-labelledby="{base}-t {base}-d" font-family="{FONT}" '
f'class="rb-diagram rb-diagram-{layout}">'
f'<title id="{base}-t">{escape(figure.title)}</title>'
f'<desc id="{base}-d">{escape(figure.desc)}</desc>'
f'aria-labelledby="{base}-t {base}-d" font-family="{FONT}">'
f'<title id="{base}-t">{escape(title)}</title>'
f'<desc id="{base}-d">{escape(desc)}</desc>'
+ "".join(body)
+ "</svg>"
)
def svg(figure: Figure, layout: str, suffix: str = "") -> str:
"""One layout of *figure* as a standalone, accessible SVG element."""
width, height, body = (figure.wide if layout == "wide" else figure.narrow)()
return svg_document(width, height, figure.title, figure.desc, body,
f"rb-fig-{figure.image_id}{suffix}-{layout}")
# The colours retrobios.css gives a diagram, per theme: --rb-diagram-* and
# --rb-text-secondary, then the text and background Starlight resolves
# --sl-color-text and --sl-color-bg to (props.css: gray-2 and black, whose
# values swap with the theme). An SVG shown through <img> reads none of them.
THEMES: dict[str, dict[str, str]] = {
"dark": {"text": "#c1c3c8", "bg": "#17181c", "fill": "#252838", "stroke": "#7c82a3",
"accent": "#aebcff", "muted": "#a6adc8"},
"light": {"text": "#353841", "bg": "#ffffff", "fill": "#f5f6fa", "stroke": "#8c92ac",
"accent": "#3b3f7a", "muted": "#546e7a"},
}
# Where the files are served, under the site's public folder.
DIAGRAM_DIR = "assets/diagrams"
# retrobios.css shows the narrow layout below this width.
NARROW_MEDIA = "(max-width: 37.5em)"
def themed(document: str, theme: str) -> str:
"""*document* with the theme's colours, the rules retrobios.css gives
the .rb-diagram classes on the page."""
c = THEMES[theme]
style = (
f"<style>svg{{color:{c['text']}}}text{{font-family:{FONT};fill:currentColor}}"
f".rb-d-box{{fill:{c['fill']};stroke:{c['stroke']}}}.rb-d-accent{{stroke:{c['accent']}}}"
f".rb-d-line{{stroke:{c['stroke']}}}.rb-d-head{{fill:{c['stroke']}}}"
f".rb-d-num{{fill:{c['accent']}}}.rb-d-numtext{{fill:{c['bg']}}}"
f".rb-d-muted{{fill:{c['muted']}}}</style>"
)
head = document.index(">") + 1
return document[:head] + style + document[head:]
def _size(document: str) -> tuple[str, str]:
match = re.match(r'<svg [^>]*?width="([\d.]+)" height="([\d.]+)"', document)
if not match:
raise ValueError("an SVG document without its size")
return match.group(1), match.group(2)
def diagram_files(stem: str, layouts: dict[str, str]) -> dict[str, str]:
"""The files of one drawing: *layouts* maps wide and narrow to its SVG,
each written once per theme."""
return {f"{stem}-{layout}-{theme}.svg": themed(document, theme) + "\n"
for layout, document in layouts.items() for theme in THEMES}
def pictures(stem: str, layouts: dict[str, str]) -> str:
"""The drawing on the page: one <picture> per theme, the narrow layout
under NARROW_MEDIA. Each image is alt="", the figure says the words."""
(wide_w, wide_h), (narrow_w, narrow_h) = _size(layouts["wide"]), _size(layouts["narrow"])
out = []
for theme in THEMES:
url = markup.site_href(f"{DIAGRAM_DIR}/{stem}")
out.append(
f'<picture class="rb-diagram rb-diagram-{theme}">'
f'<source media="{NARROW_MEDIA}" srcset="{url}-narrow-{theme}.svg" '
f'width="{narrow_w}" height="{narrow_h}" />'
f'<img src="{url}-wide-{theme}.svg" width="{wide_w}" height="{wide_h}" alt="" '
'loading="lazy" decoding="async" /></picture>'
)
return "".join(out)
def _layouts(figure: Figure) -> dict[str, str]:
return {layout: svg(figure, layout) for layout in ("wide", "narrow")}
def figure_files() -> dict[str, str]:
"""Every figure's files, by name under DIAGRAM_DIR."""
return {name: text for image_id in IMAGE_IDS
for name, text in diagram_files(image_id, _layouts(figures()[image_id])).items()}
def write_diagram_files(directory: Path, files: dict[str, str]) -> None:
"""*files* under *directory*, and no other SVG: a drawing renamed or
dropped leaves no file behind."""
directory.mkdir(parents=True, exist_ok=True)
for stale in directory.glob("*.svg"):
if stale.name not in files:
stale.unlink()
for name, text in sorted(files.items()):
path = directory / name
if not path.is_file() or path.read_text(encoding="utf-8") != text:
path.write_text(text, encoding="utf-8")
# Data
@@ -667,18 +763,20 @@ _INLINE_ESCAPES = str.maketrans({"_": "&#95;", "*": "&#42;", "`": "&#96;", "[":
def figure_html(image_id: str, occurrence: int = 1, inline: bool = False) -> str:
figure = figures()[image_id]
suffix = "" if occurrence == 1 else f"-{occurrence}"
drawings = svg(figure, "wide", suffix) + svg(figure, "narrow", suffix)
drawings = pictures(image_id, _layouts(figure))
said = f'<span class="sr-only">{escape(figure.desc)}</span>'
caption = escape(figure.caption)
anchor = f"rb-fig-{image_id}{suffix}"
if inline:
html = (
f'<span class="rb-figure rb-figure-inline" id="{anchor}" {markup.search_exclude()}>'
f'{drawings}<span class="rb-figure-caption">{caption}</span></span>'
f'{drawings} {said} <span class="rb-figure-caption">{caption}</span></span>'
)
return html.translate(_INLINE_ESCAPES)
return (
f'<figure class="rb-figure" id="{anchor}" {markup.search_exclude()}>\n'
f"{drawings}\n"
f"{said}\n"
f"<figcaption>{caption}</figcaption>\n"
"</figure>"
)
+13 -4
View File
@@ -47,12 +47,21 @@ def filter_placeholder(labels: list[str]) -> str:
def filter_box(ident: str, heading: str, labels: list[str], rows: int, noun: str = "rows") -> str:
"""The filter box rehype-stack-tables.mjs writes above a long table."""
"""The filter box rehype-stack-tables.mjs writes above a long table.
It is `hidden` until site.ts wires it: without the script it filters
nothing, so a reader with no JavaScript, a text dump and the search
skip it while the rows stay. retrobios.css keeps its room meanwhile,
so the table does not move when it shows. The count is the input's
description, and spaces keep label, field and count apart in any text
read from the HTML."""
return (
f'<div class="rb-table-filter"><label for="{ident}">Filter {html.escape(heading)}</label>'
f'<div class="rb-table-filter" hidden {markup.search_exclude()}>'
f'<label for="{ident}">Filter {html.escape(heading)}</label> '
f'<input id="{ident}" type="search" autocomplete="off" '
f'placeholder="{html.escape(filter_placeholder(labels))}">'
f'<span class="rb-table-filter-count" aria-live="polite">{rows:,} {noun}</span></div>'
f'placeholder="{html.escape(filter_placeholder(labels))}" aria-describedby="{ident}-count"> '
f'<span id="{ident}-count" class="rb-table-filter-count" aria-live="polite">'
f"{rows:,} {noun}</span></div>"
)
+258
View File
@@ -0,0 +1,258 @@
"""The handheld launchers the site serves, and where each one goes.
The four archives scripts/build_port.py writes carry install.py pinned by
SHA-256, so they change with the installer, not with the BIOS packs. The
site builds them from the commit it is built from and serves them under
get/handheld/, beside the bootstraps that pin the same installer
(sitebootstrap.py). build_archive refuses an install.py that install.sh
does not pin: a stale pin stops the site build, the last good archives
staying served.
LAUNCHERS is the one description of where each archive goes on the card
and which menu starts it. The handheld tables of wiki/installer.md are
written from it (scripts/generate_installer_doc.py), and so is the block
each get/<platform>/ page and the handheld page carry.
"""
from __future__ import annotations
import hashlib
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
import sitemarkup as markup
from artifacts import write_bytes_atomic
from build_port import ARCHIVES, BATOCERA_ZIP, MUOS_APP, PORT_ZIP, TOOLS_ZIP, build_archive
REPO_ROOT = Path(__file__).resolve().parent.parent
# Below the site's root: get/handheld/RetroBIOS.zip.
SERVED_DIR = "get/handheld"
# The page of the systems no registered platform answers for. It shares
# its name with the handheld guide (platforms/linux-handhelds.md), so the
# sidebar files it with that guide, as get/batocera.md is with
# platforms/batocera.md.
GROUP_PAGE = "linux-handhelds"
GROUP_TITLE = "RetroBIOS app for handhelds"
@dataclass(frozen=True)
class Launcher:
"""One row of the installer's handheld table.
*systems* are named as the installer page names them. *copy_to* is
where the file goes, and *places* gives a system its own folder when
the row's systems differ there. *lead* opens the row's first cell.
"""
archive: str
systems: tuple[str, ...]
copy_to: str
start: str
extracted: bool = False
lead: str = ""
places: tuple[tuple[str, tuple[str, ...]], ...] = field(default=())
def folder_for(self, system: str) -> str:
return next((folder for folder, systems in self.places if system in systems),
self.copy_to)
LAUNCHERS: tuple[Launcher, ...] = (
Launcher(MUOS_APP, ("muOS",),
"`ARCHIVE` at the root of the card, then install it from the Archive Manager",
"Applications"),
Launcher(PORT_ZIP, ("ArkOS", "dArkOS", "ROCKNIX", "AmberELEC", "JELOS", "KNULLI"),
"PortMaster's `autoinstall` folder", "Ports, after opening PortMaster once",
lead="Any other system with [PortMaster](https://portmaster.games/)",
places=(("`/roms/ports/PortMaster/autoinstall/`", ("ROCKNIX", "AmberELEC")),
("`/roms/tools/PortMaster/autoinstall/`", ("ArkOS",)),
("`/userdata/system/.local/share/PortMaster/autoinstall/`", ("KNULLI",)))),
Launcher(BATOCERA_ZIP, ("Batocera", "KNULLI"), "`roms/ports` on the SHARE partition",
"Ports, after updating the game list", extracted=True),
Launcher(TOOLS_ZIP, ("ArkOS", "dArkOS"), "`tools` on the EASYROMS partition",
"Options, then Tools", extracted=True),
Launcher(TOOLS_ZIP, ("ROCKNIX", "JELOS"),
"`/storage/.config/modules`, over the network share or SSH", "Tools",
extracted=True),
Launcher(TOOLS_ZIP, ("AmberELEC",), "`/storage/.config/distribution/modules`", "Tools",
extracted=True),
)
# The registered platform whose get/ page answers for a system. A system
# outside this map is on the handheld page.
PLATFORM_OF = {"Batocera": "batocera", "KNULLI": "knulli", "ROCKNIX": "rocknix",
"AmberELEC": "amberelec"}
def systems() -> list[str]:
"""Every system a launcher runs on, in table order."""
return list(dict.fromkeys(name for launcher in LAUNCHERS for name in launcher.systems))
def group_systems() -> list[str]:
return [name for name in systems() if name not in PLATFORM_OF]
def joined(names: list[str], last: str = "and") -> str:
"""muOS, ArkOS and JELOS."""
return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} {last} {names[-1]}"
def page_of(system: str) -> str:
"""The site page that holds the download for *system*."""
return f"get/{PLATFORM_OF.get(system, GROUP_PAGE)}.md"
def launchers_for(system: str) -> list[Launcher]:
"""The launchers of *system*, its own menu first and PortMaster last."""
own = [launcher for launcher in LAUNCHERS if system in launcher.systems]
return sorted(own, key=lambda launcher: launcher.archive == PORT_ZIP)
@dataclass(frozen=True)
class Served:
data: bytes
@property
def size(self) -> int:
return len(self.data)
@property
def sha256(self) -> str:
return hashlib.sha256(self.data).hexdigest()
_built: dict[tuple[str, str], Served] = {}
def served(name: str, root: Path = REPO_ROOT) -> Served:
"""The bytes of archive *name* as build_port builds it from *root*,
built once per run: the page states the size and hash of the file the
same run writes."""
key = (str(root.resolve()), name)
if key not in _built:
scratch_root = root / "tmp"
scratch_root.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=scratch_root, prefix="handheld-") as scratch:
path = build_archive(name, Path(scratch) / name, root)
_built[key] = Served(path.read_bytes())
return _built[key]
def write_launchers(public: Path, root: Path = REPO_ROOT) -> list[Path]:
"""Write every launcher archive under the site's public folder, each
only when its bytes moved."""
folder = public / SERVED_DIR
folder.mkdir(parents=True, exist_ok=True)
written = []
for name in ARCHIVES:
path = folder / name
data = served(name, root).data
if not path.is_file() or path.read_bytes() != data:
write_bytes_atomic(str(path), data)
written.append(path)
return written
def table_rows() -> list[str]:
"""The handheld table of the installer page, each system linked to the
page that holds its download. The page sits in wiki/."""
def name(system: str) -> str:
return f"[{system}](../{page_of(system)})"
rows = ["| System | File | Copy it to | Start it from |",
"|--------|------|------------|---------------|"]
for launcher in LAUNCHERS:
names = ", ".join(name(system) for system in launcher.systems)
first = f"{launcher.lead}: {names}" if launcher.lead else names
file = f"`{launcher.archive}`" + (", extracted" if launcher.extracted else "")
copy_to = launcher.copy_to
if launcher.places:
copy_to += ": " + ", ".join(
f"{folder} on {' and '.join(where)}" for folder, where in launcher.places)
rows.append(f"| {first} | {file} | {copy_to} | {launcher.start} |")
return rows
def _anchor(system: str) -> str:
"""Where *system*'s downloads sit on its page."""
return "on-the-handheld" if system in PLATFORM_OF else system.casefold()
def download_rows() -> list[str]:
"""The short table that opens the installer's handheld section: each
system, its files as links to the site's copies, and its page. The
page sits in wiki/."""
rows = ["| System | Download | Steps |", "|--------|----------|-------|"]
for system in systems():
files = ", ".join(
f"[{launcher.archive}](../{SERVED_DIR}/{launcher.archive})"
+ (" (PortMaster)" if launcher.archive == PORT_ZIP else "")
for launcher in launchers_for(system))
page = f"../{page_of(system)}#{_anchor(system)}"
rows.append(f"| {system} | {files} | [{system} steps]({page}) |")
return rows
def _launcher_block(launcher: Launcher, system: str, root: Path) -> list[str]:
archive = served(launcher.archive, root)
verb = "Unzip it into" if launcher.extracted else "Copy it to"
via = " (with PortMaster)" if launcher.archive == PORT_ZIP else ""
return [
markup.button(f"Download {launcher.archive}", f"handheld/{launcher.archive}",
primary=True) + via,
"",
f"- {verb} {launcher.folder_for(system)}.",
f"- Start it from {launcher.start}.",
f"- {_size(archive.size)}. SHA-256: `{archive.sha256}`",
"",
]
def _size(count: int) -> str:
if count >= 1024 * 1024:
return f"{count / 1024 ** 2:.1f} MB"
return f"{count / 1024:.0f} KB"
APP_LINE = "RetroBIOS also runs on the handheld, with the controller."
# The installer's handheld section opens on the download of every system.
INSTALLER_SECTION = "wiki/installer.md#on-a-handheld-the-retrobios-port"
DETAILS_LINK = f"[Every system's file](../{INSTALLER_SECTION})"
def platform_block(platform: str, root: Path = REPO_ROOT) -> list[str]:
"""The app section of get/<platform>/, empty for a platform no launcher
runs on."""
system = next((name for name, key in PLATFORM_OF.items() if key == platform), None)
if system is None:
return []
lines = ["## On the handheld { #on-the-handheld }", "", APP_LINE, ""]
for launcher in launchers_for(system):
lines += _launcher_block(launcher, system, root)
return [*lines, DETAILS_LINK, ""]
def group_page(root: Path = REPO_ROOT) -> str:
"""get/linux-handhelds/: the app for the systems no setup page answers
for, then the setup pages that carry it for the others."""
names = group_systems()
listed = joined(names)
lines = [
"---", "search: exclude",
f'description: "The RetroBIOS app for {listed}: the file to put on the card '
'and the menu that starts it."',
"---", "",
f"# {GROUP_TITLE}", "",
f"{APP_LINE} Each system has its file below.", "",
]
for system in names:
lines += [f"## {system}", ""]
for launcher in launchers_for(system):
lines += _launcher_block(launcher, system, root)
others = [f"[{name}]({PLATFORM_OF[name]}.md#on-the-handheld)"
for name in sorted(PLATFORM_OF, key=str.casefold)]
lines += ["## Other systems", "", f"On {joined(others, 'or')}: on its page.", "",
DETAILS_LINK, ""]
return "\n".join(lines)
+7 -6
View File
@@ -225,10 +225,11 @@ def _tile_mark(name: str, logo: str, lazy: bool = False) -> str:
loading = ' loading="lazy"' if lazy else ""
return (f'<img class="rb-card-logo" src="{html.escape(logo)}" alt="" '
f'width="40" height="40"{loading}>')
# The same square as a logo, drawn on white like the logos are.
return ('<svg class="rb-card-logo" viewBox="0 0 40 40" width="40" height="40" aria-hidden="true">'
'<text x="20" y="25" text-anchor="middle" font-size="14" font-weight="700" '
f'fill="#2b2e5c">{html.escape(initials(name))}</text></svg>')
# The same square as a logo, drawn on white like the logos are. The
# letters are the stylesheet's (::before), not text of the page: the
# tile's name follows, and a copy or a text dump read "MMMyMinUI".
return (f'<span class="rb-card-logo rb-card-initials" data-initials="{html.escape(initials(name))}" '
'aria-hidden="true"></span>')
# Tiles in the first row of a grid at its widest, two columns of 15rem in
@@ -246,8 +247,8 @@ def platform_tiles(tiles: list[tuple[str, str, str, str]], eager: int = 0) -> li
links = "".join(
f'<a class="rb-card rb-tile" href="{html.escape(target)}">'
f"{_tile_mark(name, logo, lazy=index >= eager)}"
f'<strong class="rb-tile-name">{html.escape(name)}</strong>'
f'<span class="rb-tile-runs">{inline_html(runs_on)}</span></a>'
f'<strong class="rb-tile-name">{html.escape(name)}</strong> '
f'<span class="rb-tile-runs">{inline_html(runs_on)}</span></a> '
for index, (name, target, logo, runs_on) in enumerate(tiles)
)
return [f'<div class="rb-cards rb-tiles">{links}</div>', ""]
+5 -1
View File
@@ -982,7 +982,6 @@ SYSTEM_NAMES: dict[str, str] = {
"heroes-of-might-and-magic-2": "Heroes of Might and Magic II",
"hexen": "Hexen",
"hexen2": "Hexen II",
"hppa": "HP PA-RISC",
"hugo": "Hugo",
"hyper-neogeo64": "SNK Hyper Neo Geo 64",
"ibm-at": "IBM PC/AT",
@@ -1339,6 +1338,11 @@ SYSTEM_PARENTS: dict[str, tuple[str, str]] = {
# Games, filed with the game whose folder holds their data
"dinothawr": ("Dinothawr", "Dinothawr"),
"doom": ("Id Software", "Doom"),
# The other games of the Doom engines keep their IWADs in its folder.
"heretic": ("Id Software", "Doom"),
"hexen": ("Id Software", "Doom"),
"strife": ("Id Software", "Doom"),
"chex": ("Id Software", "Doom"),
"ctf": ("Id Software", "Quake II"),
"teamarena": ("Id Software", "Quake III Arena"),
"enemyterritory": ("Id Software", "Wolfenstein Enemy Territory"),
+9 -2
View File
@@ -274,9 +274,13 @@ _HEADING_ATTRS = re.compile(r"(?m)(?<=\S)[ \t]+\{[ \t]*#[^{}\n]*\}[ \t]*$")
_COMMENT = re.compile(r"<!--.*?-->", re.S)
_TAG_GAP = re.compile(r"(</[A-Za-z][\w-]*>)[ \t]+(?=<[A-Za-z])")
def mdx_safe(text: str) -> str:
"""What MDX would read as code in prose: braces, a stray ``<``,
comments, unclosed void tags and ``<https://...>`` links."""
comments, unclosed void tags and ``<https://...>`` links. A space
between two tags is written as an expression MDX keeps."""
def fix(chunk: str) -> str:
chunk = _COMMENT.sub("", chunk)
chunk = re.sub(r"<(https?://[^>\s]+)>", r"[\1](\1)", chunk)
@@ -289,7 +293,10 @@ def mdx_safe(text: str) -> str:
chunk = chunk.replace("{", "&#123;").replace("}", "&#125;")
chunk = re.sub(r"\x00(\d+)\x00", lambda m: held[int(m[1])], chunk)
chunk = re.sub(r"<(?![A-Za-z/])", "&lt;", chunk)
return _VOID.sub(lambda m: f"<{m[1]}{m[2].rstrip()} />", chunk)
chunk = _VOID.sub(lambda m: f"<{m[1]}{m[2].rstrip()} />", chunk)
# A line of tags alone is JSX to MDX, which drops the space between
# them: a setup page with tabs read "2007/2008Coverage".
return _TAG_GAP.sub(r'\1{" "}', chunk)
return outside_code(text, fix)
+29 -21
View File
@@ -3,12 +3,14 @@
Two things per tab, both drawn from data:
- The steps that differ by system, opening a terminal and pasting the line,
as an inline SVG: one card per step, a pictogram and a short caption,
drawn with sitediagrams' primitives so it takes the theme's colours in
light and dark. The text steps above it (platforms/_guides.yml,
terminals) stay the accessible source. The SVG says the same in its title
and desc. The pictograms are generic shapes (a menu, a search field, a
window, keys, a mouse, the power symbol), no vendor's interface or logo.
as a drawing: one card per step, a pictogram and a short caption, drawn
with sitediagrams' primitives and shown as its SVG files, one per layout
and theme (sitediagrams.pictures). The text steps above it
(platforms/_guides.yml, terminals) are the one text source: the images
are alt="", so the page reads the steps once. The files say the same in
their title and desc, for one opened on its own. The pictograms are
generic shapes (a menu, a search field, a window, keys, a mouse, the
power symbol), no vendor's interface or logo.
- The installer demo recorded for that place (scripts/make_demo.py): the
full-screen interface on a handheld under "On the device", the terminal
recording under the others but Windows. No Windows recording is
@@ -23,7 +25,6 @@ from xml.sax.saxutils import escape
import sitemarkup as markup
from sitediagrams import (
FONT,
MONO_STYLE,
NARROW,
STROKE,
@@ -35,6 +36,9 @@ from sitediagrams import (
_n,
_rect,
_text,
diagram_files,
pictures,
svg_document,
wrap,
)
@@ -92,7 +96,7 @@ def demo_variant(tab: str) -> str:
def description(tab: str) -> str:
"""The steps in words: the SVG's desc."""
"""The steps in words: the desc of the SVG files."""
return " ".join(f"{index}. {step.caption}." for index, step in
enumerate(STEPS[tab][1], start=1))
@@ -234,25 +238,29 @@ def _narrow(steps: tuple[Step, ...]) -> tuple[float, float, list[str]]:
def _svg(tab: str, layout: str) -> str:
title, steps = STEPS[tab]
width, height, body = (_wide if layout == "wide" else _narrow)(steps)
base = f"rb-steps-{tab}-{layout}"
return (
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {_n(width)} {_n(height)}" '
f'width="{_n(width)}" height="{_n(height)}" role="img" '
f'aria-labelledby="{base}-t {base}-d" font-family="{FONT}" '
f'class="rb-diagram rb-diagram-{layout}">'
f'<title id="{base}-t">{escape(title)}</title>'
f'<desc id="{base}-d">{escape(description(tab))}</desc>'
+ "".join(body) + "</svg>"
)
return svg_document(width, height, title, description(tab), body, f"rb-steps-{tab}-{layout}")
def _layouts(tab: str) -> dict[str, str]:
return {layout: _svg(tab, layout) for layout in ("wide", "narrow")}
def stem(tab: str) -> str:
return f"steps-{tab}"
def steps_files() -> dict[str, str]:
"""Every tab's drawing files, by name under sitediagrams.DIAGRAM_DIR."""
return {name: text for tab in STEPS for name, text in diagram_files(stem(tab), _layouts(tab)).items()}
def steps_figure(tab: str) -> list[str]:
"""The figure of a tab's steps, both layouts, or nothing for a tab with
no drawing."""
"""The figure of a tab's steps, both layouts in both themes, or nothing
for a tab with no drawing. The steps above it say its words."""
if tab not in STEPS:
return []
return [f'<figure class="rb-figure rb-steps" {markup.search_exclude()}>',
_svg(tab, "wide") + _svg(tab, "narrow"), "</figure>", ""]
pictures(stem(tab), _layouts(tab)), "</figure>", ""]
def tab_demo(tab: str) -> list[str]:
+17 -3
View File
@@ -54,6 +54,21 @@ def write_decorated(path: str | Path, content: str) -> bool:
_record(path)
return _write_artifact(str(path), content)
# A page body is written as .md and the decoration pass, which runs after
# the sweep, gives it its final extension: .mdx when it holds components,
# the other file removed. The .mdx a previous run left is that same page.
_PAGE_SUFFIXES = (".md", ".mdx")
def _was_produced(path: Path) -> bool:
"""Whether this run produced *path*, a page under either extension."""
if os.path.realpath(str(path)) in _produced:
return True
return path.suffix in _PAGE_SUFFIXES and any(
os.path.realpath(str(path.with_suffix(suffix))) in _produced
for suffix in _PAGE_SUFFIXES if suffix != path.suffix)
def _sweep_generated(docs: Path, directories: list[str]) -> int:
"""Delete files in the generated tree that this run did not produce."""
removed = 0
@@ -62,7 +77,7 @@ def _sweep_generated(docs: Path, directories: list[str]) -> int:
if not root.is_dir():
continue
for path in sorted(root.rglob("*")):
if path.is_file() and os.path.realpath(str(path)) not in _produced:
if path.is_file() and not _was_produced(path):
path.unlink()
removed += 1
for path in sorted(root.rglob("*"), reverse=True):
@@ -81,8 +96,7 @@ def _sweep_top_pages(docs: Path) -> int:
"""
removed = 0
for path in sorted(docs.glob("*.md*")):
if (path.is_file() and path.suffix in (".md", ".mdx")
and os.path.realpath(str(path)) not in _produced):
if path.is_file() and path.suffix in _PAGE_SUFFIXES and not _was_produced(path):
path.unlink()
removed += 1
return removed
+4 -2
View File
@@ -12,6 +12,7 @@ import sys
from pathlib import Path
from common import (
OUTER_ROOTS,
_norm_system_id,
load_data_dir_registry,
platform_layouts,
@@ -453,11 +454,12 @@ def _system_dir_files(profile: dict, standalone: bool) -> list[dict]:
"""Entries of the build the platform runs, read from the system directory.
An entry the platform's launchers leave outside the BIOS tree
(``unplaced``) is not: the platform has no file of its own there.
(``unplaced``) is not, nor one placed below its roms or an emulator
folder (``root``): the platform has no file of its own there.
"""
return [
f for f in filter_files_by_mode(profile.get("files", []), standalone=standalone)
if read_from_system_dir(f) and not f.get("unplaced")
if read_from_system_dir(f) and not f.get("unplaced") and f.get("root") not in OUTER_ROOTS
]
+138 -2
View File
@@ -81,12 +81,16 @@ def _validate_yaml_directory(
continue
out.extend(_errors(validator, data, str(path.relative_to(ROOT))))
out.extend(_unreachable_citations(path, data))
if schema_name == "platform.schema.json":
out.extend(_config_records_without_evidence(path, data))
if schema_name == "emulator.schema.json":
out.extend(_config_reads_without_build(path, data))
out.extend(_checks_without_values(path, data))
out.extend(_save_dir_without_library_name(path, data))
out.extend(_systems_outside_profile(path, data))
out.extend(_doubled_paths(path))
out.extend(_group_requirement_split(path, data))
out.extend(_data_only_source_refs(path, data))
return out
@@ -95,10 +99,65 @@ _CHECK_FIELDS = {
"md5": ("md5",),
"sha1": ("sha1",),
"sha256": ("sha256",),
"size": ("size", "min_size", "max_size"),
"size": ("size", "min_size", "max_size", "size_multiple"),
"romdir": ("romdir",),
"masked_sha1": ("masked_sha1",),
}
def _config_records_without_evidence(path: Path, document: object) -> list[str]:
"""A launcher record citing a config without the links its extractor reads.
A config file is proof only when the code installing it and the code
reading it are shown (launchers.config_evidence). The platform's half
is the extractor's to write: a record citing a shipped config carries
installs and overrides, and a feature or option file is never a
record's source, only its choices_from.
"""
if not isinstance(document, dict):
return []
from scraper.shell_launchers import config_ref, is_feature_ref # noqa: PLC0415
out: list[str] = []
for index, record in enumerate(document.get("launchers") or []):
if not isinstance(record, dict):
continue
cited = config_ref(str(record.get("source_ref") or ""))
where = f"{path.relative_to(ROOT)}: launchers[{index}] ({record.get('emulator')})"
features = [part for part in cited if is_feature_ref(part)]
if features:
out.append(f"{where} cites {features[0]} as source, choices_from holds it")
if [part for part in cited if not is_feature_ref(part)] and not (
record.get("installs") and "overrides" in record
):
out.append(f"{where} cites a config without installs and overrides")
return out
def _config_reads_without_build(path: Path, document: object) -> list[str]:
"""A config_reads entry naming a platform the profile gives no pin_build.
Such an entry is read at the build that platform ships, and pin_build is
where that build is named.
"""
if not isinstance(document, dict):
return []
builds = {str(b.get("platform")) for b in document.get("pin_build") or []}
out: list[str] = []
for index, read in enumerate(document.get("config_reads") or []):
if not isinstance(read, dict):
continue
if read.get("revision") or read.get("binary_sha256"):
continue
for platform in read.get("platforms") or []:
if str(platform) not in builds:
out.append(
f"{path.relative_to(ROOT)}: config_reads[{index}] ({read.get('file')}) "
f"names {platform}, which has no pin_build"
)
return out
def _systems_outside_profile(path: Path, document: object) -> list[str]:
"""An entry's system: or systems: naming a system its profile does not list.
@@ -153,6 +212,77 @@ def _group_requirement_split(path: Path, document: object) -> list[str]:
return out
_CODE_SUFFIXES = frozenset(
"c cc cpp cxx c++ h hh hpp hxx inc inl ipp m mm mjs cjs js jsx ts tsx py cs java kt "
"go rs lua pas pp asm s sh bash zsh ps1 bat cmd vbs swift d zig nim qml qc rb pl php "
"scala ml hs dart vue ino z80 smali".split()
)
_CODE_FILE = re.compile(r"(?<=[\w+-])\.([A-Za-z0-9+]+)\b")
# A compiled image: a part that names one has to say where in it the file
# is read, an address, a decompiled function or an IL method.
# A name under a directory is a file of the tree it sits in, and a further
# extension (.dll.map) makes it another file.
_BINARY_FILE = re.compile(
r"(?<![\w/+.-])[\w+.-]+\.(?:so|dll|exe|dylib|dex|elf|nro|xex)(?:\.\d+)*(?![\w.-]*\w)",
re.IGNORECASE,
)
_BINARY_EVIDENCE = re.compile(
r"\b0x[0-9a-fA-F]+\b"
r"|\b(?:FUN|sub|thunk|LAB)_[0-9a-fA-F]+\b"
r"|\bIL_[0-9a-fA-F]{4}\b"
r"|::|\.\.c?ctor\b"
r"|\b[A-Za-z_][\w.$]*\("
)
# Profiles whose files cite no published code. Each reason says why the
# check cannot apply yet.
DATA_ONLY_REF_EXCEPTIONS: dict[str, str] = {}
def _ref_cites_code(ref: str) -> bool:
"""A source_ref cites a source file or a place in a compiled image.
A part naming a binary without an address, a decompiled function or an
IL method says only that the binary exists: "import directory",
"string table" and "readelf -d" are not the code that reads a file.
"""
from sourceref import split_source_ref
cited = False
for part in split_source_ref(ref):
located = bool(_BINARY_EVIDENCE.search(part.raw)) or any(
suffix.lower() in _CODE_SUFFIXES for suffix in _CODE_FILE.findall(part.raw)
)
if _BINARY_FILE.search(part.raw) and not located:
return False
cited = cited or located
return cited
def _data_only_source_refs(path: Path, document: object) -> list[str]:
"""A files[] source_ref that cites only data or build files.
A data file is evidence that the emulator reads a file only once the
code that ships and parses it is cited too: iwadinfo.txt names the
IWADs, d_iwad.cpp is what reads it. 655 entries in 27 profiles cited
the table alone, and six of them named a file no code opens.
"""
if not isinstance(document, dict) or path.stem in DATA_ONLY_REF_EXCEPTIONS:
return []
out: list[str] = []
for index, entry in enumerate(document.get("files") or []):
if not isinstance(entry, dict) or not entry.get("source_ref"):
continue
refs = entry["source_ref"]
for ref in refs.values() if isinstance(refs, dict) else [refs]:
if ref and not _ref_cites_code(str(ref)):
out.append(
f"{path.relative_to(ROOT)}: files[{index}] ({entry.get('name')}) "
f"source_ref cites no code that reads the file: {ref}"
)
return out
def _checks_without_values(path: Path, document: object) -> list[str]:
"""A check an entry declares with nothing to compare against.
@@ -584,7 +714,13 @@ def _semantic_install_checks(path: Path, manifest: dict) -> list[str]:
destinations = [(entry.get("root"), entry.get("dest")) for entry in files]
if len(destinations) != len(set(destinations)):
out.append(f"{path.relative_to(ROOT)}: duplicate destinations")
omitted_destinations = [(entry.get("root"), entry.get("dest")) for entry in omitted]
# root: emulator is each core's own folder: mame2015 and mame2016 read
# 3dobios.zip in two places, one omission each, named by its cores.
omitted_destinations = [
(entry.get("root"), entry.get("dest"),
tuple(entry.get("cores") or ()) if entry.get("root") == "emulator" else ())
for entry in omitted
]
if len(omitted_destinations) != len(set(omitted_destinations)):
out.append(f"{path.relative_to(ROOT)}: duplicate omitted destinations")
overlap = set(destinations) & set(omitted_destinations)
+44 -3
View File
@@ -15,10 +15,14 @@ from collections.abc import Callable, Iterator, Mapping, Sequence
from common import (
adler32_of,
archive_members,
CONTENT_CHECKS,
compute_hashes,
content_fits,
declared_content_checks,
entry_system_ids,
name_match_size_ok,
sanitize_pack_path,
shape_fits,
size_fits,
)
from hashing import md5_composite, parse_hash_list, parse_md5_list
@@ -35,6 +39,11 @@ def _adler32_byteswapped(path: str) -> str:
return adler32_of(path, byteswap=True)
_CONTENT_REASONS = {
"romdir": "romdir mismatch: no RESET and ROMVER the code accepts",
"masked_sha1": "masked_sha1 mismatch: the cleared image is not the one the code names",
}
# All reproducible validation types.
_HASH_CHECKS = frozenset({"crc32", "md5", "sha1", "adler32"})
@@ -75,6 +84,7 @@ def _entry_rule(emu_name: str, f: dict, checks: set[str]) -> dict:
- {None},
"min_size": f.get("min_size") if "size" in checks else None,
"max_size": f.get("max_size") if "size" in checks else None,
"size_multiple": f.get("size_multiple") if "size" in checks else None,
"crc32": values("crc32"),
"md5": values("md5"),
"sha1": values("sha1"),
@@ -84,6 +94,9 @@ def _entry_rule(emu_name: str, f: dict, checks: set[str]) -> dict:
},
"adler32_byteswap": bool(f.get("adler32_byteswap")),
"crypto": {c for c in checks if c in _CRYPTO_CHECKS},
"content": {
check: f.get(check) or {} for check in sorted(CONTENT_CHECKS & set(checks))
},
# The checks whose failure the code only warns about: the file runs.
"warn": warned_checks(f, checks),
}
@@ -122,6 +135,8 @@ def _rule_failure(
return f"size too small: min {rule['min_size']}, got {actual_size}"
if rule["max_size"] is not None and actual_size > rule["max_size"]:
return f"size too large: max {rule['max_size']}, got {actual_size}"
if rule.get("size_multiple") and actual_size % int(rule["size_multiple"]):
return f"size mismatch: got {actual_size}, accepted multiples of {rule['size_multiple']}"
for hash_type in ("crc32", "md5", "sha1", "sha256"):
if rule[hash_type] and hash_type not in skip:
if not hashes:
@@ -139,6 +154,9 @@ def _rule_failure(
if actual not in rule["adler32"]:
accepted = ",".join(sorted(rule["adler32"]))
return f"adler32 mismatch: got 0x{actual}, accepted [{accepted}]"
for check, spec in rule.get("content", {}).items():
if check not in skip and not content_fits({"validation": [check], check: spec}, local_path):
return _CONTENT_REASONS[check]
if rule["crypto"] - skip:
from crypto_verify import check_crypto_validation
@@ -253,6 +271,7 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]:
"sizes": set(),
"min_size": None,
"max_size": None,
"size_multiples": set(),
"crc32": set(),
"md5": set(),
"sha1": set(),
@@ -288,6 +307,8 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]:
index[fname]["min_size"] = (
min(cur, f["min_size"]) if cur is not None else f["min_size"]
)
if f.get("size_multiple"):
index[fname]["size_multiples"].add(int(f["size_multiple"]))
if f.get("max_size") is not None:
cur = index[fname]["max_size"]
index[fname]["max_size"] = (
@@ -325,7 +346,7 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]:
# Per-emulator ground truth detail
expected: dict = {}
if "size" in checks:
for key in ("size", "min_size", "max_size"):
for key in ("size", "min_size", "max_size", "size_multiple"):
if f.get(key) is not None:
expected[key] = f[key]
for hash_type in ("crc32", "md5", "sha1", "sha256"):
@@ -334,6 +355,8 @@ def _build_validation_index(profiles: dict) -> dict[str, dict]:
adler_val_pe = f.get("known_hash_adler32") or f.get("adler32")
if adler_val_pe:
expected["adler32"] = adler_val_pe
for check in sorted(CONTENT_CHECKS & set(checks)):
expected[check] = f.get(check) or {}
pe_entry = {
"checks": sorted(checks),
"source_ref": f.get("source_ref"),
@@ -479,6 +502,20 @@ def check_file_validation(
if entry["max_size"] is not None and actual_size > entry["max_size"]:
emus = _emulators_for_check("size", pe)
return f"size too large: max {entry['max_size']}, got {actual_size}", emus
multiples = entry.get("size_multiples") or set()
if multiples and all(actual_size % m for m in multiples):
emus = _emulators_for_check("size", pe)
accepted = ",".join(str(m) for m in sorted(multiples))
return f"size mismatch: got {actual_size}, accepted multiples of [{accepted}]", emus
# A content test passes when one of the entries declaring it accepts
# the file, each read as its own code reads it.
for check in sorted(CONTENT_CHECKS & set(checks)):
specs = [r["content"][check] for r in entry.get("rules", []) if check in r.get("content", {})]
if specs and not any(
content_fits({"validation": [check], check: spec}, local_path) for spec in specs
):
return _CONTENT_REASONS[check], _emulators_for_check(check, pe)
# Hash checks: compute once, reuse for all hash types.
# Each hash field is a set of accepted values (multiple valid ROM versions).
@@ -855,8 +892,8 @@ def agnostic_substitute(
held = candidate.get("path", "")
if (
held.startswith(prefix)
and size_fits(entry, candidate.get("size", 0))
and os.path.exists(held)
and shape_fits(entry, held, candidate.get("size", 0))
):
return held, prefix
break
@@ -1148,8 +1185,12 @@ def core_size_refusal(
if not local_path or not os.path.isfile(local_path):
return None
size = os.path.getsize(local_path)
if any(name_match_size_ok(entry, size) for entry in (file_entry, *alternatives)):
sized = [entry for entry in (file_entry, *alternatives) if name_match_size_ok(entry, size)]
if any(content_fits(entry, local_path) for entry in sized):
return None
if sized:
tests = sorted({check for entry in sized for check in declared_content_checks(entry)})
return f"the core's {', '.join(tests)} test turns it away"
bounds = (
f"{file_entry['size']}" if file_entry.get("size") is not None
else f"{file_entry.get('min_size', 0)} to {file_entry.get('max_size', 'any')}"
+38 -6
View File
@@ -46,6 +46,8 @@ from alternatives import (
slot_set_keys,
)
from common import (
TARGET_KEY,
canonical_target_name,
OUTER_ROOTS,
_foreign_tree,
_owner_tokens,
@@ -100,7 +102,7 @@ from common import (
yaml = require_yaml()
from exporter.candidates import BIOS, EntryCategories
from launchers import LauncherLayer, declared_destinations, held_record
from launchers import LauncherLayer, declared_destinations, held_record, launcher_unproven
from cross_reference import launcher_reads_not_held
from nativemode import (
SIZE_AND_ANY_HASH,
@@ -400,7 +402,7 @@ def _build_expected(file_entry: dict, checks: list[str]) -> dict:
if not checks:
return expected
if "size" in checks:
for key in ("size", "min_size", "max_size"):
for key in ("size", "min_size", "max_size", "size_multiple"):
if file_entry.get(key) is not None:
expected[key] = file_entry[key]
for hash_type in ("crc32", "md5", "sha1", "sha256"):
@@ -564,15 +566,19 @@ def find_undeclared_files(
if emu_name not in relevant:
continue
# Skip agnostic profiles entirely (filename-agnostic BIOS detection)
if profile.get("bios_mode") == "agnostic":
continue
# A filename-agnostic profile is served by the scan (packextras), all
# but the entries its layout reads outside the BIOS tree: those are
# named here, or a launcher folder drops them without a word
# (ARMSX2's arcade/proverb.zip once ROCKNIX binds bios/armsx2).
agnostic = profile.get("bios_mode") == "agnostic"
for profile, is_standalone in platform_layouts(emu_name, profile, standalone_set):
for f in expand_directory_entries(
profile.get("files", []), db, is_standalone
):
if agnostic and not f.get("unplaced"):
continue
fname = f.get("name", "")
# One destination rule for the dedup key and for the entry: a
# standalone build without standalone_path falls back on path.
@@ -805,7 +811,10 @@ def find_undeclared_files(
# Read below the roms directory (ROCKNIX's roms/pico-8)
# or in an emulator folder (RetroBat's emulators/pico8).
entry["root"] = f["root"]
elif launcher_layer and not save_root:
if launcher_layer and not save_root and f.get("root") not in OUTER_ROOTS:
# One read outside the BIOS tree is still served where a
# launcher links that very file: RetroDECK links Cemu's
# keys.txt to bios/cemu/keys.txt.
launcher_candidates.append((emu_name, is_standalone, f, entry))
keys = set_keys((emu_name, is_standalone), f)
if duplicate:
@@ -1757,6 +1766,8 @@ def verify_platform(
"launcher_reads_not_held": launcher_reads_not_held(
{config.get("_key", platform): config}, db, profiles, data_dir_registry
),
# Records a config file does not prove: listed, never consumed.
"launcher_unproven": launcher_unproven({config.get("_key", platform): config}, profiles),
"exclusion_notes": exclusions,
"region_fallbacks": sorted(region_fallbacks),
**({"left_out": left_out} if no_game_data else {}),
@@ -2123,6 +2134,21 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None:
)
def _print_launcher_unproven(result: dict, verbose: bool) -> None:
"""Launcher records resting on a config file the code does not prove."""
rows = result.get("launcher_unproven") or []
if not rows:
return
listed = "" if verbose else " (--verbose lists them)"
print(f" Launcher records unproven: {len(rows)}{listed}")
if not verbose:
return
for row in rows:
print(f" [{row['index']}] {row['emulator']} {row['kind']}: {row['passes_to']}")
for link in row["missing"]:
print(f" missing {link}")
def _print_launcher_reads(result: dict, verbose: bool) -> None:
"""Names the platform's launch code reads that the collection lacks."""
every = result.get("launcher_reads_not_held") or []
@@ -2213,6 +2239,7 @@ def print_platform_result(
_print_detail_entries(result["details"], seen_details, verbose)
_print_undeclared_section(result, verbose)
_print_launcher_reads(result, verbose)
_print_launcher_unproven(result, verbose)
# The same notes come back for every platform running these cores and
# filled 985 of the 1114 lines of verify --all: counted, listed on ask.
@@ -3277,6 +3304,11 @@ def _main(held: contextlib.ExitStack) -> None:
for group_platforms, representative in groups:
config = load_platform_config(representative, args.platforms_dir)
tc = target_cores_cache.get(representative) if args.target else None
if tc is not None:
# A core a roms folder offers on other boards only is not placed
# there, as generate_pack builds the board's pack.
config = {**config, TARGET_KEY: canonical_target_name(
[representative], args.target, args.platforms_dir)}
result = verify_platform(
config,
db,