diff --git a/schemas/install-manifest.schema.json b/schemas/install-manifest.schema.json index 7ec7a91d3..613c9e86d 100644 --- a/schemas/install-manifest.schema.json +++ b/schemas/install-manifest.schema.json @@ -55,6 +55,10 @@ "description": "Built without game data, absent when the game data is listed", "const": true }, + "slot_fields": { + "description": "The entries a slot decides carry slot, which --one-per-slot reads. Without it the installer refuses --one-per-slot.", + "const": true + }, "platform": { "type": "string", "minLength": 1, @@ -378,6 +382,13 @@ "description": "The rank the code searches the file at, lower first: a world file withdraws an unmatched regional one only when it ranks no worse.", "type": "integer" }, + "truth": { + "description": "false when the list --source truth installs lacks this omission.", + "const": false + }, + "slot": { + "$ref": "#/$defs/slot" + }, "declared_in": { "description": "The platform systems declaring the file, when fewer than `systems`, which also names the systems whose cores read it there.", "type": "array", @@ -443,6 +454,49 @@ "$ref": "#/$defs/file" } }, + "truth_files": { + "description": "Files only the list --source truth installs holds, at their destination with their bytes. With the files not marked truth: false they make that list. Absent on a list built before it, on which --source truth is refused.", + "type": "array", + "items": { + "$ref": "#/$defs/file" + } + }, + "truth_omitted": { + "description": "Omissions only the list --source truth installs holds.", + "type": "array", + "items": { + "type": "object" + } + }, + "standalone_layouts": { + "description": "Per emulator with a standalone build, the files generate_pack.py --emulator --standalone packs, at the destinations that build reads: an entry, or [dest, sha1] when the list carries that content.", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "array", + "prefixItems": [ + { + "type": "string", + "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$" + }, + { + "type": "string", + "pattern": "^[a-f0-9]{40}$" + } + ], + "minItems": 2, + "maxItems": 2 + }, + { + "$ref": "#/$defs/file" + } + ] + } + } + }, "data_directories": { "description": "Data trees the pack carries, rebuilt by the installer from their source archive. Each file is kept only when its sha1 matches.", "type": "array", @@ -657,6 +711,65 @@ } }, "$defs": { + "slot": { + "description": "What --one-per-slot reads: the groups the file competes in, once per time a group lists it, then the keys the slot lookup tries, each with what every emulator declares there.", + "type": "object", + "additionalProperties": false, + "required": [ + "groups", + "keys" + ], + "properties": { + "groups": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "minItems": 1 + }, + "keys": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": [ + "ranks" + ], + "properties": { + "ranks": { + "description": "The priority: of each entry of the emulator at this key, null for one without, lower first.", + "type": "array", + "minItems": 1, + "items": { + "type": [ + "integer", + "null" + ] + } + }, + "regions": { + "type": "array", + "items": { + "type": "string" + } + }, + "sets": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + }, "file": { "type": "object", "additionalProperties": false, @@ -804,6 +917,13 @@ "description": "The rank the code searches the file at, lower first: a world file withdraws an unmatched regional one only when it ranks no worse.", "type": "integer" }, + "truth": { + "description": "false when the list --source truth installs lacks this file at this destination with these bytes.", + "const": false + }, + "slot": { + "$ref": "#/$defs/slot" + }, "alternatives": { "description": "Copies other cores read at this destination when they disagree on its content, in the order the pack builder tries them. A narrowing that drops the entry's cores takes the first whose cores remain.", "type": "array", diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 612af9ae7..214351776 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -775,14 +775,8 @@ def _select_variants( slot_undecidable: list[str] = [] if one_per_slot: - slot_groups = { - sys_id: [(d, n) for d, n in members if d not in region_drops] - for sys_id, members in region_groups.items() - } - slot_drops, slot_undecidable = slot_mod.resolve_slot_drops( - slot_groups, - slot_mod.platform_slot_index(config, emu_profiles or {}, target_cores), - held, + slot_drops, slot_undecidable = _slot_drops( + config, emu_profiles, target_cores, region_groups, region_drops, held ) region_drops = region_drops | slot_drops if slot_undecidable: @@ -794,6 +788,27 @@ def _select_variants( return region_drops, region_fallbacks, slot_undecidable +def _slot_drops( + config: dict, + emu_profiles: dict | None, + target_cores: set[str] | None, + region_groups: dict[str, list[tuple[str, str]]], + region_drops: set[str], + held: set[str], +) -> tuple[set[str], list[str]]: + """What --one-per-slot withdraws once the regions have, and the slots no + declared order decides. The pack and the manifest both read it.""" + slot_groups = { + sys_id: [(d, n) for d, n in members if d not in region_drops] + for sys_id, members in region_groups.items() + } + return slot_mod.resolve_slot_drops( + slot_groups, + slot_mod.platform_slot_index(config, emu_profiles or {}, target_cores), + held, + ) + + def _platform_pack_name( platform_name: str, platforms_dir: str, @@ -4649,12 +4664,14 @@ def _manifest_selection( zip_contents: dict | None = None, data_registry: dict | None = None, slot_overrides: dict[str, str] | None = None, + one_per_slot: bool = False, ) -> tuple[set[str], SelectionIndex, set[str]]: - """Destinations a region list removes, the groups the installer replays, - and the destinations the builder holds. + """Destinations a region list and --one-per-slot remove, the groups the + installer replays, and the destinations the builder holds. - Grouped as the pack groups them, so a region the installer applies to - the full manifest withdraws what `--region` withdraws from the pack. + Grouped as the pack groups them, so a region or a slot the installer + decides on the full manifest withdraws what `--region` and + `--one-per-slot` withdraw from the pack. """ extras: list[dict] = [] held: set[str] = set() @@ -4684,9 +4701,14 @@ def _manifest_selection( if regions else set() ) + if one_per_slot: + drops = drops | _slot_drops( + config, emu_profiles, target_cores, region_groups, drops, held + )[0] return drops, SelectionIndex.build( region_groups, region_index, pack_systems, extras, required_only, extras_prefix=declared_root(config), + slot_claims=slot_mod.platform_slot_claims(config, emu_profiles, target_cores), ), held @@ -4853,6 +4875,8 @@ def generate_manifest( data_registry: dict | None = None, fold_case: bool | None = None, no_game_data: bool = False, + one_per_slot: bool = False, + known_slot_choices: dict | None = None, ) -> dict: """Generate a JSON manifest for a platform (same resolution as generate_pack). @@ -4947,8 +4971,10 @@ def generate_manifest( # The full manifest records every core's answer at a contested slot, so a # target narrowed from it gets what that target's own pack serves. whole = target_cores is None and source != "platform" and bool(emu_profiles) + # The truth list read inside this run takes the choices already made. slot_choices = ( - slots.slot_choices(config, emu_profiles, db, zip_contents, data_registry) + known_slot_choices if known_slot_choices is not None and whole + else slots.slot_choices(config, emu_profiles, db, zip_contents, data_registry) if whole else {} ) # Derived from the same choices: computed twice, it was 8% of a run. @@ -5025,7 +5051,7 @@ def generate_manifest( config, pack_systems, emulators_dir, db, base_dest, emu_profiles, target_cores, source, required_only, regions, undeclared=undeclared, zip_contents=zip_contents, data_registry=data_registry, - slot_overrides=slot_overrides, + slot_overrides=slot_overrides, one_per_slot=one_per_slot, ) # Phase 1: baseline files @@ -5317,6 +5343,9 @@ def generate_manifest( # Every game data file below says so: the installer's --no-game-data # relies on it, and refuses a list that does not record categories. "categorized": True, + # The entries a slot decides carry `slot`, which --one-per-slot + # reads: without this mark the installer refuses it. + "slot_fields": True, **({"no_game_data": True} if no_game_data else {}), "platform": platform_name, "display_name": platform_display, @@ -5394,9 +5423,110 @@ def generate_manifest( ] if variants: result["case_variants"] = variants + if source == "full" and target_cores is None and fold_case is None and not one_per_slot: + with contextlib.redirect_stdout(io.StringIO()): + truth = generate_manifest( + platform_name, platforms_dir, db, bios_dir, registry_path, + emulators_dir, zip_contents, full_profiles, None, "truth", + regions, target_name, offline, required_only, data_registry, + fold_case=None, no_game_data=no_game_data, + known_slot_choices=slot_choices, + ) + _mark_truth(result, truth) + layouts = _standalone_layouts( + manifest_profiles, emulators_dir, db, bios_dir, zip_contents, offline, + platforms_dir, repo_root, result, + ) + if layouts: + result["standalone_layouts"] = layouts return result +def _truth_key(entry: dict) -> tuple: + """What tells one entry from another, as the installer's _entry_key.""" + root = entry.get("root") + cores = tuple(entry.get("cores") or []) if root == "emulator" else () + return (str(entry.get("dest")), root, cores) + + +def _mark_truth(result: dict, truth: dict) -> None: + """What `--source truth` installs, carried in the full list. + + The truth list holds what the emulator profiles prove is read. A file of + the full list it does not hold, by destination and content, is marked + `"truth": false`, and what only the truth list holds is `truth_files`. + Omissions compare by destination. The installer then rebuilds the + truth list from the full one, and a list without `truth_files` is one + published before, on which `--source truth` is refused. + """ + held = {(_truth_key(entry), entry.get("sha1")) for entry in truth["files"]} + full = {(_truth_key(entry), entry.get("sha1")) for entry in result["files"]} + for entry in result["files"]: + if (_truth_key(entry), entry.get("sha1")) not in held: + entry["truth"] = False + result["truth_files"] = [ + entry for entry in truth["files"] + if (_truth_key(entry), entry.get("sha1")) not in full + ] + absent = {_truth_key(entry) for entry in truth["omitted_files"]} + listed = {_truth_key(entry) for entry in result["omitted_files"]} + for entry in result["omitted_files"]: + if _truth_key(entry) not in absent: + entry["truth"] = False + result["truth_omitted"] = [ + entry for entry in truth["omitted_files"] if _truth_key(entry) not in listed + ] + + +def _standalone_layouts( + profiles: dict[str, dict], + emulators_dir: str, + db: dict, + bios_dir: str, + zip_contents: dict, + offline: bool | None, + platforms_dir: str, + repo_root: str, + result: dict, +) -> dict[str, list]: + """Per emulator with a standalone build, the files `--emulator X + --standalone` packs, at the destinations that build reads. + + Built by the emulator pack itself, in memory. A file whose content the + list already carries is written as [dest, sha1], its download read from + that entry. Another is written whole. A data tree member is left to the + list's data directories. + """ + known = { + copy["sha1"] + for entry in [*result["files"], *result.get("truth_files", [])] + for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])] + if copy.get("sha1") and (copy.get("repo_path") or copy.get("release_asset")) + } + layouts: dict[str, list] = {} + for name, profile in sorted(profiles.items()): + if "standalone" not in str(profile.get("type", "")): + continue + record = PackRecord() + with contextlib.redirect_stdout(io.StringIO()), \ + contextlib.redirect_stderr(io.StringIO()): + generate_emulator_pack( + [name], emulators_dir, db, bios_dir, "", standalone=True, + zip_contents=zip_contents, offline=offline, + platforms_dir=platforms_dir, record=record, + ) + items: list = [] + for member in record.files: + entry, _size = _manifest_entry( + record.sources.get(member), member, [name], db, repo_root, {} + ) + if entry is None: + continue + items.append([member, entry["sha1"]] if entry["sha1"] in known else entry) + layouts[name] = items + return layouts + + def tree_readers(pack_systems: dict, core_trees: Iterable[dict]) -> dict[str, list[str]]: """The cores that read each tree, for a tree only cores read. A tree a platform system declares is the system's, whatever core runs it, and diff --git a/scripts/manifestselect.py b/scripts/manifestselect.py index 5093957f1..c7e7284e6 100644 --- a/scripts/manifestselect.py +++ b/scripts/manifestselect.py @@ -18,6 +18,7 @@ from __future__ import annotations from dataclasses import dataclass import region as region_mod +import slot as slot_mod from common import _norm_system_id, sanitize_pack_path from packextras import ( _kept, @@ -41,6 +42,7 @@ class SelectionIndex: systems_by_dest: dict[str, frozenset[str]] declared_by: dict[str, frozenset[str]] extra_groups: dict[str, frozenset[str]] + slots: dict[str, dict] @classmethod def build( @@ -51,6 +53,7 @@ class SelectionIndex: extras: list[dict], required_only: bool = False, extras_prefix: str = "", + slot_claims: dict[str, dict[str, dict]] | None = None, ) -> SelectionIndex: by_norm: dict[str, set[str]] = {} for sys_id in pack_systems: @@ -93,6 +96,7 @@ class SelectionIndex: systems_by_dest, {dest: frozenset(ids) for dest, ids in declared_by.items()}, {dest: frozenset(ids) for dest, ids in extra_groups.items()}, + _slot_fields(region_groups, slot_claims or {}), ) def fields(self, dest: str, name: str) -> dict: @@ -110,6 +114,8 @@ class SelectionIndex: out["systems"] = sorted(systems) if dest not in self.competing: return out + if dest in self.slots: + out["slot"] = self.slots[dest] regions = region_mod.lookup_regions(self.region_index, dest, name) if not regions: return out @@ -126,3 +132,63 @@ class SelectionIndex: if priority is not None: out["priority"] = priority return out + + +def _slot_fields( + region_groups: dict[str, list[tuple[str, str]]], + claims: dict[str, dict[str, dict]], +) -> dict[str, dict]: + """Per destination, the groups it competes in for a slot and the claims + at each key slot.lookup_slot would try. + + Only a group where some emulator ranks a member can drop a file, so + only its members are written, each with all its groups. A key whose + claims equal the previous one's answers the same and is left out. A + destination no emulator claims is never dropped, and carries nothing. + """ + names: dict[str, list[str]] = {} + for members in region_groups.values(): + for dest, name in members: + if name not in names.setdefault(dest, []): + names[dest].append(name) + keyed: dict[str, list[str]] = {} + for dest, found in names.items(): + keys: list[str] = [] + for name in found: + keys += [k for k in slot_mod.slot_lookup_keys(dest, name) + if k in claims and k not in keys] + if keys: + keyed[dest] = keys + + def ranked(dest: str) -> bool: + return any(rank is not None for key in keyed.get(dest, ()) + for claim in claims[key].values() for rank in claim["ranks"]) + + # Each time a group lists the destination: two cores filing one file in + # a group make two candidates of one rank, which no order separates. + groups: dict[str, list[str]] = {} + for group_id, members in region_groups.items(): + for dest, _name in members: + groups.setdefault(dest, []).append(group_id) + # Every group of such a destination: one where it stays keeps it. + written: set[str] = set() + for members in region_groups.values(): + if any(ranked(member) for member, _name in members): + written.update(member for member, _name in members if member in keyed) + fields: dict[str, dict] = {} + for dest in sorted(written): + kept: list[dict] = [] + for key in keyed[dest]: + by_emulator = { + emulator: { + "ranks": claim["ranks"], + **({"regions": sorted(claim["regions"])} if claim["regions"] else {}), + **({"sets": sorted(g for _owner, g in claim["sets"])} + if claim["sets"] else {}), + } + for emulator, claim in sorted(claims[key].items()) + } + if not kept or kept[-1] != by_emulator: + kept.append(by_emulator) + fields[dest] = {"groups": sorted(groups[dest]), "keys": kept} + return fields diff --git a/scripts/slot.py b/scripts/slot.py index f40281e02..3d7b81ff0 100644 --- a/scripts/slot.py +++ b/scripts/slot.py @@ -43,15 +43,31 @@ def platform_slot_index( PlayStation BIOS of RomM, whose cores rank none of them, and `--one-per-slot` dropped four images RomM declares. """ + return { + key: merge_claims(by_emu) + for key, by_emu in platform_slot_claims(config, profiles, target_cores).items() + } + + +def platform_slot_claims( + config: dict, profiles: dict, target_cores: set[str] | None = None +) -> dict[str, dict[str, dict]]: + """What each emulator a platform runs declares at each key, unmerged.""" from common import resolve_platform_cores # noqa: PLC0415 cores = resolve_platform_cores(config, profiles, target_cores=target_cores) - return build_slot_index({n: profiles[n] for n in cores if n in profiles}) + return slot_claims({n: profiles[n] for n in cores if n in profiles}) -def build_slot_index(profiles: dict) -> dict[str, dict]: - """Map a file key to its slot metadata, keyed by path then name.""" - index: dict[str, dict] = {} +def slot_claims(profiles: dict) -> dict[str, dict[str, dict]]: + """Per key (path, standalone path, name), what each emulator declares there. + + Each claim holds the ranks the emulator gives the key in declaration + order, None for an entry without one, the regions, and the set keys. + The install manifest carries these unmerged, so the installer merges + them over the cores a board runs as build_slot_index merges them here. + """ + claims: dict[str, dict[str, dict]] = {} for emu_name, profile in sorted(profiles.items()): if profile.get("type") in ("launcher", "alias"): continue @@ -64,34 +80,49 @@ def build_slot_index(profiles: dict) -> dict[str, dict]: path = f.get("path") or "" # Keyed by the standalone layout too, as build_region_index is. for key in {path, f.get("standalone_path") or "", name} - {""}: - entry = index.setdefault( - key, - {"rank": None, "conflict": False, "regions": set(), - "emulators": [], "ranked_by": set(), "unranked_by": set(), - "sets": set()}, + claim = claims.setdefault(key, {}).setdefault( + emu_name, {"ranks": [], "regions": set(), "sets": set()} ) - entry["regions"] |= {str(r) for r in (f.get("region") or [])} - entry["sets"] |= set(set_keys(emu_name, f)) - rank = f.get("priority") - entry["unranked_by" if rank is None else "ranked_by"].add(emu_name) - if rank is not None: - current = entry["rank"] - if current is not None and current != rank: - entry["conflict"] = True - entry["rank"] = ( - rank if current is None else min(current, rank) - ) - if emu_name not in entry["emulators"]: - entry["emulators"].append(emu_name) - # A core that declares the file without a rank loads it by a rule of its - # own: Genesis Plus GX opens bios_CD_U.bin by name for a US disc, and - # PicoDrive's rank 4 for it would let its rank-3 file replace it. - for entry in index.values(): - if entry["ranked_by"] and entry.pop("unranked_by") - entry["ranked_by"]: - entry["conflict"] = True - entry.pop("unranked_by", None) - entry.pop("ranked_by") - return index + claim["regions"] |= {str(r) for r in (f.get("region") or [])} + claim["sets"] |= set(set_keys(emu_name, f)) + claim["ranks"].append(f.get("priority")) + return claims + + +def merge_claims(by_emulator: dict[str, dict]) -> dict: + """One key's slot metadata, merged over the emulators claiming it. + + Two ranks that differ make the key conflicting. So does an emulator + that declares the key without a rank beside one that ranks it: a core + that declares the file without a rank loads it by a rule of its own. + Genesis Plus GX opens bios_CD_U.bin by name for a US disc, and + PicoDrive's rank 4 for it would let its rank-3 file replace it. + """ + ranks = {r for claim in by_emulator.values() for r in claim["ranks"] if r is not None} + ranked_by = {e for e, claim in by_emulator.items() + if any(r is not None for r in claim["ranks"])} + unranked_by = {e for e, claim in by_emulator.items() if None in claim["ranks"]} + return { + "rank": min(ranks) if ranks else None, + "conflict": len(ranks) > 1 or bool(ranked_by and unranked_by - ranked_by), + "regions": {r for claim in by_emulator.values() for r in claim["regions"]}, + "emulators": sorted(by_emulator), + "sets": {k for claim in by_emulator.values() for k in claim["sets"]}, + } + + +def build_slot_index(profiles: dict) -> dict[str, dict]: + """Map a file key to its slot metadata, keyed by path then name.""" + return {key: merge_claims(by_emu) for key, by_emu in slot_claims(profiles).items()} + + +def slot_lookup_keys(destination: str, name: str) -> list[str]: + """The keys lookup_slot tries, in its order.""" + keys: list[str] = [] + if destination: + parts = destination.split("/") + keys += ["/".join(parts[i:]) for i in range(len(parts))] + return [*keys, name] def lookup_slot(index: dict[str, dict], destination: str, name: str) -> dict | None: