From c6352f2db1d1eb092aee1b82d428aae74d10b2f5 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:32:15 +0100 Subject: [PATCH] refactor: split the launcher layer by subject --- scripts/packs/coverage.py | 2 +- scripts/packs/crossref.py | 2 +- scripts/packs/crossreflaunchers.py | 7 +- scripts/packs/crossrefrun.py | 3 +- scripts/packs/gaps.py | 3 +- scripts/resolve/categories.py | 3 +- scripts/resolve/contentlayout.py | 2 +- scripts/resolve/launcherconfig.py | 301 ++++++++ scripts/resolve/launcherlayer.py | 475 +++++++++++++ scripts/resolve/launcherplaces.py | 301 ++++++++ scripts/resolve/launchers.py | 1033 +--------------------------- scripts/resolve/layout.py | 3 +- scripts/resolve/standalone.py | 2 +- scripts/sitegen/platformfiles.py | 6 +- tests/test_launcher_evidence.py | 6 +- tests/test_launcher_layer.py | 7 +- tests/test_launcher_placement.py | 2 +- 17 files changed, 1108 insertions(+), 1050 deletions(-) create mode 100644 scripts/resolve/launcherconfig.py create mode 100644 scripts/resolve/launcherlayer.py create mode 100644 scripts/resolve/launcherplaces.py diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py index 15ec7e8f2..5afddec63 100644 --- a/scripts/packs/coverage.py +++ b/scripts/packs/coverage.py @@ -31,7 +31,7 @@ from packs.verdicts import ( ) from resolve.categories import BIOS, EntryCategories from resolve.cores import platform_scope_systems, resolve_platform_cores -from resolve.launchers import launcher_unproven +from resolve.launcherconfig import launcher_unproven from resolve.nativemode import digest_algorithm, platform_mode, reads_file_contents from resolve.validation import ( accepted_hashes, diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index 5c53b8d92..a663ede45 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -19,7 +19,7 @@ from packs.supplemental import SupplementalIndex, data_hit, declared_content from resolve.archives import archive_entry from resolve.content import content_fits, name_match_size_ok from resolve.directories import directory_members -from resolve.launchers import LauncherLayer, held_record +from resolve.launcherlayer import LauncherLayer, held_record from resolve.layout import system_dir_path from resolve.localfile import held_record_for from resolve.ownership import foreign_tree, owner_tokens diff --git a/scripts/packs/crossreflaunchers.py b/scripts/packs/crossreflaunchers.py index 20e77ee4d..1f4bdd27f 100644 --- a/scripts/packs/crossreflaunchers.py +++ b/scripts/packs/crossreflaunchers.py @@ -9,11 +9,10 @@ from model.launcherrecords import record_emulators from model.profiles import lists_files from model.registry import list_registered_platforms from resolve.content import name_match_size_ok -from resolve.launchers import ( - LauncherLayer, - bound_launchers, +from resolve.launcherlayer import LauncherLayer +from resolve.launcherconfig import bound_launchers, launcher_unproven +from resolve.launcherplaces import ( catalogued_model_files, - launcher_unproven, name_settings, record_directories as launcher_directories, record_names as launcher_names, diff --git a/scripts/packs/crossrefrun.py b/scripts/packs/crossrefrun.py index 28bf0ef6b..e8cd5aba0 100644 --- a/scripts/packs/crossrefrun.py +++ b/scripts/packs/crossrefrun.py @@ -11,7 +11,8 @@ from packs.crossref import ( ) from packs.crossrefscope import TreeScope from packs.supplemental import build_supplemental_index -from resolve.launchers import LauncherLayer, declared_destinations +from resolve.launcherlayer import LauncherLayer +from resolve.launchers import declared_destinations def scope_gaps( diff --git a/scripts/packs/gaps.py b/scripts/packs/gaps.py index 27c14b85b..f8cb07a99 100644 --- a/scripts/packs/gaps.py +++ b/scripts/packs/gaps.py @@ -13,7 +13,8 @@ from packs.paths import core_save_folder from resolve.archives import archive_entry, archive_members from resolve.cores import resolve_platform_cores from resolve.directories import expand_directory_entries -from resolve.launchers import LauncherLayer, declared_destinations, held_record +from resolve.launcherlayer import LauncherLayer, held_record +from resolve.launchers import declared_destinations from resolve.layout import system_dir_path from resolve.localfile import resolve_local_file from resolve.nativemode import hash_mismatch_excludes_file, platform_mode diff --git a/scripts/resolve/categories.py b/scripts/resolve/categories.py index d39ddf7a7..f819308a6 100644 --- a/scripts/resolve/categories.py +++ b/scripts/resolve/categories.py @@ -22,7 +22,8 @@ from core.hashing import declared_hashes, parse_hash_list from resolve.reconcile import ( HASH_FIELDS, NativeSystem, comparable, contradicts, entry_names, ) -from resolve.launchers import bound_launchers, record_names as launcher_names +from resolve.launcherconfig import bound_launchers +from resolve.launcherplaces import record_names as launcher_names def _tails(path: str) -> list[str]: diff --git a/scripts/resolve/contentlayout.py b/scripts/resolve/contentlayout.py index 298e16757..2449a7fbe 100644 --- a/scripts/resolve/contentlayout.py +++ b/scripts/resolve/contentlayout.py @@ -303,7 +303,7 @@ def _libretro_content_layout( # path with stand for these: libretro MAME hands MAME # /mame/bios unless the content's command line names # another (retro_init.cpp Set_Path_Option, execute_game_cmd). - from resolve.launchers import pool_folders + from resolve.launcherconfig import pool_folders pools = set(pool_folders({"standalone_pools": view.get("libretro_pools")}).values()) out: list = [] diff --git a/scripts/resolve/launcherconfig.py b/scripts/resolve/launcherconfig.py new file mode 100644 index 000000000..db8ad827d --- /dev/null +++ b/scripts/resolve/launcherconfig.py @@ -0,0 +1,301 @@ +"""Whether a launcher record's config file binds: the evidence that the emulator reads what the platform writes.""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from dataclasses import dataclass + +from model.launcherrecords import record_emulators +from model.profiles import lists_files, platform_builds, profile_names + + +# 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/". 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"(?" 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 + + 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 record_emulators(record): + named = [ + key for key, profile in profiles.items() + if lists_files(profile) and part in profile_names(key, profile) + ] + found.extend(platform_builds(named, profiles, platform)) + 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 resolve.launcherrefs import config_ref, is_feature_ref + + 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)) + + +def _cites_config(record: dict) -> bool: + from resolve.launcherrefs import config_ref + + 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]) -> 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 against the run's profiles. + """ + 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 + platform = str(config.get("_key") or "") + return [r for r in records if config_evidence(r, profiles, platform).proven] + + +def launcher_unproven( + configs: Mapping[str, dict], profiles: Mapping[str, dict] +) -> 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 + for index, record in enumerate(records): + evidence = config_evidence(record, profiles, 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 diff --git a/scripts/resolve/launcherlayer.py b/scripts/resolve/launcherlayer.py new file mode 100644 index 000000000..021c5f3ff --- /dev/null +++ b/scripts/resolve/launcherlayer.py @@ -0,0 +1,475 @@ +"""The platform's launcher layer, read by verify and by the pack builder. + +A platform's own launch code often decides which name a file is read under. +Batocera's DuckStation generator tries 22 names per region and keeps the +first it finds, RetroBat's ares launcher writes the LaserActive image it +finds into ares's settings. The platform scraper records that code under +``launchers:`` and this module turns the records into places: a set of +destinations, relative to the directory core files go to, any one of which +the launcher reads for one purpose. + +Two consequences follow, both computed here once for every reader. A core +file the launcher would not read because another name of the same place is +held is not missing on that platform. A place nothing fills yet receives, +under the launcher's name, a file the core accepts by content. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from dataclasses import dataclass + +from core.hashing import HASH_FIELDS, declared_hashes +from core.paths import sanitize_pack_path +from model.database import record_at +from model.launcherrecords import emulator_names +from model.profiles import lists_files, profile_names +from resolve.content import name_match_size_ok +from resolve.launcherplaces import ( + LauncherPlace, + catalogued_model_files, + launcher_places, + set_by, + setting_readers, + suffixed_stem, +) +from resolve.localfile import resolve_local_file + + +def held_record(report: dict, db: dict) -> dict | None: + """The database record of the file the collection holds for a report entry.""" + local, status = resolve_local_file(report, db, dest_hint=report.get("path") or "") + if local is None or status in ("not_found", "hash_mismatch"): + return None + return record_at(db, local) + + +def _hashes(entry: dict) -> dict[str, set[str]]: + expected = entry.get("expected") or {} + return declared_hashes({f: entry.get(f) or expected.get(f) for f in HASH_FIELDS}) + + +def accepts(entry: dict, record: dict) -> bool: + """Whether a core entry takes the database file ``record`` by its content.""" + hashes = _hashes(entry) + if not hashes: + return False + return any( + str(record.get(field, "")).lower() in values + for field, values in hashes.items() + ) + + +@dataclass +class _Candidate: + """A core entry one launcher place stands for, and how it was matched.""" + + entry: dict + names: set[str] + by_content: bool + # Matched by the size the code checks, the entry naming no hash. + by_shape: bool = False + # Matched through the setting the launcher writes or the name it extends. + by_setting_or_stem: bool = False + + +class LauncherLayer: + """The launcher places of one platform matched to the cores it runs. + + ``declared`` holds each destination the platform declares, relative to + the directory core files go to, case kept. + """ + + def __init__( + self, + config: dict, + profiles: dict, + relevant: Iterable[str], + db: dict, + declared: Iterable[str], + ) -> None: + 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} + self.declared_names_folded = {n.lower() for n in self.declared_names} + by_name = db.get("indexes", {}).get("by_name", {}) + self._by_name = by_name + self._by_name_folded: dict[str, list[str]] = {} + for name, sha1s in by_name.items(): + self._by_name_folded.setdefault(name.lower(), []).extend(sha1s) + self._files = db.get("files", {}) + self._owners: dict[tuple[str, bool], list[LauncherPlace]] = {} + self._unoffered: dict[tuple[str, bool], list[tuple[dict, dict]]] = {} + relevant = set(relevant) + for place in self.places: + standalone = place.build == "standalone" + owners = { + key + for emulator in emulator_names(place.emulator) + 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: 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): + self._owners.setdefault((key, standalone), []).append(place) + # The report never offers a placeholder, which stands for every + # file a scan finds, nor an entry the platform's list settles + # (AmberELEC declares kick34005.A500): the launcher still reads + # its file under its own name. + self._unoffered.setdefault((key, standalone), [ + (entry, _placeholder_report(key, profiles[key], entry)) + for entry in profiles[key].get("files") or [] + ]) + self._db = db + self._declared_elsewhere: set[tuple[str, bool, str, str]] = set() + + def declared_elsewhere(self, emulator: str, standalone: bool, entry: dict) -> None: + """Record a core entry the platform's list settles under another + name. A launcher opening the entry's own name finds nothing there: + RetroPie lists KS 1.3 as kick34005.A500, and its fs-uae launcher + passes $biosdir/kick13.rom. A name the list holds somewhere is + copied to the launcher's place from that declaration.""" + name = str(entry.get("name", "")) + if name.rsplit("/", 1)[-1].lower() in self.declared_names_folded: + return + self._declared_elsewhere.add((emulator, standalone, name, str(entry.get("path") or ""))) + + @staticmethod + def _profiles_named(name: str, profiles: dict, relevant: set[str]) -> list[str]: + """The profiles a platform's emulator name designates, among those it runs.""" + return sorted( + key for key in relevant + if (profile := profiles.get(key)) is not None + and lists_files(profile) + and name in profile_names(key, profile) + ) + + def __bool__(self) -> bool: + return bool(self._owners) + + def places_for(self, emulator: str, standalone: bool) -> list[LauncherPlace]: + return self._owners.get((emulator, standalone), []) + + def files_named(self, place: LauncherPlace, name: str) -> list[dict]: + """The database files carrying a name, in the place's case rule.""" + if place.case_insensitive: + sha1s = self._by_name_folded.get(name.lower(), []) + else: + sha1s = self._by_name.get(name, []) + return [self._files[s] for s in dict.fromkeys(sha1s) if s in self._files] + + def match(self, place: LauncherPlace, entry: dict) -> _Candidate | None: + """How a core entry belongs to a place: by a name it is read under, or by content.""" + basenames = place.basenames() + own = { + place.fold(str(n).rsplit("/", 1)[-1]) + for n in (entry.get("name", ""), *(entry.get("aliases") or [])) + if n + } + names = own & basenames + if names: + return _Candidate(entry, names, False) + # RetroPie runs sdl2trs with `-romfile4p $biosdir/level4p.rom`: the + # file under that name is the one the romfile4p slot reads. + if set_by(entry, place.passes_to): + return _Candidate(entry, basenames, False, by_setting_or_stem=True) + if place.kind == "fixed_name": + stems = { + base for base in basenames + if (stem := suffixed_stem(base)) is not None and place.fold(stem) in own + } + if stems: + return _Candidate(entry, stems, False, by_setting_or_stem=True) + content = { + place.fold(path.rsplit("/", 1)[-1]) + for path in place.paths + if any( + accepts(entry, record) + for record in self.files_named(place, path.rsplit("/", 1)[-1]) + ) + } + if content: + return _Candidate(entry, content, True) + # A hashless entry the code checks by size: EmuDeck passes + # Complex_4627v1.03.bin as xemu's flash ROM, and xemu's entry + # Complex_4627.bin states only the sizes it maps. + checks = entry.get("validation") or [] + sized = any(entry.get(k) for k in ("size", "min_size", "max_size")) + if not _hashes(entry) and sized and "size" in checks: + shaped = { + place.fold(path.rsplit("/", 1)[-1]) + for path in place.paths + if any( + name_match_size_ok(entry, record.get("size")) + for record in self.files_named(place, path.rsplit("/", 1)[-1]) + ) + } + if shaped: + return _Candidate(entry, shaped, False, by_shape=True) + return None + + def platform_holds(self, place: LauncherPlace) -> bool: + """Whether the platform's own list declares a file the place reads.""" + if place.anchored: + pool = self.declared_folded if place.case_insensitive else self.declared + return any(place.fold(path) in pool for path in place.paths) + pool = self.declared_names_folded if place.case_insensitive else self.declared_names + return bool(place.basenames() & pool) + + def _add_unoffered( + self, + by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]], + offered: set[int], + resolve_held: Callable[[dict], dict | None], + ) -> None: + """The entries the report left out, each answering only through a + launcher's setting or extended name.""" + for layout, members in self._unoffered.items(): + for entry, report in members: + if id(entry) in offered: + continue + if "<" not in str(entry.get("name", "")): + report["in_repo"] = resolve_held(report) is not None + report["unoffered"] = True + if (*layout, str(entry.get("name", "")), + str(entry.get("path") or "")) in self._declared_elsewhere: + report["declared_elsewhere"] = True + by_layout.setdefault(layout, []).append((entry, report)) + + def settle( + self, + candidates: list[tuple[str, bool, dict, dict]], + resolve_held: Callable[[dict], dict | None], + ) -> tuple[list[dict], set[int]]: + """What the launcher layer adds to the report and what it settles. + + ``candidates`` holds (profile, standalone, profile entry, report + entry) for every core entry the report considered. ``resolve_held`` + returns the database record of the file the collection holds for a + report entry, None when it holds none. + + Returns the report entries to add, one per place nothing filled that + a held file the core accepts can fill under the launcher's name, and + the ids of the report entries the filled places settle. + """ + added: list[dict] = [] + settled: set[int] = set() + # Destinations the report already fills with a held file, whichever + # core asked for it: the pack puts a file there either way. + reported_at: dict[str, dict] = {} + for _emulator, _standalone, _entry, report in candidates: + # 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]]] = {} + for emulator, standalone, entry, report in candidates: + by_layout.setdefault((emulator, standalone), []).append((entry, report)) + self._add_unoffered( + by_layout, {id(entry) for _e, _s, entry, _r in candidates}, resolve_held, + ) + placed: set[str] = set() + for (emulator, standalone), members in sorted(by_layout.items()): + for place in self.places_for(emulator, standalone): + # An entry the report left out answers only through the + # setting or the extended name: by its own name it was left + # out for a reason (a region variant, a settled duplicate). + # One the platform settles under another name still answers + # by its own: the place reads a name the list does not hold. + matched = [ + (candidate, report) + for entry, report in members + if (candidate := self.match(place, entry)) is not None + and (candidate.by_setting_or_stem or not report.get("unoffered") + or report.get("declared_elsewhere")) + ] + # A size names one entry only when no other of the core's + # entries takes that size too. + if sum(c.by_shape for c, _ in matched) > 1: + matched = [(c, r) for c, r in matched if not c.by_shape] + if not matched: + continue + filled = self._fill(place, matched, reported_at, resolve_held, placed) + if filled is None: + 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: + # EmuDeck passes Complex_4627v1.03.bin to xemu, which then + # never opens Complex_4627.bin. A held file sitting on one + # of the place's own paths is what fills it. + own = {place.fold(p) for p in place.paths} + settled.update( + id(report) for _candidate, report in matched + if not report.get("in_repo") + or place.fold(sanitize_pack_path( + report.get("path") or report.get("name", "") + )) not in own + ) + return added, settled + + def _fill( + self, + place: LauncherPlace, + matched: list[tuple[_Candidate, dict]], + reported_at: dict[str, dict], + resolve_held: Callable[[dict], dict | None], + placed: set[str], + ) -> dict | bool | None: + """True when the place is filled already, a new report entry when one fills it.""" + if self.platform_holds(place): + return True + folded_reported = {place.fold(dest): r for dest, r in reported_at.items()} + for path in place.paths: + name = path.rsplit("/", 1)[-1] + key = place.fold(name) + if place.anchored: + if place.fold(path) in folded_reported: + return True + elif any( + key == place.fold(r.get("name", "")) or key == place.fold(dest.rsplit("/", 1)[-1]) + for dest, r in folded_reported.items() + ): + return True + if not place.anchored: + # A setting holds a name the core resolves in the directory + # of the entry read from it: LRPS2 joins pcsx2_bios under + # pcsx2/bios. + setting = [ + (candidate, report) for candidate, report in matched + if set_by(candidate.entry, place.passes_to) + ] + directory = next( + ( + str(c.entry.get("path") or "").rpartition("/")[0] + for c, _report in setting + if "/" in str(c.entry.get("path") or "") + ), + None, + ) + if directory is None: + continue + path = f"{directory}/{name}" + if place.fold(path) in folded_reported: + return True + source = self._content_for(place, name, key, setting, resolve_held) + if source is None or place.fold(path) in placed: + continue + placed.add(place.fold(path)) + return _launcher_entry(source[0], name, path, source[1], place) + # The emulator as this platform installs it brings the file: the + # place is filled, nothing is packed (ROCKNIX's xemu hdd image). + if any(key in candidate.names and report.get("bundled") + for candidate, report in matched): + return True + source = self._content_for(place, name, key, matched, resolve_held) + if source is None: + continue + report, record = source + if place.fold(path) in placed: + return True + placed.add(place.fold(path)) + return _launcher_entry(report, name, path, record, place) + return None + + def _content_for( + self, + place: LauncherPlace, + name: str, + key: str, + matched: list[tuple[_Candidate, dict]], + resolve_held: Callable[[dict], dict | None], + ) -> tuple[dict, dict] | None: + """A held file the core accepts for one launcher name, and its entry. + + The file the database knows under that name comes first when the + core accepts it: by content when the entry pins one, by name and + size when the entry reads it under that name. Otherwise the file the + collection holds for an entry read under that name. + """ + for candidate, report in matched: + if key not in candidate.names: + continue + for record in self.files_named(place, name): + if accepts(candidate.entry, record) or ( + not candidate.by_content + and not _hashes(candidate.entry) + and name_match_size_ok(candidate.entry, record.get("size")) + ): + return report, record + for candidate, report in matched: + if key not in candidate.names or candidate.by_content: + continue + if not report.get("in_repo"): + continue + held = resolve_held(report) + if held is not None: + return report, held + for candidate, report in matched: + if key not in candidate.names or not set_by(candidate.entry, place.passes_to): + continue + for record in catalogued_model_files(name, self._db): + if name_match_size_ok(candidate.entry, record.get("size")): + return report, record + return None + + +def _placeholder_report(key: str, profile: dict, entry: dict) -> dict: + """The report entry of an entry the gap report never builds.""" + identity = { + field: entry[field] + for field in ("aliases", "md5", "sha1", "sha256", "crc32", "size", "min_size", "max_size") + if entry.get(field) is not None + } + return { + **identity, + "profile": key, + "emulator": profile.get("emulator", key), + "name": entry.get("name", ""), + "path": entry.get("path") or entry.get("name", ""), + "system": entry.get("system"), + "systems": profile.get("systems"), + "required": entry.get("required", False), + "category": entry.get("category"), + "in_repo": False, + } + + +def _launcher_entry( + report: dict, name: str, path: str, record: dict, place: LauncherPlace +) -> dict: + """The report entry asking for a file under the name a launcher opens.""" + entry = { + key: report.get(key) + for key in ( + "profile", "emulator", "systems", "system", "region", "selection_slot", + "required", "hle_fallback", "category", + ) + } + entry.update( + name=name, + path=path, + bundled=False, + in_repo=True, + note="", + checks=[], + source_ref=None, + expected={}, + sha1=record.get("sha1"), + md5=record.get("md5"), + launcher=place.source_ref, + launcher_of=report.get("name", ""), + ) + return entry diff --git a/scripts/resolve/launcherplaces.py b/scripts/resolve/launcherplaces.py new file mode 100644 index 000000000..bfcb4b65d --- /dev/null +++ b/scripts/resolve/launcherplaces.py @@ -0,0 +1,301 @@ +"""A launcher record's names and directories, turned into the places the launcher reads a file from.""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Mapping +from dataclasses import dataclass + +from core.paths import comparable_destination, sanitize_pack_path +from resolve.launcherconfig import bound_launchers + + +# The kinds whose names say which file the launcher opens. A link of a named +# file is one too: ROCKNIX links /storage/roms/bios/nds_bios_arm9.bin into +# DraStic's system folder, so that is the path the emulator reads. The others +# hand over a directory, copy a file the platform already names, or let the +# emulator choose. +PLACE_KINDS = ("names_searched", "fixed_name", "core_option", "links") + +# How each launcher extractor spells the BIOS directory in search_dir, as the +# platform's own scripts name it: RetroPie's scriptmodules ($biosdir, +# retropie_reader.BIOSDIR), EmuDeck's EmuScripts (${biosPath}, +# emudeck_launchers.BIOS) and RetroDECK's framework ($bios_path, +# retrodeck_launchers.BIOS). +BIOS_ROOT_TOKENS = ("$biosdir", "${biosdir}", "${biosPath}", "$bios_path", "${bios_path}") + +# A path spelled from a home or filesystem root names the BIOS directory by +# its base name: /userdata/bios, ~/roms/bios, $HOME/RetroPie/BIOS. +_ROOTED = ("/", "~/", "$HOME/", "$home/", "${HOME}/") + +_LABELLED = re.compile(r"^([^\s()]+\.[A-Za-z0-9]+) \([^()]*\)$") +_PLACEHOLDER = re.compile(r"\{(\w+)\}") + + +@dataclass(frozen=True) +class LauncherPlace: + """One file a launcher opens, under any of ``paths``. + + ``paths`` are in the order the launcher tries them, relative to the + directory core files go to. An unanchored place has no directory of its + own: the core resolves the name the launcher passes in the directory it + reads the entry from. ``alternatives`` is true when the launcher keeps + the first name it finds, false when each path is the one it passes. + """ + + emulator: str + build: str + kind: str + slot: str + paths: tuple[str, ...] + case_insensitive: bool + anchored: bool + conditional: bool + source_ref: str + passes_to: str = "" + + def fold(self, name: str) -> str: + return comparable_destination(name, self.case_insensitive) + + def basenames(self) -> set[str]: + return {self.fold(p.rsplit("/", 1)[-1]) for p in self.paths} + + @property + def stands_for_default(self) -> bool: + """Whether filling the place means the core's default is never read. + + A launcher that always passes the file it found replaces the name + the core would open by itself. A record that applies only under an + option or a system leaves that default in use elsewhere, and a core + option offers a file the user may choose without ever choosing it. + """ + return ( + self.kind in ("names_searched", "fixed_name", "links") + and not self.conditional + ) + + +def setting_tokens(passes_to: str) -> set[str]: + """The words of a record's ``passes_to``, as an emulator setting is spelled. + + "command line -romfile4p" hands the file to sdltrs's romfile4p option, + "settings.bml NeoGeoPocket/Firmware/BIOS.World" to an ares setting. + """ + return { + word.strip("()\"',;").lstrip("-") + for word in passes_to.split() + } - {""} + + +def suffixed_stem(name: str) -> str | None: + """The file name a launcher name carries before an extension it appended. + + ROCKNIX's Amiberry config passes kick34005.A500.rom, the name Amiberry + gives Kickstart 1.3 (amiberry_whdbooter.cpp:370) followed by ".rom". A + stem that is no file name itself (scph1001 of scph1001.bin) is none. + """ + base = name.rsplit("/", 1)[-1] + stem = base.rsplit(".", 1)[0] + return stem if "." in stem else None + + +_MODEL = re.compile(r"\b([A-Z]{2,5})-?(\d{3,6}[A-Z]?)\b") + + +def catalogued_model_files(name: str, db: dict) -> list[dict]: + """Held files a dump catalogue describes as the model a launcher name spells. + + RetroDECK sets LRPS2's pcsx2_bios option to scph10000.bin, a name no code + hashes: the SCPH-10000 is the model whose BIOS it means. Redump and TOSEC + describe two revisions for it. Primaries come before .variants copies, + then the Redump name, which carries the version (ps2-0100j before + ps2-0101j), then the No-Intro and TOSEC names. + """ + stem = name.rsplit("/", 1)[-1].rsplit(".", 1)[0].casefold() + if not re.fullmatch(r"[a-z]{2,5}\d{3,6}[a-z]?", stem): + return [] + found = [] + for record in db.get("files", {}).values(): + catalogues = record.get("provenance") or {} + models = { + (a + b).casefold() + for entry in catalogues.values() + for a, b in _MODEL.findall(str(entry.get("description") or "")) + } + if stem in models: + names = [ + str((catalogues.get(source) or {}).get("name") or "") + for source in ("redump", "no-intro", "tosec") + ] + found.append(("/.variants/" in str(record.get("path", "")), names, record)) + # The core accepts every revision of the model, and neither priority nor + # region separates two primaries. The pick must still be the same on + # every run, so it goes to the original revision: the Redump name carries + # the version, and ps2-0100j sorts before ps2-0101j. + return [record for *_key, record in sorted(found, key=lambda f: (f[0], f[1]))] + + +def name_settings(record: dict, names: list[str]) -> dict[str, str]: + """The setting each name of a record is written to. + + A record naming several files of one config spells passes_to as + describe_keys does (shell_launchers.py), "atari800.cfg ROM_OS_A_PAL, + ROM_5200_A, ...", one key per name and in the order of the names. When + the counts differ, each name keeps the whole description. + """ + passes_to = str(record.get("passes_to") or "") + head, _, rest = passes_to.partition(" ") + keys = [ + key.strip() + for key in re.sub(r"\[[^\]]*\]", ",", rest).split(",") + if key.strip() + ] + if len(names) > 1 and len(keys) == len(names) and all(" " not in k for k in keys): + return {name: f"{head} {key}" for name, key in zip(names, keys)} + return {name: passes_to for name in names} + + +def setting_readers(passes_to: str, profiles: dict, keys: Iterable[str]) -> list[str]: + """The profiles with an entry read from the setting a launcher writes.""" + if not passes_to: + return [] + return sorted( + key for key in keys + if (profile := profiles.get(key)) is not None + and any(set_by(entry, passes_to) for entry in profile.get("files") or []) + ) + + +def set_by(entry: dict, passes_to: str) -> bool: + """Whether a launcher hands its file to the setting a profile entry is read from.""" + key = str(entry.get("config_key") or "") + return bool(key) and key in setting_tokens(passes_to) + + +def _bios_relative(directory: str, base: str) -> str | None: + """A launcher directory relative to the BIOS root, None when it is not one.""" + directory = directory.strip().rstrip("/") + roots = {base, "", *BIOS_ROOT_TOKENS} + head, _, rest = directory.partition("/") + if directory in roots: + return "" + if head in roots: + relative = rest + elif directory.startswith(_ROOTED) and base and f"/{base}/" in f"{directory}/": + relative = f"{directory}/".split(f"/{base}/", 1)[1].rstrip("/") + else: + return None + return None if re.search(r"[\s<>]", relative) else relative + + +def record_directories(record: dict, base: str) -> list[str] | None: + """The directories a record reads, in order. None when the code says none. + + ``search_dir`` transcribes the code, conditions included: "bios/chihiro, + then bios", "bios/pcsx2/bios if any listed name is there, else bios". + A directory the record describes rather than names ("directory of the + Chihiro BIOS found") cannot be placed. + """ + raw = record.get("search_dir") + if raw is None: + return None + text = re.sub(r"\([^()]*\)", "", str(raw)) + text = re.sub(r"\s+if\s+[^,]*", "", text) + found: list[str] = [] + for part in re.split(r",|\bthen\b|\belse\b", text): + if not part.strip(): + continue + relative = _bios_relative(part, base) + if relative is None: + return [] + if relative not in found: + found.append(relative) + return found + + +def record_names(record: dict) -> list[str]: + """The file names a record tries, placeholders expanded in code order.""" + expands = record.get("expands") or {} + names: list[str] = [] + for raw in record.get("names") or []: + name = str(raw).strip() + labelled = _LABELLED.match(name) + if labelled: + name = labelled.group(1) + expanded = [name] + for key in _PLACEHOLDER.findall(name): + values = expands.get(key) + if values is None: + expanded = [] + break + expanded = [ + candidate.replace("{" + key + "}", str(value)) + for candidate in expanded + for value in values + ] + for candidate in expanded: + if "<" in candidate or "." not in candidate.rsplit("/", 1)[-1]: + continue + if candidate not in names: + names.append(candidate) + return names + + +def _place_paths(name: str, directories: list[str] | None) -> tuple[str, ...]: + """The paths a name is opened at: under each directory, or bare when the + record anchors it nowhere.""" + if directories is None: + return (name,) + return tuple( + sanitize_pack_path(f"{d}/{name}" if d else name) for d in directories + ) + + +def launcher_places( + config: dict, profiles: Mapping[str, dict] +) -> 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 bound_launchers(config, profiles): + kind = record.get("kind") + if kind not in PLACE_KINDS: + continue + names = record_names(record) + directories = record_directories(record, base) + if not names or directories == []: + continue + anchored = directories is not None + common = { + "emulator": str(record.get("emulator", "")), + "build": str(record.get("build", "")), + "kind": kind, + "slot": str(record.get("slot") or ""), + # A filesystem that folds case folds it for the launcher too. + "case_insensitive": bool( + record.get("case_insensitive") or config.get("case_insensitive_fs") + ), + "anchored": anchored, + "conditional": bool(record.get("depends_on_option")), + "source_ref": str(record.get("source_ref", "")), + } + settings = name_settings(record, names) + if kind == "names_searched": + # Each directory in turn, every name in it. + depth = len(directories) if directories is not None else 1 + ordered = tuple( + _place_paths(name, directories)[i] for i in range(depth) for name in names + ) + places.append(LauncherPlace( + paths=ordered, passes_to=str(record.get("passes_to") or ""), **common + )) + continue + # A fixed name is the one file passed, and a core option offers + # each value as the file the user picks: one place per name. + places.extend( + LauncherPlace( + paths=_place_paths(name, directories), passes_to=settings[name], **common + ) + for name in names + ) + return places diff --git a/scripts/resolve/launchers.py b/scripts/resolve/launchers.py index cd29e5442..4113ef594 100644 --- a/scripts/resolve/launchers.py +++ b/scripts/resolve/launchers.py @@ -17,598 +17,14 @@ under the launcher's name, a file the core accepts by content. from __future__ import annotations import re -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Iterable, Mapping from dataclasses import dataclass -from core.hashing import HASH_FIELDS, declared_hashes -from model.database import record_at from model.declarations import CONFIGS_ROOT, ROMS_ROOT, declared_root, declared_slot, outer_layout -from model.launcherrecords import emulator_names, record_emulators -from model.profiles import lists_files, platform_builds, profile_names -from resolve.content import name_match_size_ok -from resolve.localfile import resolve_local_file -from core.paths import comparable_destination, sanitize_pack_path - -# The kinds whose names say which file the launcher opens. A link of a named -# file is one too: ROCKNIX links /storage/roms/bios/nds_bios_arm9.bin into -# DraStic's system folder, so that is the path the emulator reads. The others -# hand over a directory, copy a file the platform already names, or let the -# emulator choose. -PLACE_KINDS = ("names_searched", "fixed_name", "core_option", "links") - -# How each launcher extractor spells the BIOS directory in search_dir, as the -# platform's own scripts name it: RetroPie's scriptmodules ($biosdir, -# retropie_reader.BIOSDIR), EmuDeck's EmuScripts (${biosPath}, -# emudeck_launchers.BIOS) and RetroDECK's framework ($bios_path, -# retrodeck_launchers.BIOS). -BIOS_ROOT_TOKENS = ("$biosdir", "${biosdir}", "${biosPath}", "$bios_path", "${bios_path}") - -# A path spelled from a home or filesystem root names the BIOS directory by -# its base name: /userdata/bios, ~/roms/bios, $HOME/RetroPie/BIOS. -_ROOTED = ("/", "~/", "$HOME/", "$home/", "${HOME}/") - -_LABELLED = re.compile(r"^([^\s()]+\.[A-Za-z0-9]+) \([^()]*\)$") -_PLACEHOLDER = re.compile(r"\{(\w+)\}") - - -@dataclass(frozen=True) -class LauncherPlace: - """One file a launcher opens, under any of ``paths``. - - ``paths`` are in the order the launcher tries them, relative to the - directory core files go to. An unanchored place has no directory of its - own: the core resolves the name the launcher passes in the directory it - reads the entry from. ``alternatives`` is true when the launcher keeps - the first name it finds, false when each path is the one it passes. - """ - - emulator: str - build: str - kind: str - slot: str - paths: tuple[str, ...] - case_insensitive: bool - anchored: bool - conditional: bool - source_ref: str - passes_to: str = "" - - def fold(self, name: str) -> str: - return comparable_destination(name, self.case_insensitive) - - def basenames(self) -> set[str]: - return {self.fold(p.rsplit("/", 1)[-1]) for p in self.paths} - - @property - def stands_for_default(self) -> bool: - """Whether filling the place means the core's default is never read. - - A launcher that always passes the file it found replaces the name - the core would open by itself. A record that applies only under an - option or a system leaves that default in use elsewhere, and a core - option offers a file the user may choose without ever choosing it. - """ - return ( - self.kind in ("names_searched", "fixed_name", "links") - and not self.conditional - ) - - -def setting_tokens(passes_to: str) -> set[str]: - """The words of a record's ``passes_to``, as an emulator setting is spelled. - - "command line -romfile4p" hands the file to sdltrs's romfile4p option, - "settings.bml NeoGeoPocket/Firmware/BIOS.World" to an ares setting. - """ - return { - word.strip("()\"',;").lstrip("-") - for word in passes_to.split() - } - {""} - - -def suffixed_stem(name: str) -> str | None: - """The file name a launcher name carries before an extension it appended. - - ROCKNIX's Amiberry config passes kick34005.A500.rom, the name Amiberry - gives Kickstart 1.3 (amiberry_whdbooter.cpp:370) followed by ".rom". A - stem that is no file name itself (scph1001 of scph1001.bin) is none. - """ - base = name.rsplit("/", 1)[-1] - stem = base.rsplit(".", 1)[0] - return stem if "." in stem else None - - -_MODEL = re.compile(r"\b([A-Z]{2,5})-?(\d{3,6}[A-Z]?)\b") - - -def catalogued_model_files(name: str, db: dict) -> list[dict]: - """Held files a dump catalogue describes as the model a launcher name spells. - - RetroDECK sets LRPS2's pcsx2_bios option to scph10000.bin, a name no code - hashes: the SCPH-10000 is the model whose BIOS it means. Redump and TOSEC - describe two revisions for it. Primaries come before .variants copies, - then the Redump name, which carries the version (ps2-0100j before - ps2-0101j), then the No-Intro and TOSEC names. - """ - stem = name.rsplit("/", 1)[-1].rsplit(".", 1)[0].casefold() - if not re.fullmatch(r"[a-z]{2,5}\d{3,6}[a-z]?", stem): - return [] - found = [] - for record in db.get("files", {}).values(): - catalogues = record.get("provenance") or {} - models = { - (a + b).casefold() - for entry in catalogues.values() - for a, b in _MODEL.findall(str(entry.get("description") or "")) - } - if stem in models: - names = [ - str((catalogues.get(source) or {}).get("name") or "") - for source in ("redump", "no-intro", "tosec") - ] - found.append(("/.variants/" in str(record.get("path", "")), names, record)) - # The core accepts every revision of the model, and neither priority nor - # region separates two primaries. The pick must still be the same on - # every run, so it goes to the original revision: the Redump name carries - # the version, and ps2-0100j sorts before ps2-0101j. - return [record for *_key, record in sorted(found, key=lambda f: (f[0], f[1]))] - - -def name_settings(record: dict, names: list[str]) -> dict[str, str]: - """The setting each name of a record is written to. - - A record naming several files of one config spells passes_to as - describe_keys does (shell_launchers.py), "atari800.cfg ROM_OS_A_PAL, - ROM_5200_A, ...", one key per name and in the order of the names. When - the counts differ, each name keeps the whole description. - """ - passes_to = str(record.get("passes_to") or "") - head, _, rest = passes_to.partition(" ") - keys = [ - key.strip() - for key in re.sub(r"\[[^\]]*\]", ",", rest).split(",") - if key.strip() - ] - if len(names) > 1 and len(keys) == len(names) and all(" " not in k for k in keys): - return {name: f"{head} {key}" for name, key in zip(names, keys)} - return {name: passes_to for name in names} - - -def setting_readers(passes_to: str, profiles: dict, keys: Iterable[str]) -> list[str]: - """The profiles with an entry read from the setting a launcher writes.""" - if not passes_to: - return [] - return sorted( - key for key in keys - if (profile := profiles.get(key)) is not None - and any(set_by(entry, passes_to) for entry in profile.get("files") or []) - ) - - -def set_by(entry: dict, passes_to: str) -> bool: - """Whether a launcher hands its file to the setting a profile entry is read from.""" - key = str(entry.get("config_key") or "") - return bool(key) and key in setting_tokens(passes_to) - - -def _bios_relative(directory: str, base: str) -> str | None: - """A launcher directory relative to the BIOS root, None when it is not one.""" - directory = directory.strip().rstrip("/") - roots = {base, "", *BIOS_ROOT_TOKENS} - head, _, rest = directory.partition("/") - if directory in roots: - return "" - if head in roots: - relative = rest - elif directory.startswith(_ROOTED) and base and f"/{base}/" in f"{directory}/": - relative = f"{directory}/".split(f"/{base}/", 1)[1].rstrip("/") - else: - return None - return None if re.search(r"[\s<>]", relative) else relative - - -def record_directories(record: dict, base: str) -> list[str] | None: - """The directories a record reads, in order. None when the code says none. - - ``search_dir`` transcribes the code, conditions included: "bios/chihiro, - then bios", "bios/pcsx2/bios if any listed name is there, else bios". - A directory the record describes rather than names ("directory of the - Chihiro BIOS found") cannot be placed. - """ - raw = record.get("search_dir") - if raw is None: - return None - text = re.sub(r"\([^()]*\)", "", str(raw)) - text = re.sub(r"\s+if\s+[^,]*", "", text) - found: list[str] = [] - for part in re.split(r",|\bthen\b|\belse\b", text): - if not part.strip(): - continue - relative = _bios_relative(part, base) - if relative is None: - return [] - if relative not in found: - found.append(relative) - return found - - -def record_names(record: dict) -> list[str]: - """The file names a record tries, placeholders expanded in code order.""" - expands = record.get("expands") or {} - names: list[str] = [] - for raw in record.get("names") or []: - name = str(raw).strip() - labelled = _LABELLED.match(name) - if labelled: - name = labelled.group(1) - expanded = [name] - for key in _PLACEHOLDER.findall(name): - values = expands.get(key) - if values is None: - expanded = [] - break - expanded = [ - candidate.replace("{" + key + "}", str(value)) - for candidate in expanded - for value in values - ] - for candidate in expanded: - if "<" in candidate or "." not in candidate.rsplit("/", 1)[-1]: - continue - if candidate not in names: - names.append(candidate) - return names - - -# 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/". 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"(?" 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 - - 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 record_emulators(record): - named = [ - key for key, profile in profiles.items() - if lists_files(profile) and part in profile_names(key, profile) - ] - found.extend(platform_builds(named, profiles, platform)) - 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 resolve.launcherrefs import config_ref, is_feature_ref - - 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)) - - -def _cites_config(record: dict) -> bool: - from resolve.launcherrefs import config_ref - - 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]) -> 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 against the run's profiles. - """ - 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 - platform = str(config.get("_key") or "") - return [r for r in records if config_evidence(r, profiles, platform).proven] - - -def launcher_unproven( - configs: Mapping[str, dict], profiles: Mapping[str, dict] -) -> 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 - for index, record in enumerate(records): - evidence = config_evidence(record, profiles, 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 _place_paths(name: str, directories: list[str] | None) -> tuple[str, ...]: - """The paths a name is opened at: under each directory, or bare when the - record anchors it nowhere.""" - if directories is None: - return (name,) - return tuple( - sanitize_pack_path(f"{d}/{name}" if d else name) for d in directories - ) - - -def launcher_places( - config: dict, profiles: Mapping[str, dict] -) -> 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 bound_launchers(config, profiles): - kind = record.get("kind") - if kind not in PLACE_KINDS: - continue - names = record_names(record) - directories = record_directories(record, base) - if not names or directories == []: - continue - anchored = directories is not None - common = { - "emulator": str(record.get("emulator", "")), - "build": str(record.get("build", "")), - "kind": kind, - "slot": str(record.get("slot") or ""), - # A filesystem that folds case folds it for the launcher too. - "case_insensitive": bool( - record.get("case_insensitive") or config.get("case_insensitive_fs") - ), - "anchored": anchored, - "conditional": bool(record.get("depends_on_option")), - "source_ref": str(record.get("source_ref", "")), - } - settings = name_settings(record, names) - if kind == "names_searched": - # Each directory in turn, every name in it. - depth = len(directories) if directories is not None else 1 - ordered = tuple( - _place_paths(name, directories)[i] for i in range(depth) for name in names - ) - places.append(LauncherPlace( - paths=ordered, passes_to=str(record.get("passes_to") or ""), **common - )) - continue - # A fixed name is the one file passed, and a core option offers - # each value as the file the user picks: one place per name. - places.extend( - LauncherPlace( - paths=_place_paths(name, directories), passes_to=settings[name], **common - ) - for name in names - ) - return places +from model.launcherrecords import record_emulators +from core.paths import sanitize_pack_path +from resolve.launcherconfig import bound_launchers +from resolve.launcherplaces import _bios_relative, record_directories # The names a platform's launch code gives its BIOS root, besides the @@ -1212,14 +628,6 @@ def bound_path(path: str, bindings: dict[str, Place]) -> Place | None: return None -def held_record(report: dict, db: dict) -> dict | None: - """The database record of the file the collection holds for a report entry.""" - local, status = resolve_local_file(report, db, dest_hint=report.get("path") or "") - if local is None or status in ("not_found", "hash_mismatch"): - return None - return record_at(db, local) - - def declared_destinations(config: dict) -> set[str]: """Each destination the platform declares, relative to the core file directory. @@ -1234,434 +642,3 @@ def declared_destinations(config: dict) -> set[str]: if slot: found.add(slot) return found - - -def _hashes(entry: dict) -> dict[str, set[str]]: - expected = entry.get("expected") or {} - return declared_hashes({f: entry.get(f) or expected.get(f) for f in HASH_FIELDS}) - - -def accepts(entry: dict, record: dict) -> bool: - """Whether a core entry takes the database file ``record`` by its content.""" - hashes = _hashes(entry) - if not hashes: - return False - return any( - str(record.get(field, "")).lower() in values - for field, values in hashes.items() - ) - - -@dataclass -class _Candidate: - """A core entry one launcher place stands for, and how it was matched.""" - - entry: dict - names: set[str] - by_content: bool - # Matched by the size the code checks, the entry naming no hash. - by_shape: bool = False - # Matched through the setting the launcher writes or the name it extends. - by_setting_or_stem: bool = False - - -class LauncherLayer: - """The launcher places of one platform matched to the cores it runs. - - ``declared`` holds each destination the platform declares, relative to - the directory core files go to, case kept. - """ - - def __init__( - self, - config: dict, - profiles: dict, - relevant: Iterable[str], - db: dict, - declared: Iterable[str], - ) -> None: - 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} - self.declared_names_folded = {n.lower() for n in self.declared_names} - by_name = db.get("indexes", {}).get("by_name", {}) - self._by_name = by_name - self._by_name_folded: dict[str, list[str]] = {} - for name, sha1s in by_name.items(): - self._by_name_folded.setdefault(name.lower(), []).extend(sha1s) - self._files = db.get("files", {}) - self._owners: dict[tuple[str, bool], list[LauncherPlace]] = {} - self._unoffered: dict[tuple[str, bool], list[tuple[dict, dict]]] = {} - relevant = set(relevant) - for place in self.places: - standalone = place.build == "standalone" - owners = { - key - for emulator in emulator_names(place.emulator) - 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: 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): - self._owners.setdefault((key, standalone), []).append(place) - # The report never offers a placeholder, which stands for every - # file a scan finds, nor an entry the platform's list settles - # (AmberELEC declares kick34005.A500): the launcher still reads - # its file under its own name. - self._unoffered.setdefault((key, standalone), [ - (entry, _placeholder_report(key, profiles[key], entry)) - for entry in profiles[key].get("files") or [] - ]) - self._db = db - self._declared_elsewhere: set[tuple[str, bool, str, str]] = set() - - def declared_elsewhere(self, emulator: str, standalone: bool, entry: dict) -> None: - """Record a core entry the platform's list settles under another - name. A launcher opening the entry's own name finds nothing there: - RetroPie lists KS 1.3 as kick34005.A500, and its fs-uae launcher - passes $biosdir/kick13.rom. A name the list holds somewhere is - copied to the launcher's place from that declaration.""" - name = str(entry.get("name", "")) - if name.rsplit("/", 1)[-1].lower() in self.declared_names_folded: - return - self._declared_elsewhere.add((emulator, standalone, name, str(entry.get("path") or ""))) - - @staticmethod - def _profiles_named(name: str, profiles: dict, relevant: set[str]) -> list[str]: - """The profiles a platform's emulator name designates, among those it runs.""" - return sorted( - key for key in relevant - if (profile := profiles.get(key)) is not None - and lists_files(profile) - and name in profile_names(key, profile) - ) - - def __bool__(self) -> bool: - return bool(self._owners) - - def places_for(self, emulator: str, standalone: bool) -> list[LauncherPlace]: - return self._owners.get((emulator, standalone), []) - - def files_named(self, place: LauncherPlace, name: str) -> list[dict]: - """The database files carrying a name, in the place's case rule.""" - if place.case_insensitive: - sha1s = self._by_name_folded.get(name.lower(), []) - else: - sha1s = self._by_name.get(name, []) - return [self._files[s] for s in dict.fromkeys(sha1s) if s in self._files] - - def match(self, place: LauncherPlace, entry: dict) -> _Candidate | None: - """How a core entry belongs to a place: by a name it is read under, or by content.""" - basenames = place.basenames() - own = { - place.fold(str(n).rsplit("/", 1)[-1]) - for n in (entry.get("name", ""), *(entry.get("aliases") or [])) - if n - } - names = own & basenames - if names: - return _Candidate(entry, names, False) - # RetroPie runs sdl2trs with `-romfile4p $biosdir/level4p.rom`: the - # file under that name is the one the romfile4p slot reads. - if set_by(entry, place.passes_to): - return _Candidate(entry, basenames, False, by_setting_or_stem=True) - if place.kind == "fixed_name": - stems = { - base for base in basenames - if (stem := suffixed_stem(base)) is not None and place.fold(stem) in own - } - if stems: - return _Candidate(entry, stems, False, by_setting_or_stem=True) - content = { - place.fold(path.rsplit("/", 1)[-1]) - for path in place.paths - if any( - accepts(entry, record) - for record in self.files_named(place, path.rsplit("/", 1)[-1]) - ) - } - if content: - return _Candidate(entry, content, True) - # A hashless entry the code checks by size: EmuDeck passes - # Complex_4627v1.03.bin as xemu's flash ROM, and xemu's entry - # Complex_4627.bin states only the sizes it maps. - checks = entry.get("validation") or [] - sized = any(entry.get(k) for k in ("size", "min_size", "max_size")) - if not _hashes(entry) and sized and "size" in checks: - shaped = { - place.fold(path.rsplit("/", 1)[-1]) - for path in place.paths - if any( - name_match_size_ok(entry, record.get("size")) - for record in self.files_named(place, path.rsplit("/", 1)[-1]) - ) - } - if shaped: - return _Candidate(entry, shaped, False, by_shape=True) - return None - - def platform_holds(self, place: LauncherPlace) -> bool: - """Whether the platform's own list declares a file the place reads.""" - if place.anchored: - pool = self.declared_folded if place.case_insensitive else self.declared - return any(place.fold(path) in pool for path in place.paths) - pool = self.declared_names_folded if place.case_insensitive else self.declared_names - return bool(place.basenames() & pool) - - def _add_unoffered( - self, - by_layout: dict[tuple[str, bool], list[tuple[dict, dict]]], - offered: set[int], - resolve_held: Callable[[dict], dict | None], - ) -> None: - """The entries the report left out, each answering only through a - launcher's setting or extended name.""" - for layout, members in self._unoffered.items(): - for entry, report in members: - if id(entry) in offered: - continue - if "<" not in str(entry.get("name", "")): - report["in_repo"] = resolve_held(report) is not None - report["unoffered"] = True - if (*layout, str(entry.get("name", "")), - str(entry.get("path") or "")) in self._declared_elsewhere: - report["declared_elsewhere"] = True - by_layout.setdefault(layout, []).append((entry, report)) - - def settle( - self, - candidates: list[tuple[str, bool, dict, dict]], - resolve_held: Callable[[dict], dict | None], - ) -> tuple[list[dict], set[int]]: - """What the launcher layer adds to the report and what it settles. - - ``candidates`` holds (profile, standalone, profile entry, report - entry) for every core entry the report considered. ``resolve_held`` - returns the database record of the file the collection holds for a - report entry, None when it holds none. - - Returns the report entries to add, one per place nothing filled that - a held file the core accepts can fill under the launcher's name, and - the ids of the report entries the filled places settle. - """ - added: list[dict] = [] - settled: set[int] = set() - # Destinations the report already fills with a held file, whichever - # core asked for it: the pack puts a file there either way. - reported_at: dict[str, dict] = {} - for _emulator, _standalone, _entry, report in candidates: - # 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]]] = {} - for emulator, standalone, entry, report in candidates: - by_layout.setdefault((emulator, standalone), []).append((entry, report)) - self._add_unoffered( - by_layout, {id(entry) for _e, _s, entry, _r in candidates}, resolve_held, - ) - placed: set[str] = set() - for (emulator, standalone), members in sorted(by_layout.items()): - for place in self.places_for(emulator, standalone): - # An entry the report left out answers only through the - # setting or the extended name: by its own name it was left - # out for a reason (a region variant, a settled duplicate). - # One the platform settles under another name still answers - # by its own: the place reads a name the list does not hold. - matched = [ - (candidate, report) - for entry, report in members - if (candidate := self.match(place, entry)) is not None - and (candidate.by_setting_or_stem or not report.get("unoffered") - or report.get("declared_elsewhere")) - ] - # A size names one entry only when no other of the core's - # entries takes that size too. - if sum(c.by_shape for c, _ in matched) > 1: - matched = [(c, r) for c, r in matched if not c.by_shape] - if not matched: - continue - filled = self._fill(place, matched, reported_at, resolve_held, placed) - if filled is None: - 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: - # EmuDeck passes Complex_4627v1.03.bin to xemu, which then - # never opens Complex_4627.bin. A held file sitting on one - # of the place's own paths is what fills it. - own = {place.fold(p) for p in place.paths} - settled.update( - id(report) for _candidate, report in matched - if not report.get("in_repo") - or place.fold(sanitize_pack_path( - report.get("path") or report.get("name", "") - )) not in own - ) - return added, settled - - def _fill( - self, - place: LauncherPlace, - matched: list[tuple[_Candidate, dict]], - reported_at: dict[str, dict], - resolve_held: Callable[[dict], dict | None], - placed: set[str], - ) -> dict | bool | None: - """True when the place is filled already, a new report entry when one fills it.""" - if self.platform_holds(place): - return True - folded_reported = {place.fold(dest): r for dest, r in reported_at.items()} - for path in place.paths: - name = path.rsplit("/", 1)[-1] - key = place.fold(name) - if place.anchored: - if place.fold(path) in folded_reported: - return True - elif any( - key == place.fold(r.get("name", "")) or key == place.fold(dest.rsplit("/", 1)[-1]) - for dest, r in folded_reported.items() - ): - return True - if not place.anchored: - # A setting holds a name the core resolves in the directory - # of the entry read from it: LRPS2 joins pcsx2_bios under - # pcsx2/bios. - setting = [ - (candidate, report) for candidate, report in matched - if set_by(candidate.entry, place.passes_to) - ] - directory = next( - ( - str(c.entry.get("path") or "").rpartition("/")[0] - for c, _report in setting - if "/" in str(c.entry.get("path") or "") - ), - None, - ) - if directory is None: - continue - path = f"{directory}/{name}" - if place.fold(path) in folded_reported: - return True - source = self._content_for(place, name, key, setting, resolve_held) - if source is None or place.fold(path) in placed: - continue - placed.add(place.fold(path)) - return _launcher_entry(source[0], name, path, source[1], place) - # The emulator as this platform installs it brings the file: the - # place is filled, nothing is packed (ROCKNIX's xemu hdd image). - if any(key in candidate.names and report.get("bundled") - for candidate, report in matched): - return True - source = self._content_for(place, name, key, matched, resolve_held) - if source is None: - continue - report, record = source - if place.fold(path) in placed: - return True - placed.add(place.fold(path)) - return _launcher_entry(report, name, path, record, place) - return None - - def _content_for( - self, - place: LauncherPlace, - name: str, - key: str, - matched: list[tuple[_Candidate, dict]], - resolve_held: Callable[[dict], dict | None], - ) -> tuple[dict, dict] | None: - """A held file the core accepts for one launcher name, and its entry. - - The file the database knows under that name comes first when the - core accepts it: by content when the entry pins one, by name and - size when the entry reads it under that name. Otherwise the file the - collection holds for an entry read under that name. - """ - for candidate, report in matched: - if key not in candidate.names: - continue - for record in self.files_named(place, name): - if accepts(candidate.entry, record) or ( - not candidate.by_content - and not _hashes(candidate.entry) - and name_match_size_ok(candidate.entry, record.get("size")) - ): - return report, record - for candidate, report in matched: - if key not in candidate.names or candidate.by_content: - continue - if not report.get("in_repo"): - continue - held = resolve_held(report) - if held is not None: - return report, held - for candidate, report in matched: - if key not in candidate.names or not set_by(candidate.entry, place.passes_to): - continue - for record in catalogued_model_files(name, self._db): - if name_match_size_ok(candidate.entry, record.get("size")): - return report, record - return None - - -def _placeholder_report(key: str, profile: dict, entry: dict) -> dict: - """The report entry of an entry the gap report never builds.""" - identity = { - field: entry[field] - for field in ("aliases", "md5", "sha1", "sha256", "crc32", "size", "min_size", "max_size") - if entry.get(field) is not None - } - return { - **identity, - "profile": key, - "emulator": profile.get("emulator", key), - "name": entry.get("name", ""), - "path": entry.get("path") or entry.get("name", ""), - "system": entry.get("system"), - "systems": profile.get("systems"), - "required": entry.get("required", False), - "category": entry.get("category"), - "in_repo": False, - } - - -def _launcher_entry( - report: dict, name: str, path: str, record: dict, place: LauncherPlace -) -> dict: - """The report entry asking for a file under the name a launcher opens.""" - entry = { - key: report.get(key) - for key in ( - "profile", "emulator", "systems", "system", "region", "selection_slot", - "required", "hle_fallback", "category", - ) - } - entry.update( - name=name, - path=path, - bundled=False, - in_repo=True, - note="", - checks=[], - source_ref=None, - expected={}, - sha1=record.get("sha1"), - md5=record.get("md5"), - launcher=place.source_ref, - launcher_of=report.get("name", ""), - ) - return entry diff --git a/scripts/resolve/layout.py b/scripts/resolve/layout.py index faa43e7c2..5ffeec8d4 100644 --- a/scripts/resolve/layout.py +++ b/scripts/resolve/layout.py @@ -161,7 +161,8 @@ def standalone_bindings_for( ``systems`` are those the entry is launched for (entry_launch_systems). """ - from resolve.launchers import directory_handles, pool_folders, standalone_bindings + from resolve.launcherconfig import directory_handles, pool_folders + from resolve.launchers import standalone_bindings declared = directory_handles(profile) pools = pool_folders(profile) diff --git a/scripts/resolve/standalone.py b/scripts/resolve/standalone.py index ee52c19e0..5362435f1 100644 --- a/scripts/resolve/standalone.py +++ b/scripts/resolve/standalone.py @@ -199,7 +199,7 @@ class _StandaloneLaunches: # The layout folders a search setting stands for (standalone_pools): # bound, the launcher passes the setting and the default is not read. - from resolve.launchers import pool_folders as _pool_folders + from resolve.launcherconfig import pool_folders as _pool_folders pool_folders = {v.strip("/") for v in _pool_folders(profile).values()} - {""} return cls( diff --git a/scripts/sitegen/platformfiles.py b/scripts/sitegen/platformfiles.py index 382ca2a8d..4ca037731 100644 --- a/scripts/sitegen/platformfiles.py +++ b/scripts/sitegen/platformfiles.py @@ -110,8 +110,8 @@ 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 resolve.launchers import record_names as launcher_names - from resolve.launchers import bound_launchers + from resolve.launcherplaces import record_names as launcher_names + from resolve.launcherconfig import bound_launchers from sitegen.sources import launcher_ref_markdown, list_source # Every scraper reads its launchers in the repository and at the revision @@ -140,7 +140,7 @@ def launcher_unproven_section(config: dict) -> list[str]: A config file is proof only when the code installing it and the code reading it are shown: these records place no file. """ - from resolve.launchers import launcher_unproven + from resolve.launcherconfig import launcher_unproven from sitegen.sources import launcher_ref_markdown, list_source rows = launcher_unproven({str(config.get("_key") or ""): config}, _site_profiles()) diff --git a/tests/test_launcher_evidence.py b/tests/test_launcher_evidence.py index fa22d72fb..2387a0382 100644 --- a/tests/test_launcher_evidence.py +++ b/tests/test_launcher_evidence.py @@ -19,14 +19,14 @@ from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from resolve.categories import EntryCategories from resolve.standalone import platform_launches -from resolve.launchers import ( +from resolve.launcherconfig import ( bound_launchers, config_evidence, config_target, - handed_directories, - launcher_places, launcher_unproven, ) +from resolve.launchers import handed_directories +from resolve.launcherplaces import launcher_places from profiling.resolver import _check_build_refs from profiling.repos import shipped_build_holders from scraper.retrobat_launchers import _choices_apart diff --git a/tests/test_launcher_layer.py b/tests/test_launcher_layer.py index 4e273a87f..a72069eb7 100644 --- a/tests/test_launcher_layer.py +++ b/tests/test_launcher_layer.py @@ -24,7 +24,8 @@ import yaml from model.profiles import emulator_profiles_cache, load_emulator_profiles from model.platforms import load_platform_config from resolve.launches import PlatformLaunches -from resolve.launchers import LauncherLayer, launcher_places, suffixed_stem +from resolve.launcherlayer import LauncherLayer +from resolve.launcherplaces import launcher_places, suffixed_stem from packs.gaps import find_undeclared_files from packs.coverage import verify_platform @@ -396,12 +397,12 @@ class LauncherLayerTest(unittest.TestCase): self.assertEqual(launcher_places(self.config, self.profiles)[2].paths, ("sub/sub/fix.bin",)) def test_every_extractor_spelling_of_the_bios_folder_is_known(self) -> None: - from resolve import launchers + from resolve.launcherplaces import BIOS_ROOT_TOKENS from scraper import emudeck_launchers, retrodeck_launchers, retropie_reader for token in (emudeck_launchers.BIOS, retrodeck_launchers.BIOS, retropie_reader.BIOSDIR): - self.assertIn(token, launchers.BIOS_ROOT_TOKENS) + self.assertIn(token, BIOS_ROOT_TOKENS) def test_no_place_is_filled_twice(self) -> None: added = [u["path"] for u in self._report() if u.get("launcher")] diff --git a/tests/test_launcher_placement.py b/tests/test_launcher_placement.py index a9f525f2c..811b616cc 100644 --- a/tests/test_launcher_placement.py +++ b/tests/test_launcher_placement.py @@ -1346,7 +1346,7 @@ class MacBootDisksOnKnulli(unittest.TestCase): # mameGenerator.py and libretroMAMEConfig.py pass the boot disk as # -hard, the brief name of the LC III's one hard disk image # (harddriv.h:43, diimage.cpp:1131-1165, maclc3.cpp:266). - from resolve.launchers import bound_launchers + from resolve.launcherconfig import bound_launchers config = load_platform_config("knulli", str(REPO_ROOT / "platforms")) profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))