diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 9d06c50d1..e8e2375cc 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -176,15 +176,20 @@ on: - "scripts/sitegen/descriptions.py" - "scripts/sitegen/diagrams.py" - "scripts/sitegen/emulatorcards.py" + - "scripts/sitegen/emulatordata.py" + - "scripts/sitegen/emulatorintro.py" - "scripts/sitegen/emulatormetadata.py" - "scripts/sitegen/emulatorpage.py" - "scripts/sitegen/emulatorsindex.py" - "scripts/sitegen/entries.py" + - "scripts/sitegen/exportrows.py" - "scripts/sitegen/exports.py" - "scripts/sitegen/extraction.py" - "scripts/sitegen/fields.py" - "scripts/sitegen/filebadges.py" + - "scripts/sitegen/gapproblems.py" - "scripts/sitegen/gaps.py" + - "scripts/sitegen/gapsources.py" - "scripts/sitegen/getpages.py" - "scripts/sitegen/guidedata.py" - "scripts/sitegen/guidepage.py" @@ -213,6 +218,7 @@ on: - "scripts/sitegen/render.py" - "scripts/sitegen/runlinks.py" - "scripts/sitegen/runsections.py" + - "scripts/sitegen/sidebartopics.py" - "scripts/sitegen/sources.py" - "scripts/sitegen/starlight.py" - "scripts/sitegen/startwith.py" diff --git a/scripts/sitegen/build.py b/scripts/sitegen/build.py index 946b3cfc5..f2f0894b5 100644 --- a/scripts/sitegen/build.py +++ b/scripts/sitegen/build.py @@ -40,6 +40,7 @@ from sitegen import ( measurements as sitemeasurements, runlinks, runsections, + sidebartopics, starlight as sitestarlight, steps as sitesteps, wanted as sitewanted, @@ -49,8 +50,8 @@ from sitegen.config import GENERATED_DIRS, PUBLIC_DIRS, REPO_URL, yaml from core.paths import REPO_ROOT from sitegen.archivecounts import ARCHIVE_RECIPES_PAGE, with_archive_counts from sitegen.crossref import generate_cross_reference +from sitegen.exportrows import source_commit from sitegen.dataexports import ( - source_commit, generate_data_exports, generate_stats, system_export_item, @@ -70,7 +71,8 @@ from sitegen.emulatorpage import ( ) from sitegen.emulatorsindex import generate_emulators_index from sitegen.exports import generate_exports_page, load_export_reports -from sitegen.gaps import PlatformRegistries, SourceListing, generate_gap_analysis +from sitegen.gaps import PlatformRegistries, generate_gap_analysis +from sitegen.gapsources import SourceListing from sitegen.getpages import generate_get_index, generate_get_page, get_page_data from sitegen.guidepage import DEMO_ASSETS, generate_handheld_guide from sitegen.home import generate_explore_index, generate_home @@ -621,7 +623,7 @@ def _write_navigation(run: _SiteRun, published_parts: dict[str, str]) -> None: generated = site / "src" / "generated" generated.mkdir(parents=True, exist_ok=True) write_if_changed(str(generated / "sidebar.json"), - json.dumps(sitestarlight.sidebar(nav, present, overview_anchors(nav, docs)), + json.dumps(sidebartopics.sidebar(nav, present, overview_anchors(nav, docs)), indent=1) + "\n") write_if_changed(str(generated / "redirects.json"), json.dumps(sitestarlight.redirects(run.profiles, present, published_parts), indent=1, diff --git a/scripts/sitegen/dataexports.py b/scripts/sitegen/dataexports.py index 4ad731695..3c19617cc 100644 --- a/scripts/sitegen/dataexports.py +++ b/scripts/sitegen/dataexports.py @@ -3,31 +3,22 @@ from __future__ import annotations import csv -import functools import io import json import os import shutil import sqlite3 -import sys -from collections.abc import Callable from pathlib import Path from core.artifacts import build_timestamp from core.artifacts import json_text as _json_text from core.hashing import file_digest from model import retired as model_retired -from model.database import sha1_at -from model.platforms import ENTRY_TAGS, registry_fields -from model.profiles import is_emulator from packs.consumers import FileConsumers from sitegen.apiitems import core_index_items, system_index_items -from sitegen.config import DATA_LICENSE, REPO_URL, build_commit +from sitegen.config import DATA_LICENSE, REPO_URL from core.paths import REPO_ROOT -from sitegen.install import release_pack_platforms from sitegen.lookup import ( - HASH_ALGORITHMS, - hash_pairs, data_directory_members, file_location_items, file_lookup_records, @@ -37,50 +28,23 @@ from sitegen.provenance import WantedDumps from sitegen.publish import publish_manifests from sitegen.structured import write_platform_dats, collection_dat from sitegen.write import record_written, write_if_changed +from sitegen.exportrows import ( + ENTRY_EXPORT_FIELDS, + WANTED_FIELDS, + accepted_hash_rows, + cross_reference_export_rows, + emulator_export_items, + gap_export_rows, + platform_export_rows, + provenance_wanted_rows, + source_commit, +) def generate_stats(stats: dict) -> str: return json.dumps(stats, indent=2) + "\n" -def _accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict]) -> list[dict]: - """One row per accepted hash value, for both layers, lookup-ready.""" - rows: list[dict] = [] - for row in platform_files: - # A table row keeps the field as declared under _raw. - declared = {algo: row.get(f"{algo}_raw", row.get(algo)) for algo in HASH_ALGORITHMS} - rows.extend({ - "layer": "platform", "owner": row["platform_id"], - "system": row["system"], "name": row["name"], - "path": row["destination"], "algorithm": algorithm, "value": value, - } for algorithm, value in hash_pairs(declared)) - for item in emulator_items: - for entry in item["profile"].get("files", []) or []: - if not isinstance(entry, dict): - continue - rows.extend({ - "layer": "emulator", "owner": item["id"], - "system": _json_text(entry.get("system")), - "name": entry.get("name", ""), "path": entry.get("path", "") or "", - "algorithm": algorithm, "value": value, - } for algorithm, value in hash_pairs(entry)) - # Members of an archive: MAME and FBNeo hash the ROMs inside the - # set, never the set. Left out, a loose nmk004.bin (crc32 - # 83b6f611) found no row while the site search found it. - archive = entry.get("name", "") - for member in entry.get("contents") or []: - if not isinstance(member, dict) or not member.get("name"): - continue - rows.extend({ - "layer": "emulator", "owner": item["id"], - "system": _json_text(entry.get("system")), - "name": str(member["name"]), "path": f"{archive}/{member['name']}", - "algorithm": algorithm, "value": value, - } for algorithm, value in hash_pairs(member)) - rows.sort(key=lambda r: (r["layer"], r["owner"], r["name"], r["algorithm"], r["value"])) - return rows - - def _csv_document(fieldnames: list[str], rows: list[dict]) -> str: stream = io.StringIO(newline="") writer = csv.DictWriter( @@ -91,272 +55,6 @@ def _csv_document(fieldnames: list[str], rows: list[dict]) -> str: return stream.getvalue() -def _verify_outcomes( - coverage: dict, db: dict -) -> Callable[[str, str], dict]: - """For each declared entry, in declaration order: what verify found. - - Returns a function of (system, name) giving the next outcome for that - pair: status, category, the collection path that answers the entry and - that file's sha1. The CSV gave the declaration and nothing about it. - """ - details: dict[tuple[str, str], list[dict]] = {} - for detail in coverage.get("details") or []: - details.setdefault((detail.get("system", ""), detail.get("name", "")), []).append(detail) - taken: dict[tuple[str, str], int] = {} - - def outcome(system: str, name: str) -> dict: - found = details.get((system, name)) or [{}] - nth = taken.get((system, name), 0) - taken[(system, name)] = nth + 1 - detail = found[min(nth, len(found) - 1)] - path = str(detail.get("path") or "") if detail.get("status") != "missing" else "" - return { - "status": detail.get("status", ""), - "category": detail.get("category", ""), - "collection_path": path, - "resolved_sha1": sha1_at(db, path) or "", - } - return outcome - - -@functools.lru_cache(maxsize=1) -def _contract_keys() -> frozenset[str]: - """The top-level keys platform.schema.json allows in a platform's list.""" - schema = json.loads((REPO_ROOT / "schemas" / "platform.schema.json").read_text(encoding="utf-8")) - return frozenset(schema.get("properties") or {}) - - -def _split_contract(config: dict) -> tuple[dict, dict]: - """The list, valid against platform.schema.json, and the registry entry. - - load_platform_config merges the registry into the list: `install`, - `logo`, `scraper` and `_key` made all 18 contracts fail the published - schema. They stay published, beside the contract. - """ - allowed = _contract_keys() - contract = {key: value for key, value in config.items() if key in allowed} - if isinstance(contract.get("systems"), dict): - contract["systems"] = { - sys_id: { - **system, - "files": [ - { - k: v - for k, v in f.items() - if k not in ENTRY_TAGS - } - for f in system["files"] - ], - } - if isinstance(system, dict) and system.get("files") - else system - for sys_id, system in contract["systems"].items() - } - registry = {key: value for key, value in registry_fields(config).items() - if key not in allowed} - # The merged config gives a child its parent's release_pack: Lakka and - # RetroPie said true in the API while every page said they had no ZIP. - # The registry's own entry decides, as it does for the pages. - released = config.get("_key") in release_pack_platforms() - if released or "release_pack" in registry: - registry["release_pack"] = released - return contract, registry - - -# Per-entry fields a folder check needs beyond the hashes: an md5 is a ZIP -# member's when zipped_file is set, and a CSV without it judged 106 good -# Batocera files wrong. -ENTRY_EXPORT_FIELDS = ( - "zipped_file", "hash_match_mandatory", "mandatory_declared", "curated", - "shared_group", "mirror_of", "zip_digest", -) - - -def _platform_export_rows( - coverages: dict, db: dict | None = None, -) -> tuple[list[dict], list[dict]]: - """Normalized platform summaries and one row per declared file.""" - items: list[dict] = [] - file_rows: list[dict] = [] - for key, coverage in sorted(coverages.items()): - config = coverage["config"] - outcome = _verify_outcomes(coverage, db or {}) - contract, registry = _split_contract(config) - items.append({ - "id": key, - "name": coverage["platform"], - "coverage": { - field: coverage.get(field, 0) - for field in ( - "total", "present", "verified", "untested", "missing", - "core_present", "core_missing", "core_unplaced", "core_unsourceable", - ) - }, - "contract": contract, - "registry": registry, - }) - for system_id, system in sorted(config.get("systems", {}).items()): - file_rows.extend({ - "platform_id": key, - "platform": coverage["platform"], - "system": system_id, - "name": entry.get("name", ""), - "destination": entry.get( - "destination", entry.get("dest", entry.get("name", "")) - ), - "required": bool(entry.get("required", True)), - "region": _json_text(entry.get("region")), - "selection_slot": _json_text(entry.get("selection_slot")), - "size": entry.get("size"), - "sha1": _json_text(entry.get("sha1")), - "sha256": _json_text(entry.get("sha256")), - "md5": _json_text(entry.get("md5")), - "crc32": _json_text(entry.get("crc32")), - **{field: _export_flag(entry.get(field)) for field in ENTRY_EXPORT_FIELDS}, - **outcome(system_id, entry.get("name", "")), - } for entry in system.get("files", []) or []) - return items, file_rows - - -def _export_flag(value: object) -> object: - """A per-entry field as CSV and SQLite hold it: booleans stay booleans, - an absent field is empty.""" - if value is None: - return "" - return value if isinstance(value, bool) else str(value) - - -def _emulator_export_items(profiles: dict) -> list[dict]: - return [ - {"id": key, "profile": profile} - for key, profile in sorted(profiles.items()) - ] - - -def _gap_export_rows( - coverages: dict, gap_report: dict | None = None, db: dict | None = None, -) -> list[dict]: - """Every gap the site reports, both layers, in one table. - - ``platform`` rows are anomalies against a platform's own BIOS list. - ``emulator`` rows are files a profiled core loads that no platform - declares, which is the larger number the gap analysis page leads with. - A `layer` column keeps the two apart instead of publishing only one. - """ - rows: list[dict] = [] - db = db or {} - for key, coverage in sorted(coverages.items()): - for detail in coverage.get("details", []): - if detail.get("status") == "ok" and not detail.get("discrepancy"): - continue - path = str(detail.get("path") or "") if detail.get("status") != "missing" else "" - rows.append({ - "category": detail.get("category", "bios"), - "collection_path": path, - "resolved_sha1": sha1_at(db, path) or "", - "layer": "platform", - "platform_id": key, - "platform": coverage["platform"], - "emulator": "", - "system": detail.get("system", ""), - "name": detail.get("name", ""), - "status": detail.get("status", ""), - "required": bool(detail.get("required", True)), - "in_repo": "", - "reason": detail.get("reason", ""), - "discrepancy": detail.get("discrepancy", ""), - "destination": detail.get("destination", ""), - "expected": "", - }) - for emu_key, data in sorted((gap_report or {}).items()): - systems = ";".join(str(s) for s in data.get("systems", []) or []) - # The category travels on the row: its path is the destination the - # running build reads, not the profile's, and a join on it left 940 - # rows without one. - rows.extend({ - "category": gap.get("category", ""), - "collection_path": "", - "resolved_sha1": "", - "layer": "emulator", - "platform_id": "", - "platform": "", - "emulator": data.get("emulator", emu_key), - "system": systems, - "name": gap.get("name", ""), - # A file the emulator's own package installs is not one to - # find: its own status, as unsourceable has. - "status": ( - "bundled" if gap.get("bundled") and gap.get("source") == "missing" - else gap.get("source", "") - ), - "required": bool(gap.get("required", False)), - "in_repo": bool(gap.get("in_repo", False)), - "reason": gap.get("note", ""), - "discrepancy": "", - # What a contributor needs to supply the right revision and - # put it in the right place: the gaps table gave neither. - "destination": gap.get("path") or gap.get("name", ""), - "expected": gap.get("identity", ""), - } for gap in data.get("gap_details", []) or []) - rows.extend({ - "category": entry.get("category", ""), - "collection_path": "", - "resolved_sha1": "", - "layer": "emulator", - "platform_id": "", - "platform": "", - "emulator": data.get("emulator", emu_key), - "system": systems, - "name": entry.get("name", ""), - "status": "unsourceable", - "required": bool(entry.get("required", False)), - "in_repo": False, - "reason": entry.get("reason", ""), - "discrepancy": "", - "destination": entry.get("path") or entry.get("name", ""), - "expected": "", - } for entry in data.get("unsourceable", []) or []) - # Two declarations that differ only in what the row does not carry are - # one row: AmberELEC's hardwareconfig.xml was printed twice. - unique: dict[tuple, dict] = {} - for row in rows: - unique.setdefault(tuple(sorted((k, str(v)) for k, v in row.items())), row) - return list(unique.values()) - - -def _cross_reference_export_rows(coverages: dict, profiles: dict) -> list[dict]: - from resolve.cores import resolve_platform_cores - - unique = { - key: value - for key, value in profiles.items() - if is_emulator(value) - } - rows: list[dict] = [] - for platform_id, coverage in sorted(coverages.items()): - for profile_id in sorted(resolve_platform_cores(coverage["config"], unique)): - profile = unique[profile_id] - cores = profile.get("cores") or [profile_id] - systems = profile.get("systems") or [""] - for core in cores: - rows.extend({ - "platform_id": platform_id, - "platform": coverage["platform"], - "profile_id": profile_id, - "emulator": profile.get("emulator", profile_id), - "core": core, - "system": system, - "classification": profile.get("core_classification", ""), - "type": profile.get("type", ""), - "source": _json_text(profile.get("source")), - "upstream": _json_text(profile.get("upstream")), - "profiled_commit": _json_text(profile.get("source_commit", "")), - "file_count": len(profile.get("files", []) or []), - } for system in systems) - return rows - - def _write_sqlite_export( destination: Path, db: dict, @@ -523,7 +221,7 @@ def _write_sqlite_export( connection.executemany( "INSERT INTO accepted_hashes VALUES " "(:layer, :owner, :system, :name, :path, :algorithm, :value)", - _accepted_hash_rows(platform_files, emulator_items), + accepted_hash_rows(platform_files, emulator_items), ) connection.executemany( "INSERT INTO gaps VALUES " @@ -571,36 +269,6 @@ def system_export_item(slug: str, manufacturer: str, consoles: dict[str, list]) } -@functools.lru_cache(maxsize=1) -def source_commit() -> str: - """build_commit, empty outside a checkout: the exports then name no commit.""" - import subprocess - - try: - return build_commit() - except (OSError, subprocess.CalledProcessError, ValueError) as error: - print(f" no commit recorded in the exports: {error}", file=sys.stderr) - return "" - - -# One row per dump a catalog describes and the collection lacks: the list -# the provenance page publishes under "Wanted". -WANTED_FIELDS = ("catalog", "dat", "name", "description", "size", "crc32", "md5", "sha1") - - -def _provenance_wanted_rows(dumps: WantedDumps | None) -> list[dict]: - """The Wanted list of the provenance page, as rows.""" - rows: list[dict] = [] - for catalog, data in (dumps.wanted if dumps else {}).items(): - for entry in data["missing"]: - rows.extend({ - "catalog": catalog, "dat": dat, - **{f: _json_text(entry.get(f)) for f in WANTED_FIELDS[2:]}, - } for dat in entry.get("dats") or [entry.get("dat", "")]) - rows.sort(key=lambda r: (r["catalog"], r["dat"], r["name"], r["sha1"])) - return rows - - def generate_data_exports( docs: Path, db: dict, @@ -626,14 +294,14 @@ def generate_data_exports( # could not tell which commit each came from. commit = source_commit() stamp = {"commit": commit} if commit else {} - platform_items, platform_files = _platform_export_rows(coverages, db) - emulator_items = _emulator_export_items(profiles) - gap_rows = _gap_export_rows(coverages, gap_report, db) - cross_rows = _cross_reference_export_rows(coverages, profiles) + platform_items, platform_files = platform_export_rows(coverages, db) + emulator_items = emulator_export_items(profiles) + gap_rows = gap_export_rows(coverages, gap_report, db) + cross_rows = cross_reference_export_rows(coverages, profiles) members = data_directory_members() locations = file_location_items(db, profiles, members) - wanted = _provenance_wanted_rows(dumps) + wanted = provenance_wanted_rows(dumps) envelopes = { "platforms.json": ("platforms", platform_items), "emulators.json": ("emulators", emulator_items), @@ -751,7 +419,7 @@ def generate_data_exports( str(downloads / "accepted-hashes.csv"), _csv_document( ["layer", "owner", "system", "name", "path", "algorithm", "value"], - _accepted_hash_rows(platform_files, emulator_items), + accepted_hash_rows(platform_files, emulator_items), ), ) _write_sqlite_export( diff --git a/scripts/sitegen/emulatordata.py b/scripts/sitegen/emulatordata.py new file mode 100644 index 000000000..75a61c945 --- /dev/null +++ b/scripts/sitegen/emulatordata.py @@ -0,0 +1,133 @@ +"""An emulator page's data directories and the pages their file lists go to.""" + +from __future__ import annotations + +from core.sizes import size_text +from core.text import series +from sitegen import markup +from sitegen.config import date_line, yaml +from sitegen.fields import search_excluded +from sitegen.lookup import data_directory_origin, data_tree_pages +from sitegen.pageregistry import PageRegistry +from sitegen.parts import part_front_matter +from sitegen.render import card_anchor, code_span, count_text, escape_tags +from sitegen.sources import source_ref_markdown + + +def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[str]) -> list[str]: + """A data directory's files with their size and sha1, each sha1 an + anchor the first time the page lists it (``anchors``, the page's ids).""" + table = ["| File | Size | SHA1 |", "|------|-----:|------|"] + for member in names: + info = members[member] + sha1 = str(info.get("sha1", "")) + # One id per page: two members can hold the same bytes (every empty + # file), and Dolphin's trees share Sys. + anchor = card_anchor(sha1) + span = "" if anchor in anchors else f'' + anchors.add(anchor) + table.append(f"| {span}{code_span(member)} | {size_text(int(info.get('size', 0)))} | {code_span(sha1)} |") + return table + + +def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]], + index: int, registry: PageRegistry) -> str: + """One page of a large data directory's file list.""" + stem, names = pages[index] + members = registry.data_members.get(ref) or {} + part = f" (part {index + 1} of {len(pages)})" if len(pages) > 1 else "" + read_by = series([f"[{escape_tags(display)}]({key}.md#data-directories)" + for key, display in registry.data_readers.get(ref, [])]) + # A file list out of the search: "dolphin" found three parts of the + # dolphin-sys tree, on their title, before the Dolphin page. + front: dict = {"level": "reference", "search": "exclude"} + # The reader the tree is named after (dolphin for dolphin-sys), else + # the first by name. + readers = registry.data_readers.get(ref) or [] + owner = max(readers, default=None, + key=lambda reader: len(reader[0]) if ref.startswith(f"{reader[0]}-") else 0) + if owner: + head = part_front_matter( + (owner[1], f"{owner[0]}.md"), + [(f"The {ref} data directory, part {n}", f"{other}.md") + for n, (other, _names) in enumerate(pages, 1)], index, front) + else: + head = ["---", yaml.safe_dump(front, sort_keys=False, allow_unicode=True).rstrip("\n"), + "---", ""] + lines = [ + *head, + f"# The {ref} data directory{part}", "", + f"{entry.get('description') or 'A data directory'}: " + f"{count_text(len(members), 'file')}, as the packs ship them." + + (f" Read by {read_by}." if read_by else ""), "", + ] + if len(pages) > 1: + lines.extend([", ".join(f"[part {i}]({other}.md)" if other != stem else f"part {i}" + for i, (other, _names) in enumerate(pages, 1)), ""]) + lines.extend(search_excluded(_data_member_table(members, names, set()))) + lines.extend(["", date_line()]) + return "\n".join(lines) + "\n" + + +def _data_directory_lines( + dd: dict, profile: dict, data_registry: dict | None, member_anchors: set[str], + registry: PageRegistry, +) -> tuple[list[str], dict[str, str]]: + """One data directory: what it holds, where it comes from, which build + reads it, and the pages its member list went to.""" + lines: list[str] = [] + part_pages: dict[str, str] = {} + ref = dd.get("ref", "") + dest = dd.get("destination", "") + entry = (data_registry or {}).get(ref, {}) + # An empty destination wrote "``", which opened a code span + # running to the next one and hid a link from the MDX pass. + line = f"- `{ref}` > `{dest}`" if dest else f"- `{ref}`" + if entry.get("description"): + line += f": {entry['description']}" + lines.append(line) + lines.extend(f" - {line}" for line in data_directory_origin( + entry, registry.data_revisions.get(ref) or {})) + if dd.get("mode"): + lines.append(f" - Read by the {dd['mode']} build only") + if dd.get("bundled"): + lines.append(" - Installed with the emulator, so packs leave it out") + if dd.get("source_ref"): + lines.append(f" - Source: {source_ref_markdown(profile, dd['source_ref'])}") + members = registry.data_members.get(ref) or {} + tree_pages = data_tree_pages(ref, members) + if tree_pages: + where = (f"[a page of their own]({tree_pages[0][0]}.md)" if len(tree_pages) == 1 + else "pages of their own: " + ", ".join( + f"[part {i}]({stem}.md)" for i, (stem, _names) in enumerate(tree_pages, 1))) + lines.append(f" - {count_text(len(members), 'file')}, listed on {where}") + for index, (stem, _names) in enumerate(tree_pages): + part_pages[stem] = _data_tree_page(ref, entry, tree_pages, index, registry) + elif members: + table = _data_member_table(members, sorted(members), member_anchors) + lines.append("") + lines.extend(markup.details( + "info", f"{count_text(len(members), 'file')}, as the packs ship them", + table, indent=" ")) + return lines, part_pages + + +def data_directories_section( + profile: dict, data_dirs: list[dict], data_registry: dict | None, registry: PageRegistry, +) -> tuple[list[str], dict[str, str]]: + """The Data directories section, and the pages its member lists went to.""" + # The member tables are a file list with hashes: out of the search, + # dolphin, primehack and ishiiruka each put 210 KB of it there. + trees: list[str] = [] + part_pages: dict[str, str] = {} + member_anchors: set[str] = set() + # Each tree with what it holds, where it comes from, which build reads + # it and the code that does: these trees put thousands of files in + # the packs, and the page said only `dolphin-sys` > `Sys`. + for dd in data_dirs: + lines, pages = _data_directory_lines(dd, profile, data_registry, member_anchors, registry) + trees.extend(lines) + part_pages.update(pages) + trees.append("") + # The member tables are the lookup's. + return ["## Data directories", "", *search_excluded(trees)], part_pages diff --git a/scripts/sitegen/emulatorintro.py b/scripts/sitegen/emulatorintro.py new file mode 100644 index 000000000..986a98aab --- /dev/null +++ b/scripts/sitegen/emulatorintro.py @@ -0,0 +1,285 @@ +"""The opening of an emulator page: what it needs, by region or under any name, and what the collection holds.""" + +from __future__ import annotations + +from collections.abc import Callable + +from core.text import series +from sitegen.emulatorcards import any_name_bios, named_example, named_system_link +from sitegen.filebadges import region_words +from sitegen.install import comes_with_app, data_folder_block, standalone_place +from sitegen.render import code_span, count_text +from sitegen.runsections import system_name + + +def _emulator_slots(files: list[dict]) -> list[list[dict]]: + """The entries of each slot, as verify --emulator and the gaps page + count them, leaving out the slots the app ships.""" + from packs.crossref import slot_key + + slots: dict[tuple, list[dict]] = {} + for f in files: + slots.setdefault(slot_key(f), []).append(f) + return [group for group in slots.values() if not all(comes_with_app(f) for f in group)] + + +def _set_names(value: object) -> list[str]: + """The sets an entry belongs to: group takes a name, a list or a map.""" + if isinstance(value, str): + return [value] + if isinstance(value, (list, dict)): + return [str(name) for name in value] + return [] + + +def _requirements(files: list[dict], groups: dict | None) -> list[list[dict]]: + """Each thing the emulator needs: the members of a required set, any one + of which fills it (DuckStation's ps-bios, 105 images), or a required + file of its own. load_emulator_profiles marks every member of a + required set required, so counted per file DuckStation read "105 + required" for one BIOS.""" + required_sets = {name for name, spec in (groups or {}).items() + if isinstance(spec, dict) and spec.get("required")} + sets: dict[str, list[dict]] = {} + alone: list[list[dict]] = [] + for f in files: + if f.get("required") is not True or comes_with_app(f): + continue + names = [name for name in _set_names(f.get("group")) if name in required_sets] + if names: + for name in names: + sets.setdefault(name, []).append(f) + else: + alone.append([f]) + return [*sets.values(), *alone] + + +def _regional_set(requirements: list[list[dict]]) -> list[dict]: + """The one requirement, a set whose members the code picks by the game's + region, or [] when there is no such single choice.""" + if len(requirements) != 1 or len(requirements[0]) < 2: + return [] + members = requirements[0] + if not all(f.get("region") for f in members): + return [] + return members if len({region_words(f["region"]) for f in members}) >= 2 else [] + + +def emulator_file_summary(files: list[dict], groups: dict | None = None) -> list[str]: + """What the emulator reads, above its file table, and its categories. + + Counted by slot, as verify --emulator and the gaps page count: raze + lists every GRP its code accepts under one name, and holding one fills + the slot. Counted per entry, the page announced 46 missing where 12 + slots are empty. The files the app ships are counted apart: NetherSX2 + said "4 required" for one BIOS and three fonts in its package. A + required set counts once (`groups`). + """ + slots = _emulator_slots(files) + shipped = sum(1 for f in files if comes_with_app(f)) + requirements = _requirements(files, groups) + in_sets = {id(f) for members in requirements for f in members} + req_slots = sum(1 for group in slots if any(id(f) in in_sets for f in group)) + req_count = len(requirements) + optional = len(slots) - req_slots + hle_count = sum(1 for group in slots if any(f.get("hle_fallback") for f in group)) + + # Sentences, one number format: the line read "1,563 files | 164 + # required, 1399 optional | 1563 in repo". + total = f"**{count_text(len(slots), 'file')}**" + if sum(len(group) for group in slots) != len(slots): + total += f" ({sum(len(group) for group in slots):,} accepted versions)" + line = f"{total}: {req_count:,} required, {optional:,} optional." + if any(len(members) > 1 for members in requirements): + line += " Any one file of a required set fills it." + regional = _regional_set(requirements) or ( + [f for members in requirements for f in members] + if _regional_choice([f for members in requirements for f in members]) else []) + if regional: + # DuckStation takes the BIOS of the game's region: "3 required" + # read as "get all three". + line = f"{total}. One of {len(regional):,} is required, for the games' region." + if optional: + line += f" {optional:,} {'is' if optional == 1 else 'are'} optional." + if hle_count: + line += f" {hle_count:,} {'has' if hle_count == 1 else 'have'} an HLE fallback." + if shipped: + line += f" {count_text(shipped, 'more file')} {'comes' if shipped == 1 else 'come'} with the app." + lines = [line, ""] + + categories = [f.get("category", "bios") for f in files] + if "game_data" in categories or "bios_zip" in categories: + cats = [ + f"{categories.count(key):,} {label}" + for key, label in ( + ("bios", "BIOS"), ("bios_zip", "BIOS ZIPs"), ("game_data", "game data") + ) + if categories.count(key) + ] + lines.extend([f"By kind: {series(cats)}.", ""]) + return lines + + +def emulator_held_line(files: list[dict], available: Callable[[dict], bool]) -> list[str]: + """What this collection holds of them, one quiet line under the table: + a reader comes for what the emulator needs, the project's counts after.""" + slots = _emulator_slots(files) + if not slots: + return [] + in_repo = sum(1 for group in slots if any(available(f) for f in group)) + unsourceable = sum( + 1 for group in slots + if not any(available(f) for f in group) and all(f.get("unsourceable") for f in group) + ) + held = [f"{in_repo:,} in repo", f"{len(slots) - in_repo - unsourceable:,} missing"] + if unsourceable: + held.append(f"{unsourceable:,} unsourceable") + return [f"

In this collection: {series(held)}.

", ""] + + +def _any_name_folder(profile: dict, entry: dict) -> str: + """Where the one BIOS goes, as the profile states it, or "".""" + folder = str(profile.get("bios_directory") or "") + if not folder: + path = str(entry.get("path") or "") + folder = path.rsplit("/", 1)[0] + "/" if "/" in path else "" + if not folder: + return "" + if profile.get("type") == "standalone": + # A bare `bios/` is a folder inside the app's own data folder. + own = ("[the app's data folder](#data-folder)" if profile.get("data_root") + else "the app's own data folder") + return f"the {code_span(folder.strip('/'))} folder inside {own}" + return f"{code_span(folder)}, inside the BIOS folder" + + +def _any_name_steps(emu_name: str, profile: dict, entry: dict, href: str, + name: str = "") -> str: + """The intro of an emulator that takes one BIOS of any name: get one, + put it in its folder, any name works. + + An app whose profile names its data folder gets that folder, one tab + per system it runs on: AetherSX2's step said "inside the app's own + data folder" while the profile cites Android/data/xyz.aethersx2.android. + """ + system = system_name((profile.get("systems") or [""])[0]) + example = str(entry.get("name") or "") + if named_example(example) and href: + get = f"Download [{code_span(example)}]({href})." + else: + get = f"Get one from the {named_system_link(profile['systems'][0], '../')} files." + steps = [get] + folders: list[str] = [] + if profile.get("type") == "standalone" and standalone_place(profile, entry): + steps.append("Put it in this folder:") + folders = ['
', "", + *data_folder_block(profile, [entry])] + else: + folder = _any_name_folder(profile, entry) + if folder: + steps.append(f"Put it in {folder}.") + folders = _data_folder_intro(name, profile) + reader = "The app" if profile.get("type") == "standalone" else "The emulator" + return "\n".join([ + f"{emu_name} needs one {system} BIOS file, any region.", + "", + *(f"{number}. {step}" for number, step in enumerate(steps, 1)), + "", + *folders, + *([""] if folders and folders[-1] else []), + f"Any file name works. {reader} reads what the file holds.", + ]) + + +def _data_folder_intro(name: str, profile: dict) -> list[str]: + """Where the app keeps its files, under the intro of a profile that + names its data folder and takes more than one BIOS of any name.""" + if not profile.get("data_root"): + return [] + files = [f for f in profile.get("files") or [] if isinstance(f, dict)] + placed = [f for f in files if standalone_place(profile, f)] + subject = ("The app" if profile.get("type") == "standalone" + else "Run on its own, the app") + lead = (f"{subject} reads its files from this folder:" if placed + else f"{subject} keeps its data in this folder:") + return ['
', "", lead, "", + *data_folder_block(profile, files)] + + +def emulator_intro(emu_name: str, profile: dict, href: str = "", name: str = "") -> str: + """What the emulator needs, in plain words, from fields every profile has. + + The page opened on a twelve-row table: "Type", "Version", "Checked by". + DuckStation needs one PlayStation BIOS of any name, and the reader had + to infer it from the "Files found by" row. ``href`` links the + collection's copy of the one BIOS an emulator takes under any name, + and ``name`` is the profile's key. + """ + entry = any_name_bios(profile) + if entry is not None: + return _any_name_steps(emu_name, profile, entry, href, name) + names: list[str] = [] + for sys_id in profile.get("systems") or []: + label = system_name(sys_id) + if label not in names: + names.append(label) + # What the app installs itself is no file for the reader to get. + files = [f for f in profile.get("files") or [] if isinstance(f, dict) and not comes_with_app(f)] + requirements = _requirements(files, profile.get("groups")) + required = [f for members in requirements for f in members] + sentences = [] + if names: + shown = names if len(names) <= 4 else names[:3] + [f"{len(names) - 3} more systems"] + sentences.append(f"{emu_name} emulates {series(shown)}.") + regional = _regional_set(requirements) + by_region = "" if regional else _regional_choice(required) + others = len(files) - len(required) + if regional: + # DuckStation needs one BIOS of the game's region and accepts 105 + # images: every member of its ps-bios set is marked required, and + # the page said "105 of them required". + sentences.append( + f"It needs one BIOS for the game's region, among the {len(regional):,} it accepts.") + if others: + sentences.append( + f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.") + elif by_region: + # Three required BIOS of three regions: the page said "3 of them + # required" and read as "get all of these". + sentences.append(f"It picks the BIOS for the game's region: {by_region}.") + if others: + sentences.append( + f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.") + elif files: + sentences.append( + f"It reads {count_text(len(files), 'file')}, {len(requirements):,} of them required: " + "without a required file it does not start games." + if requirements else + f"It reads {count_text(len(files), 'file')}, none of them required: it starts " + "games without them." + ) + if any(len(members) > 1 for members in requirements): + sentences.append("Any one file of a required set fills it.") + if required and len(names) > 1: + sentences.append("A required file is needed only by the machines that use it.") + if profile.get("found_by") == "content": + sentences.append("It recognises a file by its contents, so any file name works.") + if any(f.get("source_ref") for f in files): + sentences.append("Each file below cites the line of source code that reads it.") + folder = _data_folder_intro(name, profile) if name else [] + return "\n".join([" ".join(sentences), "", *folder]).strip("\n") + + +def _regional_choice(required: list[dict], most: int = 6) -> str: + """The required files as one choice by region, or "" when they are not one. + + Only when every required entry carries a region: and they name at least + two: region: is the territory the code selects the file for, so the + reader needs the one of the game's region. + """ + if not required or len(required) > most or not all(f.get("region") for f in required): + return "" + if len({region_words(f["region"]) for f in required}) < 2: + return "" + choices = [f"{f.get('name', '')} ({region_words(f['region'], 3)})" for f in required] + return series(choices, "or") diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py index 938eafd36..68d17d5a8 100644 --- a/scripts/sitegen/emulatorpage.py +++ b/scripts/sitegen/emulatorpage.py @@ -9,22 +9,18 @@ from collections.abc import Callable, Sequence from dataclasses import dataclass from core.hashing import parse_hash_list -from core.sizes import size_text from sitegen.runsections import system_name from model.profiles import is_emulator from packs.consumers import FileConsumers from packs.supplemental import SupplementalIndex from sitegen import entries as siteentries, markup, measurements as sitemeasurements from sitegen.cards import ROMSET_FAQ, emulator_file_anchors -from sitegen.config import REPO_URL, date_line, yaml -from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT -from core.text import series +from sitegen.config import REPO_URL, date_line from sitegen.emulatorcards import ( CardLayout, CardSources, build_rows, entry_label, - named_example, named_system_link, render_emulator_file, any_name_bios, @@ -32,23 +28,22 @@ from sitegen.emulatorcards import ( from sitegen.filebadges import file_badges, region_words from sitegen.emulatormetadata import render_metadata_rows, emulator_romset, version_markdown from sitegen.emulatorsindex import CLS_LABEL_ONE -from sitegen.fields import render_platform_details, render_structured_blocks, search_excluded +from sitegen.fields import render_platform_details, render_structured_blocks from sitegen.home import next_block from sitegen.install import ( install_block, platform_display, comes_with_app, - data_folder_block, data_root_words, - standalone_place, ) -from sitegen.lookup import data_directory_origin, data_tree_pages from sitegen.pageregistry import PageRegistry from sitegen.render import admonition_body, card_anchor, code_span, count_text, escape_tags from sitegen.runlinks import card_page, record_emulator_cards -from sitegen.sources import source_ref_markdown, link_prose_citations, revision_markdown -from sitegen.parts import even_runs, weighted_runs +from sitegen.sources import link_prose_citations, revision_markdown +from sitegen.parts import even_runs, part_front_matter, weighted_runs from sitegen.structured import emulator_file_aliases +from sitegen.emulatordata import data_directories_section +from sitegen.emulatorintro import emulator_file_summary, emulator_held_line, emulator_intro def _distinct_spellings(names: list) -> list[str]: @@ -88,186 +83,6 @@ def availability_check( return _file_available -def _emulator_slots(files: list[dict]) -> list[list[dict]]: - """The entries of each slot, as verify --emulator and the gaps page - count them, leaving out the slots the app ships.""" - from packs.crossref import slot_key - - slots: dict[tuple, list[dict]] = {} - for f in files: - slots.setdefault(slot_key(f), []).append(f) - return [group for group in slots.values() if not all(comes_with_app(f) for f in group)] - - -def _set_names(value: object) -> list[str]: - """The sets an entry belongs to: group takes a name, a list or a map.""" - if isinstance(value, str): - return [value] - if isinstance(value, (list, dict)): - return [str(name) for name in value] - return [] - - -def _requirements(files: list[dict], groups: dict | None) -> list[list[dict]]: - """Each thing the emulator needs: the members of a required set, any one - of which fills it (DuckStation's ps-bios, 105 images), or a required - file of its own. load_emulator_profiles marks every member of a - required set required, so counted per file DuckStation read "105 - required" for one BIOS.""" - required_sets = {name for name, spec in (groups or {}).items() - if isinstance(spec, dict) and spec.get("required")} - sets: dict[str, list[dict]] = {} - alone: list[list[dict]] = [] - for f in files: - if f.get("required") is not True or comes_with_app(f): - continue - names = [name for name in _set_names(f.get("group")) if name in required_sets] - if names: - for name in names: - sets.setdefault(name, []).append(f) - else: - alone.append([f]) - return [*sets.values(), *alone] - - -def _regional_set(requirements: list[list[dict]]) -> list[dict]: - """The one requirement, a set whose members the code picks by the game's - region, or [] when there is no such single choice.""" - if len(requirements) != 1 or len(requirements[0]) < 2: - return [] - members = requirements[0] - if not all(f.get("region") for f in members): - return [] - return members if len({region_words(f["region"]) for f in members}) >= 2 else [] - - -def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> list[str]: - """What the emulator reads, above its file table, and its categories. - - Counted by slot, as verify --emulator and the gaps page count: raze - lists every GRP its code accepts under one name, and holding one fills - the slot. Counted per entry, the page announced 46 missing where 12 - slots are empty. The files the app ships are counted apart: NetherSX2 - said "4 required" for one BIOS and three fonts in its package. A - required set counts once (`groups`). - """ - slots = _emulator_slots(files) - shipped = sum(1 for f in files if comes_with_app(f)) - requirements = _requirements(files, groups) - in_sets = {id(f) for members in requirements for f in members} - req_slots = sum(1 for group in slots if any(id(f) in in_sets for f in group)) - req_count = len(requirements) - optional = len(slots) - req_slots - hle_count = sum(1 for group in slots if any(f.get("hle_fallback") for f in group)) - - # Sentences, one number format: the line read "1,563 files | 164 - # required, 1399 optional | 1563 in repo". - total = f"**{count_text(len(slots), 'file')}**" - if sum(len(group) for group in slots) != len(slots): - total += f" ({sum(len(group) for group in slots):,} accepted versions)" - line = f"{total}: {req_count:,} required, {optional:,} optional." - if any(len(members) > 1 for members in requirements): - line += " Any one file of a required set fills it." - regional = _regional_set(requirements) or ( - [f for members in requirements for f in members] - if _regional_choice([f for members in requirements for f in members]) else []) - if regional: - # DuckStation takes the BIOS of the game's region: "3 required" - # read as "get all three". - line = f"{total}. One of {len(regional):,} is required, for the games' region." - if optional: - line += f" {optional:,} {'is' if optional == 1 else 'are'} optional." - if hle_count: - line += f" {hle_count:,} {'has' if hle_count == 1 else 'have'} an HLE fallback." - if shipped: - line += f" {count_text(shipped, 'more file')} {'comes' if shipped == 1 else 'come'} with the app." - lines = [line, ""] - - categories = [f.get("category", "bios") for f in files] - if "game_data" in categories or "bios_zip" in categories: - cats = [ - f"{categories.count(key):,} {label}" - for key, label in ( - ("bios", "BIOS"), ("bios_zip", "BIOS ZIPs"), ("game_data", "game data") - ) - if categories.count(key) - ] - lines.extend([f"By kind: {series(cats)}.", ""]) - return lines - - -def _emulator_held_line(files: list[dict], available: Callable[[dict], bool]) -> list[str]: - """What this collection holds of them, one quiet line under the table: - a reader comes for what the emulator needs, the project's counts after.""" - slots = _emulator_slots(files) - if not slots: - return [] - in_repo = sum(1 for group in slots if any(available(f) for f in group)) - unsourceable = sum( - 1 for group in slots - if not any(available(f) for f in group) and all(f.get("unsourceable") for f in group) - ) - held = [f"{in_repo:,} in repo", f"{len(slots) - in_repo - unsourceable:,} missing"] - if unsourceable: - held.append(f"{unsourceable:,} unsourceable") - return [f"

In this collection: {series(held)}.

", ""] - - -def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[str]) -> list[str]: - """A data directory's files with their size and sha1, each sha1 an - anchor the first time the page lists it (``anchors``, the page's ids).""" - table = ["| File | Size | SHA1 |", "|------|-----:|------|"] - for member in names: - info = members[member] - sha1 = str(info.get("sha1", "")) - # One id per page: two members can hold the same bytes (every empty - # file), and Dolphin's trees share Sys. - anchor = card_anchor(sha1) - span = "" if anchor in anchors else f'' - anchors.add(anchor) - table.append(f"| {span}{code_span(member)} | {size_text(int(info.get('size', 0)))} | {code_span(sha1)} |") - return table - - -def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]], - index: int, registry: PageRegistry) -> str: - """One page of a large data directory's file list.""" - stem, names = pages[index] - members = registry.data_members.get(ref) or {} - part = f" (part {index + 1} of {len(pages)})" if len(pages) > 1 else "" - read_by = series([f"[{escape_tags(display)}]({key}.md#data-directories)" - for key, display in registry.data_readers.get(ref, [])]) - # A file list out of the search: "dolphin" found three parts of the - # dolphin-sys tree, on their title, before the Dolphin page. - front: dict = {"level": "reference", "search": "exclude"} - # The reader the tree is named after (dolphin for dolphin-sys), else - # the first by name. - readers = registry.data_readers.get(ref) or [] - owner = max(readers, default=None, - key=lambda reader: len(reader[0]) if ref.startswith(f"{reader[0]}-") else 0) - if owner: - head = _part_front_matter( - (owner[1], f"{owner[0]}.md"), - [(f"The {ref} data directory, part {n}", f"{other}.md") - for n, (other, _names) in enumerate(pages, 1)], index, front) - else: - head = ["---", yaml.safe_dump(front, sort_keys=False, allow_unicode=True).rstrip("\n"), - "---", ""] - lines = [ - *head, - f"# The {ref} data directory{part}", "", - f"{entry.get('description') or 'A data directory'}: " - f"{count_text(len(members), 'file')}, as the packs ship them." - + (f" Read by {read_by}." if read_by else ""), "", - ] - if len(pages) > 1: - lines.extend([", ".join(f"[part {i}]({other}.md)" if other != stem else f"part {i}" - for i, (other, _names) in enumerate(pages, 1)), ""]) - lines.extend(search_excluded(_data_member_table(members, names, set()))) - lines.extend(["", date_line()]) - return "\n".join(lines) + "\n" - - # An emulator page lists at most this many file cards: MAME's 1,564 made a # 3 MB page. Past it, the cards go to pages of their own and the emulator's # page keeps a table of every entry, each row holding the card's old @@ -506,154 +321,6 @@ def _collection_card_href(entry: dict, consumers: FileConsumers | None, owner: s return f"../systems/{urllib.parse.quote(card_page(held, sha1))}.md#{card_anchor(sha1)}" -def _any_name_folder(profile: dict, entry: dict) -> str: - """Where the one BIOS goes, as the profile states it, or "".""" - folder = str(profile.get("bios_directory") or "") - if not folder: - path = str(entry.get("path") or "") - folder = path.rsplit("/", 1)[0] + "/" if "/" in path else "" - if not folder: - return "" - if profile.get("type") == "standalone": - # A bare `bios/` is a folder inside the app's own data folder. - own = ("[the app's data folder](#data-folder)" if profile.get("data_root") - else "the app's own data folder") - return f"the {code_span(folder.strip('/'))} folder inside {own}" - return f"{code_span(folder)}, inside the BIOS folder" - - -def _any_name_steps(emu_name: str, profile: dict, entry: dict, href: str, - name: str = "") -> str: - """The intro of an emulator that takes one BIOS of any name: get one, - put it in its folder, any name works. - - An app whose profile names its data folder gets that folder, one tab - per system it runs on: AetherSX2's step said "inside the app's own - data folder" while the profile cites Android/data/xyz.aethersx2.android. - """ - system = system_name((profile.get("systems") or [""])[0]) - example = str(entry.get("name") or "") - if named_example(example) and href: - get = f"Download [{code_span(example)}]({href})." - else: - get = f"Get one from the {named_system_link(profile['systems'][0], '../')} files." - steps = [get] - folders: list[str] = [] - if profile.get("type") == "standalone" and standalone_place(profile, entry): - steps.append("Put it in this folder:") - folders = ['
', "", - *data_folder_block(profile, [entry])] - else: - folder = _any_name_folder(profile, entry) - if folder: - steps.append(f"Put it in {folder}.") - folders = _data_folder_intro(name, profile) - reader = "The app" if profile.get("type") == "standalone" else "The emulator" - return "\n".join([ - f"{emu_name} needs one {system} BIOS file, any region.", - "", - *(f"{number}. {step}" for number, step in enumerate(steps, 1)), - "", - *folders, - *([""] if folders and folders[-1] else []), - f"Any file name works. {reader} reads what the file holds.", - ]) - - -def _data_folder_intro(name: str, profile: dict) -> list[str]: - """Where the app keeps its files, under the intro of a profile that - names its data folder and takes more than one BIOS of any name.""" - if not profile.get("data_root"): - return [] - files = [f for f in profile.get("files") or [] if isinstance(f, dict)] - placed = [f for f in files if standalone_place(profile, f)] - subject = ("The app" if profile.get("type") == "standalone" - else "Run on its own, the app") - lead = (f"{subject} reads its files from this folder:" if placed - else f"{subject} keeps its data in this folder:") - return ['
', "", lead, "", - *data_folder_block(profile, files)] - - -def _emulator_intro(emu_name: str, profile: dict, href: str = "", name: str = "") -> str: - """What the emulator needs, in plain words, from fields every profile has. - - The page opened on a twelve-row table: "Type", "Version", "Checked by". - DuckStation needs one PlayStation BIOS of any name, and the reader had - to infer it from the "Files found by" row. ``href`` links the - collection's copy of the one BIOS an emulator takes under any name, - and ``name`` is the profile's key. - """ - entry = any_name_bios(profile) - if entry is not None: - return _any_name_steps(emu_name, profile, entry, href, name) - names: list[str] = [] - for sys_id in profile.get("systems") or []: - label = system_name(sys_id) - if label not in names: - names.append(label) - # What the app installs itself is no file for the reader to get. - files = [f for f in profile.get("files") or [] if isinstance(f, dict) and not comes_with_app(f)] - requirements = _requirements(files, profile.get("groups")) - required = [f for members in requirements for f in members] - sentences = [] - if names: - shown = names if len(names) <= 4 else names[:3] + [f"{len(names) - 3} more systems"] - sentences.append(f"{emu_name} emulates {series(shown)}.") - regional = _regional_set(requirements) - by_region = "" if regional else _regional_choice(required) - others = len(files) - len(required) - if regional: - # DuckStation needs one BIOS of the game's region and accepts 105 - # images: every member of its ps-bios set is marked required, and - # the page said "105 of them required". - sentences.append( - f"It needs one BIOS for the game's region, among the {len(regional):,} it accepts.") - if others: - sentences.append( - f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.") - elif by_region: - # Three required BIOS of three regions: the page said "3 of them - # required" and read as "get all of these". - sentences.append(f"It picks the BIOS for the game's region: {by_region}.") - if others: - sentences.append( - f"The {count_text(others, 'other file')} {'is' if others == 1 else 'are'} optional.") - elif files: - sentences.append( - f"It reads {count_text(len(files), 'file')}, {len(requirements):,} of them required: " - "without a required file it does not start games." - if requirements else - f"It reads {count_text(len(files), 'file')}, none of them required: it starts " - "games without them." - ) - if any(len(members) > 1 for members in requirements): - sentences.append("Any one file of a required set fills it.") - if required and len(names) > 1: - sentences.append("A required file is needed only by the machines that use it.") - if profile.get("found_by") == "content": - sentences.append("It recognises a file by its contents, so any file name works.") - if any(f.get("source_ref") for f in files): - sentences.append("Each file below cites the line of source code that reads it.") - folder = _data_folder_intro(name, profile) if name else [] - return "\n".join([" ".join(sentences), "", *folder]).strip("\n") - - -def _regional_choice(required: list[dict], most: int = 6) -> str: - """The required files as one choice by region, or "" when they are not one. - - Only when every required entry carries a region: and they name at least - two: region: is the territory the code selects the file for, so the - reader needs the one of the game's region. - """ - if not required or len(required) > most or not all(f.get("region") for f in required): - return "" - if len({region_words(f["region"]) for f in required}) < 2: - return "" - choices = [f"{f.get('name', '')} ({region_words(f['region'], 3)})" for f in required] - return series(choices, "or") - - def _alias_page(name: str, profile: dict) -> str: """The page of a core that uses another one's firmware.""" parent = profile.get("alias_of", profile.get("bios_identical_to", "unknown")) @@ -775,8 +442,8 @@ def _emulator_files_section( _file_available = availability_check(sources.db, sources.data_names, name) lines.extend(["## Files", ""]) - lines.extend(_emulator_file_summary(files, profile.get("groups"))) - held = _emulator_held_line(files, _file_available) + lines.extend(emulator_file_summary(files, profile.get("groups"))) + held = emulator_held_line(files, _file_available) anchors = emulator_file_anchors(files) aliases = emulator_file_aliases(files, anchors) @@ -809,70 +476,6 @@ def _emulator_files_section( return lines, part_pages -def _data_directory_lines( - dd: dict, profile: dict, data_registry: dict | None, member_anchors: set[str], - registry: PageRegistry, -) -> tuple[list[str], dict[str, str]]: - """One data directory: what it holds, where it comes from, which build - reads it, and the pages its member list went to.""" - lines: list[str] = [] - part_pages: dict[str, str] = {} - ref = dd.get("ref", "") - dest = dd.get("destination", "") - entry = (data_registry or {}).get(ref, {}) - # An empty destination wrote "``", which opened a code span - # running to the next one and hid a link from the MDX pass. - line = f"- `{ref}` > `{dest}`" if dest else f"- `{ref}`" - if entry.get("description"): - line += f": {entry['description']}" - lines.append(line) - lines.extend(f" - {line}" for line in data_directory_origin( - entry, registry.data_revisions.get(ref) or {})) - if dd.get("mode"): - lines.append(f" - Read by the {dd['mode']} build only") - if dd.get("bundled"): - lines.append(" - Installed with the emulator, so packs leave it out") - if dd.get("source_ref"): - lines.append(f" - Source: {source_ref_markdown(profile, dd['source_ref'])}") - members = registry.data_members.get(ref) or {} - tree_pages = data_tree_pages(ref, members) - if tree_pages: - where = (f"[a page of their own]({tree_pages[0][0]}.md)" if len(tree_pages) == 1 - else "pages of their own: " + ", ".join( - f"[part {i}]({stem}.md)" for i, (stem, _names) in enumerate(tree_pages, 1))) - lines.append(f" - {count_text(len(members), 'file')}, listed on {where}") - for index, (stem, _names) in enumerate(tree_pages): - part_pages[stem] = _data_tree_page(ref, entry, tree_pages, index, registry) - elif members: - table = _data_member_table(members, sorted(members), member_anchors) - lines.append("") - lines.extend(markup.details( - "info", f"{count_text(len(members), 'file')}, as the packs ship them", - table, indent=" ")) - return lines, part_pages - - -def _data_directories_section( - profile: dict, data_dirs: list[dict], data_registry: dict | None, registry: PageRegistry, -) -> tuple[list[str], dict[str, str]]: - """The Data directories section, and the pages its member lists went to.""" - # The member tables are a file list with hashes: out of the search, - # dolphin, primehack and ishiiruka each put 210 KB of it there. - trees: list[str] = [] - part_pages: dict[str, str] = {} - member_anchors: set[str] = set() - # Each tree with what it holds, where it comes from, which build reads - # it and the code that does: these trees put thousands of files in - # the packs, and the page said only `dolphin-sys` > `Sys`. - for dd in data_dirs: - lines, pages = _data_directory_lines(dd, profile, data_registry, member_anchors, registry) - trees.extend(lines) - part_pages.update(pages) - trees.append("") - # The member tables are the lookup's. - return ["## Data directories", "", *search_excluded(trees)], part_pages - - def emulator_pages( name: str, profile: dict, @@ -902,7 +505,7 @@ def emulator_pages( part_pages: dict[str, str] = {} one_bios = any_name_bios(profile) - intro = _emulator_intro(emu_name, profile, _collection_card_href( + intro = emulator_intro(emu_name, profile, _collection_card_href( one_bios, consumers, name) if one_bios else "", name) romset = emulator_romset(profile) lines = [ @@ -960,7 +563,7 @@ def emulator_pages( lines.extend(["## Profile data", "", *blocks]) if data_dirs: - section, pages = _data_directories_section(profile, data_dirs, data_registry, registry) + section, pages = data_directories_section(profile, data_dirs, data_registry, registry) lines.extend(section) part_pages.update(pages) @@ -1008,26 +611,6 @@ def _card_index( ] -def _part_front_matter(parent: tuple[str, str], siblings: list[tuple[str, str]], - index: int, front: dict | None = None) -> list[str]: - """The front matter of part ``index`` of ``siblings`` ((label, link) - each): the page it belongs to, its neighbours and the part weight. - - MAME's eight card pages had no parent, so the crumbs skipped MAME, and - `prev: false`, so part 5 reached part 6 only through a sentence. - The first part's previous page is the parent, the last part has no next. - """ - data = dict(front or {}) - data["parent"] = {"label": parent[0], "link": parent[1]} - before = siblings[index - 1] if index > 0 else parent - data["prev"] = {"label": before[0], "link": before[1]} - data["next"] = ({"label": siblings[index + 1][0], "link": siblings[index + 1][1]} - if index + 1 < len(siblings) else False) - data["searchWeight"] = SEARCH_WEIGHT.get("part", DEMOTED_WEIGHT) - return ["---", yaml.safe_dump(data, sort_keys=False, allow_unicode=True).rstrip("\n"), - "---", ""] - - def _emulator_part_page( name: str, emu_name: str, number: int, parts: Sequence[tuple[str, Sequence[int]]], cards: list[list[str]], files: list[dict], rows: list[siteentries.Row] | None = None, @@ -1045,7 +628,7 @@ def _emulator_part_page( others = ", ".join( f"[{n}]({stem}.md)" for n, (stem, _e) in enumerate(parts, 1) if n != number) lines = [ - *_part_front_matter((emu_name, f"{name}.md"), + *part_front_matter((emu_name, f"{name}.md"), [(f"{emu_name} files, part {n}", f"{stem}.md") for n, (stem, _e) in enumerate(parts, 1)], number - 1), f"# {emu_name} files, part {number} of {len(parts)}", diff --git a/scripts/sitegen/exportrows.py b/scripts/sitegen/exportrows.py new file mode 100644 index 000000000..946769020 --- /dev/null +++ b/scripts/sitegen/exportrows.py @@ -0,0 +1,352 @@ +"""The rows of the bulk data exports: platform entries, emulator files, gaps, cross-references and wanted dumps.""" + +from __future__ import annotations + +import functools +import json +import sys +from collections.abc import Callable + +from core.artifacts import json_text as _json_text +from core.paths import REPO_ROOT +from model.database import sha1_at +from model.platforms import ENTRY_TAGS, registry_fields +from model.profiles import is_emulator +from sitegen.config import build_commit +from sitegen.install import release_pack_platforms +from sitegen.lookup import HASH_ALGORITHMS, hash_pairs +from sitegen.provenance import WantedDumps + + +def accepted_hash_rows(platform_files: list[dict], emulator_items: list[dict]) -> list[dict]: + """One row per accepted hash value, for both layers, lookup-ready.""" + rows: list[dict] = [] + for row in platform_files: + # A table row keeps the field as declared under _raw. + declared = {algo: row.get(f"{algo}_raw", row.get(algo)) for algo in HASH_ALGORITHMS} + rows.extend({ + "layer": "platform", "owner": row["platform_id"], + "system": row["system"], "name": row["name"], + "path": row["destination"], "algorithm": algorithm, "value": value, + } for algorithm, value in hash_pairs(declared)) + for item in emulator_items: + for entry in item["profile"].get("files", []) or []: + if not isinstance(entry, dict): + continue + rows.extend({ + "layer": "emulator", "owner": item["id"], + "system": _json_text(entry.get("system")), + "name": entry.get("name", ""), "path": entry.get("path", "") or "", + "algorithm": algorithm, "value": value, + } for algorithm, value in hash_pairs(entry)) + # Members of an archive: MAME and FBNeo hash the ROMs inside the + # set, never the set. Left out, a loose nmk004.bin (crc32 + # 83b6f611) found no row while the site search found it. + archive = entry.get("name", "") + for member in entry.get("contents") or []: + if not isinstance(member, dict) or not member.get("name"): + continue + rows.extend({ + "layer": "emulator", "owner": item["id"], + "system": _json_text(entry.get("system")), + "name": str(member["name"]), "path": f"{archive}/{member['name']}", + "algorithm": algorithm, "value": value, + } for algorithm, value in hash_pairs(member)) + rows.sort(key=lambda r: (r["layer"], r["owner"], r["name"], r["algorithm"], r["value"])) + return rows + + +def _verify_outcomes( + coverage: dict, db: dict +) -> Callable[[str, str], dict]: + """For each declared entry, in declaration order: what verify found. + + Returns a function of (system, name) giving the next outcome for that + pair: status, category, the collection path that answers the entry and + that file's sha1. The CSV gave the declaration and nothing about it. + """ + details: dict[tuple[str, str], list[dict]] = {} + for detail in coverage.get("details") or []: + details.setdefault((detail.get("system", ""), detail.get("name", "")), []).append(detail) + taken: dict[tuple[str, str], int] = {} + + def outcome(system: str, name: str) -> dict: + found = details.get((system, name)) or [{}] + nth = taken.get((system, name), 0) + taken[(system, name)] = nth + 1 + detail = found[min(nth, len(found) - 1)] + path = str(detail.get("path") or "") if detail.get("status") != "missing" else "" + return { + "status": detail.get("status", ""), + "category": detail.get("category", ""), + "collection_path": path, + "resolved_sha1": sha1_at(db, path) or "", + } + return outcome + + +@functools.lru_cache(maxsize=1) +def _contract_keys() -> frozenset[str]: + """The top-level keys platform.schema.json allows in a platform's list.""" + schema = json.loads((REPO_ROOT / "schemas" / "platform.schema.json").read_text(encoding="utf-8")) + return frozenset(schema.get("properties") or {}) + + +def _split_contract(config: dict) -> tuple[dict, dict]: + """The list, valid against platform.schema.json, and the registry entry. + + load_platform_config merges the registry into the list: `install`, + `logo`, `scraper` and `_key` made all 18 contracts fail the published + schema. They stay published, beside the contract. + """ + allowed = _contract_keys() + contract = {key: value for key, value in config.items() if key in allowed} + if isinstance(contract.get("systems"), dict): + contract["systems"] = { + sys_id: { + **system, + "files": [ + { + k: v + for k, v in f.items() + if k not in ENTRY_TAGS + } + for f in system["files"] + ], + } + if isinstance(system, dict) and system.get("files") + else system + for sys_id, system in contract["systems"].items() + } + registry = {key: value for key, value in registry_fields(config).items() + if key not in allowed} + # The merged config gives a child its parent's release_pack: Lakka and + # RetroPie said true in the API while every page said they had no ZIP. + # The registry's own entry decides, as it does for the pages. + released = config.get("_key") in release_pack_platforms() + if released or "release_pack" in registry: + registry["release_pack"] = released + return contract, registry + + +# Per-entry fields a folder check needs beyond the hashes: an md5 is a ZIP +# member's when zipped_file is set, and a CSV without it judged 106 good +# Batocera files wrong. +ENTRY_EXPORT_FIELDS = ( + "zipped_file", "hash_match_mandatory", "mandatory_declared", "curated", + "shared_group", "mirror_of", "zip_digest", +) + + +def platform_export_rows( + coverages: dict, db: dict | None = None, +) -> tuple[list[dict], list[dict]]: + """Normalized platform summaries and one row per declared file.""" + items: list[dict] = [] + file_rows: list[dict] = [] + for key, coverage in sorted(coverages.items()): + config = coverage["config"] + outcome = _verify_outcomes(coverage, db or {}) + contract, registry = _split_contract(config) + items.append({ + "id": key, + "name": coverage["platform"], + "coverage": { + field: coverage.get(field, 0) + for field in ( + "total", "present", "verified", "untested", "missing", + "core_present", "core_missing", "core_unplaced", "core_unsourceable", + ) + }, + "contract": contract, + "registry": registry, + }) + for system_id, system in sorted(config.get("systems", {}).items()): + file_rows.extend({ + "platform_id": key, + "platform": coverage["platform"], + "system": system_id, + "name": entry.get("name", ""), + "destination": entry.get( + "destination", entry.get("dest", entry.get("name", "")) + ), + "required": bool(entry.get("required", True)), + "region": _json_text(entry.get("region")), + "selection_slot": _json_text(entry.get("selection_slot")), + "size": entry.get("size"), + "sha1": _json_text(entry.get("sha1")), + "sha256": _json_text(entry.get("sha256")), + "md5": _json_text(entry.get("md5")), + "crc32": _json_text(entry.get("crc32")), + **{field: _export_flag(entry.get(field)) for field in ENTRY_EXPORT_FIELDS}, + **outcome(system_id, entry.get("name", "")), + } for entry in system.get("files", []) or []) + return items, file_rows + + +def _export_flag(value: object) -> object: + """A per-entry field as CSV and SQLite hold it: booleans stay booleans, + an absent field is empty.""" + if value is None: + return "" + return value if isinstance(value, bool) else str(value) + + +def emulator_export_items(profiles: dict) -> list[dict]: + return [ + {"id": key, "profile": profile} + for key, profile in sorted(profiles.items()) + ] + + +def gap_export_rows( + coverages: dict, gap_report: dict | None = None, db: dict | None = None, +) -> list[dict]: + """Every gap the site reports, both layers, in one table. + + ``platform`` rows are anomalies against a platform's own BIOS list. + ``emulator`` rows are files a profiled core loads that no platform + declares, which is the larger number the gap analysis page leads with. + A `layer` column keeps the two apart instead of publishing only one. + """ + rows: list[dict] = [] + db = db or {} + for key, coverage in sorted(coverages.items()): + for detail in coverage.get("details", []): + if detail.get("status") == "ok" and not detail.get("discrepancy"): + continue + path = str(detail.get("path") or "") if detail.get("status") != "missing" else "" + rows.append({ + "category": detail.get("category", "bios"), + "collection_path": path, + "resolved_sha1": sha1_at(db, path) or "", + "layer": "platform", + "platform_id": key, + "platform": coverage["platform"], + "emulator": "", + "system": detail.get("system", ""), + "name": detail.get("name", ""), + "status": detail.get("status", ""), + "required": bool(detail.get("required", True)), + "in_repo": "", + "reason": detail.get("reason", ""), + "discrepancy": detail.get("discrepancy", ""), + "destination": detail.get("destination", ""), + "expected": "", + }) + for emu_key, data in sorted((gap_report or {}).items()): + systems = ";".join(str(s) for s in data.get("systems", []) or []) + # The category travels on the row: its path is the destination the + # running build reads, not the profile's, and a join on it left 940 + # rows without one. + rows.extend({ + "category": gap.get("category", ""), + "collection_path": "", + "resolved_sha1": "", + "layer": "emulator", + "platform_id": "", + "platform": "", + "emulator": data.get("emulator", emu_key), + "system": systems, + "name": gap.get("name", ""), + # A file the emulator's own package installs is not one to + # find: its own status, as unsourceable has. + "status": ( + "bundled" if gap.get("bundled") and gap.get("source") == "missing" + else gap.get("source", "") + ), + "required": bool(gap.get("required", False)), + "in_repo": bool(gap.get("in_repo", False)), + "reason": gap.get("note", ""), + "discrepancy": "", + # What a contributor needs to supply the right revision and + # put it in the right place: the gaps table gave neither. + "destination": gap.get("path") or gap.get("name", ""), + "expected": gap.get("identity", ""), + } for gap in data.get("gap_details", []) or []) + rows.extend({ + "category": entry.get("category", ""), + "collection_path": "", + "resolved_sha1": "", + "layer": "emulator", + "platform_id": "", + "platform": "", + "emulator": data.get("emulator", emu_key), + "system": systems, + "name": entry.get("name", ""), + "status": "unsourceable", + "required": bool(entry.get("required", False)), + "in_repo": False, + "reason": entry.get("reason", ""), + "discrepancy": "", + "destination": entry.get("path") or entry.get("name", ""), + "expected": "", + } for entry in data.get("unsourceable", []) or []) + # Two declarations that differ only in what the row does not carry are + # one row: AmberELEC's hardwareconfig.xml was printed twice. + unique: dict[tuple, dict] = {} + for row in rows: + unique.setdefault(tuple(sorted((k, str(v)) for k, v in row.items())), row) + return list(unique.values()) + + +def cross_reference_export_rows(coverages: dict, profiles: dict) -> list[dict]: + from resolve.cores import resolve_platform_cores + + unique = { + key: value + for key, value in profiles.items() + if is_emulator(value) + } + rows: list[dict] = [] + for platform_id, coverage in sorted(coverages.items()): + for profile_id in sorted(resolve_platform_cores(coverage["config"], unique)): + profile = unique[profile_id] + cores = profile.get("cores") or [profile_id] + systems = profile.get("systems") or [""] + for core in cores: + rows.extend({ + "platform_id": platform_id, + "platform": coverage["platform"], + "profile_id": profile_id, + "emulator": profile.get("emulator", profile_id), + "core": core, + "system": system, + "classification": profile.get("core_classification", ""), + "type": profile.get("type", ""), + "source": _json_text(profile.get("source")), + "upstream": _json_text(profile.get("upstream")), + "profiled_commit": _json_text(profile.get("source_commit", "")), + "file_count": len(profile.get("files", []) or []), + } for system in systems) + return rows + + +@functools.lru_cache(maxsize=1) +def source_commit() -> str: + """build_commit, empty outside a checkout: the exports then name no commit.""" + import subprocess + + try: + return build_commit() + except (OSError, subprocess.CalledProcessError, ValueError) as error: + print(f" no commit recorded in the exports: {error}", file=sys.stderr) + return "" + + +# One row per dump a catalog describes and the collection lacks: the list +# the provenance page publishes under "Wanted". +WANTED_FIELDS = ("catalog", "dat", "name", "description", "size", "crc32", "md5", "sha1") + + +def provenance_wanted_rows(dumps: WantedDumps | None) -> list[dict]: + """The Wanted list of the provenance page, as rows.""" + rows: list[dict] = [] + for catalog, data in (dumps.wanted if dumps else {}).items(): + for entry in data["missing"]: + rows.extend({ + "catalog": catalog, "dat": dat, + **{f: _json_text(entry.get(f)) for f in WANTED_FIELDS[2:]}, + } for dat in entry.get("dats") or [entry.get("dat", "")]) + rows.sort(key=lambda r: (r["catalog"], r["dat"], r["name"], r["sha1"])) + return rows diff --git a/scripts/sitegen/gapproblems.py b/scripts/sitegen/gapproblems.py new file mode 100644 index 000000000..863575f11 --- /dev/null +++ b/scripts/sitegen/gapproblems.py @@ -0,0 +1,220 @@ +"""The gaps page's problem files: what a platform declares and its own check rejects.""" + +from __future__ import annotations + +import html + +from model.database import declared_records, sha1_at +from sitegen.cards import fetch_url +from sitegen.render import code_span, count_text, escape_tags + + +# Contributing page + + +def _held_accepted(accepted: dict[str, list[str]], db: dict | None) -> str: + """Where the collection keeps a dump the emulator accepts, if it does. + + The table printed the hash the emulator wants and stopped there, while + the collection held that exact dump for every one of the ten rows. + ``accepted`` is the verify detail's field, the values by algorithm. + """ + if not accepted or not db: + return "" + files = db.get("files", {}) + return next((path for named in declared_records(db, accepted).values() + for sha1 in named if (path := files[sha1].get("path"))), "") + + +def short_hash(value: str) -> str: + """A hash in a table cell: its first 12 characters, the whole value in + the title. Full MD5 and SHA1 values pushed the gaps tables past the + column on every screen.""" + value = str(value) + if len(value) <= 12: + return code_span(value) + return f'{html.escape(value[:12])}' + + +def _hash_cell(hashes: dict[str, list[str]]) -> str: + return "
".join( + f"{algo} " + ", ".join(short_hash(v) for v in values) for algo, values in hashes.items() + ) + + +def reason_cell(text: str) -> str: + """A reason in a gaps table, in the class that keeps its column readable.""" + return f'{text}' if text else "-" + + +def _copy_cell(path: str, algos: list[str], db: dict | None) -> str: + """The file a path holds, with its hashes in the algorithms declared.""" + if not path: + return "-" + sha1 = sha1_at(db or {}, path) + record: dict = (db or {})["files"][sha1] | {"sha1": sha1} if sha1 else {} + hashes = {algo: [str(record[algo]).lower()] for algo in algos if record.get(algo)} + shown = f"[{code_span(path)}]({fetch_url(path)})" + return f"{shown}
{_hash_cell(hashes)}" if hashes else shown + + +def render_problem_files( + platform_problems: list, settled: list | None = None, db: dict | None = None, + missing_total: int | None = None, +) -> list[str]: + """Files a platform declares that its own check then rejects. + + Split out of generate_gap_analysis, which reached complexity 56. This + section is the one that stands alone: it reads platform_problems and + nothing else, where the sections around it share gap_report and the + resolved core list. + """ + lines: list[str] = [] + # ---- Section 2: Problem files ---- + + missing_files: dict[str, dict] = {} + untested_files: dict[str, dict] = {} + mismatch_files: dict[str, dict] = {} + + for p in platform_problems: + fname = p["name"] + if p["status"] == "missing": + entry = missing_files.setdefault(fname, { + "name": fname, "required": p["required"], + "platforms": [], "reason": p["reason"], "categories": set(), + "where": {}, + }) + entry["platforms"].append(p["platform"]) + # The platform's entry for the file, and the folder it expects. + entry["where"].setdefault( + (p["platform"], p.get("platform_key", ""), p.get("system", "")), set(), + ).add(p.get("destination") or fname) + entry["categories"].add(p.get("category", "bios")) + if p["required"]: + entry["required"] = True + elif p["status"] == "untested": + # Keyed by what is declared and what is held: two platforms + # asking two dumps under one name are two rows. + declared = p.get("declared") or {} + key = f"{fname}\0{sorted(declared.items())}\0{p.get('path', '')}" + entry = untested_files.setdefault(key, { + "name": fname, "required": p["required"], + "platforms": [], "reason": p["reason"], + "declared": declared, "path": p.get("path", ""), + }) + entry["platforms"].append(p["platform"]) + if p.get("discrepancy"): + entry = mismatch_files.setdefault(fname, { + "name": fname, "platforms": [], + "discrepancy": p["discrepancy"], + "accepted": p.get("accepted") or {}, + }) + entry["platforms"].append(p["platform"]) + + total_problems = len(missing_files) + len(untested_files) + len(mismatch_files) + # One row per name: the page opened on "48 are missing", counted by + # destination, above a heading that said "10 files". Both are said. + names = count_text(len(missing_files), "name") + missing_said = (f"{missing_total:,} missing under {names}" + if missing_total is not None else f"{len(missing_files)} missing") + + if total_problems > 0: + lines.extend([ + "## Problem files", + "", + f"{missing_said}, {len(untested_files)} untested, " + f"{len(mismatch_files)} discrepancy.", + "", + ]) + + if missing_files: + lines.extend([ + f'### Missing ' + f"{count_text(len(missing_files), 'name')}", + "", + "Required is the platform's own flag. Category says what the " + "platform's emulators do with the file: `bios` is firmware they " + "load, `game_data` comes from a copy of the game, `unread` is " + "opened by none of them. Only a missing `bios` entry stops a " + "console from starting. A name a list declares in several " + "folders is one row. Each platform links to its entry, which " + "names the cores examined, and is followed by where its list " + "puts the file.", + "", + "| File | Category | Required | Platforms |", + "|------|----------|----------|-----------|", + ]) + for fname in sorted(missing_files): + f = missing_files[fname] + req = "yes" if f["required"] else "no" + plats = "; ".join( + (f"[{display}](platforms/{key}.md#{system.replace(' ', '-')})" + if key and system else display) + + " " + ", ".join(code_span(dest) for dest in sorted(dests)) + for (display, key, system), dests in sorted(f["where"].items()) + ) + cats = f["categories"] + category = "bios" if "bios" in cats else ", ".join(sorted(cats)) + lines.append(f"| `{fname}` | {category} | {req} | {plats} |") + lines.append("") + + if untested_files: + lines.extend([ + f'### Untested ' + f"{count_text(len(untested_files), 'file')}", + "", + "Present, but not the expected hash. Declared is what the platform " + "asks for, the collection copy is what the path holds.", + "", + "| File | Platforms | Reason | Declared | Collection copy |", + "|------|----------|--------|----------|-----------------|", + ]) + for key in sorted(untested_files): + f = untested_files[key] + plats = ", ".join(sorted(set(f["platforms"]))) + declared = f["declared"] + lines.append( + f"| {code_span(f['name'])} | {plats} | {reason_cell(f['reason'])} " + f"| {_hash_cell(declared) or '-'} " + f"| {_copy_cell(f['path'], list(declared) or ['md5'], db)} |" + ) + lines.append("") + + if mismatch_files: + lines.extend([ + f'### Discrepancy ' + f"{count_text(len(mismatch_files), 'file')}", + "", + "The platform's own check passes, but the emulator's size or " + "hash check fails. Each row names the check that fails.", + "", + "| File | Platforms | Discrepancy | Accepted dump in the collection |", + "|------|----------|-------------|-------------------|", + ]) + for fname in sorted(mismatch_files): + f = mismatch_files[fname] + plats = ", ".join(sorted(set(f["platforms"]))) + held = _held_accepted(f["accepted"], db) + cell = f"[{code_span(held)}]({fetch_url(held)})" if held else "-" + lines.append(f"| `{fname}` | {plats} | {reason_cell(f['discrepancy'])} | {cell} |") + lines.append("") + + if settled: + lines.extend([ + "### Other revisions of a held destination", + "", + "A platform can declare one path twice with different hashes. The " + "path holds the file one declaration accepts, so it is counted once, " + "as held. The other declaration cannot be met at the same time.", + "", + "| File | Platform | Status | Path held for system |", + "|------|----------|--------|--------------|", + ]) + lines.extend( + f"| {code_span(p['name'])} | {escape_tags(p['platform'])} | {p['status']} " + f"| {code_span(p['held_by'])} |" + for p in sorted(settled, key=lambda row: (row["name"], row["platform"])) + ) + lines.append("") + + return lines diff --git a/scripts/sitegen/gaps.py b/scripts/sitegen/gaps.py index b20d4f69d..2ff49cd57 100644 --- a/scripts/sitegen/gaps.py +++ b/scripts/sitegen/gaps.py @@ -3,27 +3,32 @@ from __future__ import annotations import dataclasses -import html from dataclasses import dataclass from typing import TYPE_CHECKING from core.hashing import declared_hash_lists from core.text import series -from model.database import declared_records, sha1_at from model.platforms import native_layer -from packs.crossref import gap_source_counts, whole_tree_gaps +from packs.crossref import whole_tree_gaps from resolve.nativemode import check_label -from resolve.sendable import sendable from sitegen import markup, wanted as sitewanted -from sitegen.cards import PROVENANCE_LABELS, fetch_url from sitegen.config import date_line from sitegen.emulatorsindex import content_check_ceiling -from sitegen.parts import list_pages -from sitegen.render import code_span, count_text, escape_tags -from sitegen.sources import source_ref_markdown if TYPE_CHECKING: from packs.supplemental import SupplementalIndex +from sitegen.gapproblems import render_problem_files +from sitegen.gapsources import ( + SourceListing, + bundled_note, + complement_intro, + missing_files, + not_collected_section, + source_counted, + source_row, + source_table, + undeclared_gaps, +) @dataclass(frozen=True) @@ -34,23 +39,6 @@ class PlatformRegistries: data_dirs: dict = dataclasses.field(default_factory=dict) -# Contributing page - - -def _held_accepted(accepted: dict[str, list[str]], db: dict | None) -> str: - """Where the collection keeps a dump the emulator accepts, if it does. - - The table printed the hash the emulator wants and stopped there, while - the collection held that exact dump for every one of the ten rows. - ``accepted`` is the verify detail's field, the values by algorithm. - """ - if not accepted or not db: - return "" - files = db.get("files", {}) - return next((path for named in declared_records(db, accepted).values() - for sha1 in named if (path := files[sha1].get("path"))), "") - - def _declarations(cov: dict) -> dict[int, dict]: """Each verify detail of a platform, by id, with the declaration it scores (wanted.paired_declarations): AmberELEC declares @@ -68,226 +56,6 @@ def _declarations(cov: dict) -> dict[int, dict]: } -def short_hash(value: str) -> str: - """A hash in a table cell: its first 12 characters, the whole value in - the title. Full MD5 and SHA1 values pushed the gaps tables past the - column on every screen.""" - value = str(value) - if len(value) <= 12: - return code_span(value) - return f'{html.escape(value[:12])}' - - -def _hash_cell(hashes: dict[str, list[str]]) -> str: - return "
".join( - f"{algo} " + ", ".join(short_hash(v) for v in values) for algo, values in hashes.items() - ) - - -def catalog_listings(report: dict | None, labels: dict[str, str]) -> dict[tuple[str, str], list[tuple[str, str]]]: - """(profile, file name casefolded) -> (catalog or romset, the name it - lists the file under), from a provenance report built with the - profiles' needs: the "Listed in" column of the gaps page.""" - out: dict[tuple[str, str], list[tuple[str, str]]] = {} - for source, data in sorted((report or {}).items()): - label = labels.get(source, source) - for entry in data.get("missing", []): - where = [(label, str(entry.get("name", "")))] - where += [(str(hit["source"]), str(hit["archive"])) for hit in entry.get("romsets", [])] - for need in entry.get("needed_by", []): - held = out.setdefault((need["emulator"], str(need["name"]).casefold()), []) - held += [w for w in where if w not in held] - return out - - -def _catalogued_needs(report: dict | None) -> dict[tuple[str, str], list[str]]: - """(profile, file name casefolded) -> where a dump catalog or an - imported romset lists that file, from a provenance report built with - the profiles' needs.""" - return { - need: [f"{escape_tags(where)} `{escape_tags(name)}`" for where, name in listed] - for need, listed in catalog_listings(report, PROVENANCE_LABELS).items() - } - - -def _reason_cell(text: str) -> str: - """A reason in a gaps table, in the class that keeps its column readable.""" - return f'{text}' if text else "-" - - -def _copy_cell(path: str, algos: list[str], db: dict | None) -> str: - """The file a path holds, with its hashes in the algorithms declared.""" - if not path: - return "-" - sha1 = sha1_at(db or {}, path) - record: dict = (db or {})["files"][sha1] | {"sha1": sha1} if sha1 else {} - hashes = {algo: [str(record[algo]).lower()] for algo in algos if record.get(algo)} - shown = f"[{code_span(path)}]({fetch_url(path)})" - return f"{shown}
{_hash_cell(hashes)}" if hashes else shown - - -def _render_problem_files( - platform_problems: list, settled: list | None = None, db: dict | None = None, - missing_total: int | None = None, -) -> list[str]: - """Files a platform declares that its own check then rejects. - - Split out of generate_gap_analysis, which reached complexity 56. This - section is the one that stands alone: it reads platform_problems and - nothing else, where the sections around it share gap_report and the - resolved core list. - """ - lines: list[str] = [] - # ---- Section 2: Problem files ---- - - missing_files: dict[str, dict] = {} - untested_files: dict[str, dict] = {} - mismatch_files: dict[str, dict] = {} - - for p in platform_problems: - fname = p["name"] - if p["status"] == "missing": - entry = missing_files.setdefault(fname, { - "name": fname, "required": p["required"], - "platforms": [], "reason": p["reason"], "categories": set(), - "where": {}, - }) - entry["platforms"].append(p["platform"]) - # The platform's entry for the file, and the folder it expects. - entry["where"].setdefault( - (p["platform"], p.get("platform_key", ""), p.get("system", "")), set(), - ).add(p.get("destination") or fname) - entry["categories"].add(p.get("category", "bios")) - if p["required"]: - entry["required"] = True - elif p["status"] == "untested": - # Keyed by what is declared and what is held: two platforms - # asking two dumps under one name are two rows. - declared = p.get("declared") or {} - key = f"{fname}\0{sorted(declared.items())}\0{p.get('path', '')}" - entry = untested_files.setdefault(key, { - "name": fname, "required": p["required"], - "platforms": [], "reason": p["reason"], - "declared": declared, "path": p.get("path", ""), - }) - entry["platforms"].append(p["platform"]) - if p.get("discrepancy"): - entry = mismatch_files.setdefault(fname, { - "name": fname, "platforms": [], - "discrepancy": p["discrepancy"], - "accepted": p.get("accepted") or {}, - }) - entry["platforms"].append(p["platform"]) - - total_problems = len(missing_files) + len(untested_files) + len(mismatch_files) - # One row per name: the page opened on "48 are missing", counted by - # destination, above a heading that said "10 files". Both are said. - names = count_text(len(missing_files), "name") - missing_said = (f"{missing_total:,} missing under {names}" - if missing_total is not None else f"{len(missing_files)} missing") - - if total_problems > 0: - lines.extend([ - "## Problem files", - "", - f"{missing_said}, {len(untested_files)} untested, " - f"{len(mismatch_files)} discrepancy.", - "", - ]) - - if missing_files: - lines.extend([ - f'### Missing ' - f"{count_text(len(missing_files), 'name')}", - "", - "Required is the platform's own flag. Category says what the " - "platform's emulators do with the file: `bios` is firmware they " - "load, `game_data` comes from a copy of the game, `unread` is " - "opened by none of them. Only a missing `bios` entry stops a " - "console from starting. A name a list declares in several " - "folders is one row. Each platform links to its entry, which " - "names the cores examined, and is followed by where its list " - "puts the file.", - "", - "| File | Category | Required | Platforms |", - "|------|----------|----------|-----------|", - ]) - for fname in sorted(missing_files): - f = missing_files[fname] - req = "yes" if f["required"] else "no" - plats = "; ".join( - (f"[{display}](platforms/{key}.md#{system.replace(' ', '-')})" - if key and system else display) - + " " + ", ".join(code_span(dest) for dest in sorted(dests)) - for (display, key, system), dests in sorted(f["where"].items()) - ) - cats = f["categories"] - category = "bios" if "bios" in cats else ", ".join(sorted(cats)) - lines.append(f"| `{fname}` | {category} | {req} | {plats} |") - lines.append("") - - if untested_files: - lines.extend([ - f'### Untested ' - f"{count_text(len(untested_files), 'file')}", - "", - "Present, but not the expected hash. Declared is what the platform " - "asks for, the collection copy is what the path holds.", - "", - "| File | Platforms | Reason | Declared | Collection copy |", - "|------|----------|--------|----------|-----------------|", - ]) - for key in sorted(untested_files): - f = untested_files[key] - plats = ", ".join(sorted(set(f["platforms"]))) - declared = f["declared"] - lines.append( - f"| {code_span(f['name'])} | {plats} | {_reason_cell(f['reason'])} " - f"| {_hash_cell(declared) or '-'} " - f"| {_copy_cell(f['path'], list(declared) or ['md5'], db)} |" - ) - lines.append("") - - if mismatch_files: - lines.extend([ - f'### Discrepancy ' - f"{count_text(len(mismatch_files), 'file')}", - "", - "The platform's own check passes, but the emulator's size or " - "hash check fails. Each row names the check that fails.", - "", - "| File | Platforms | Discrepancy | Accepted dump in the collection |", - "|------|----------|-------------|-------------------|", - ]) - for fname in sorted(mismatch_files): - f = mismatch_files[fname] - plats = ", ".join(sorted(set(f["platforms"]))) - held = _held_accepted(f["accepted"], db) - cell = f"[{code_span(held)}]({fetch_url(held)})" if held else "-" - lines.append(f"| `{fname}` | {plats} | {_reason_cell(f['discrepancy'])} | {cell} |") - lines.append("") - - if settled: - lines.extend([ - "### Other revisions of a held destination", - "", - "A platform can declare one path twice with different hashes. The " - "path holds the file one declaration accepts, so it is counted once, " - "as held. The other declaration cannot be met at the same time.", - "", - "| File | Platform | Status | Path held for system |", - "|------|----------|--------|--------------|", - ]) - lines.extend( - f"| {code_span(p['name'])} | {escape_tags(p['platform'])} | {p['status']} " - f"| {code_span(p['held_by'])} |" - for p in sorted(settled, key=lambda row: (row["name"], row["platform"])) - ) - lines.append("") - - return lines - - def _platform_lists_sentence( total: int, verified: int, untested: int, missing: int, not_firmware: dict[str, int] | None = None, @@ -345,18 +113,6 @@ def _ratio_cell(done: int, total: int, alarm: int = 0) -> str: return cell -# GitHub's upload page for a folder of bios/: a browser upload by someone -# without write access lands on a fork and opens a pull request. -UPLOAD_URL = f"{sitewanted.UPLOAD_ROOT}bios" -# Rows of Files to source on one page: 601 on one page made a phone page -# 274,509 px long. -FILES_TO_SOURCE_PART = 100 -# The two other long tables, each on a page of its own. Emulator cards link -# the second. -PER_EMULATOR_STEM = "gaps-per-emulator" -NOT_COLLECTED_STEM = "gaps-not-collected" - - @dataclass class _VerifyTally: """Verify results aggregated across all platforms.""" @@ -496,306 +252,6 @@ def _divergence_rows( return div_rows -@dataclass -class _MissingFiles: - """The files to find, one row each, and the entries they come from.""" - - rows: list[dict] = dataclasses.field(default_factory=list) - entries: int = 0 - bundled: set[tuple[str, str]] = dataclasses.field(default_factory=set) - - -def _missing_files(emulator_gaps: list[tuple[str, dict]]) -> _MissingFiles: - """One row per file to find: a name two emulators share is one file - only when both declare the same hash. Keyed by name alone, Fallout - 2's master.dat vanished behind Fallout 1's, and the three Sonic - decompilations' Data.rsdk showed as one.""" - found = _MissingFiles() - by_identity: dict[tuple[str, str], dict] = {} - for emu_name, data in emulator_gaps: - for g in data["gap_details"]: - if g["source"] != "missing": - continue - if g.get("bundled"): - # It arrives with the emulator's own package, which is - # why the collection documents it and does not hold it: - # asking readers to source it sent them after a file - # every install already has. - found.bundled.add((data["emulator"], g["name"])) - continue - found.entries += 1 - key = (g["name"], g.get("identity") or f"emulator:{emu_name}") - row = by_identity.get(key) - if row is None: - row = by_identity[key] = { - "name": g["name"], - "path": g.get("path") or g["name"], - "identity": g.get("identity", ""), - "profile_path": g.get("profile_path", ""), - "emulators": [data["emulator"]], - "emu_keys": [emu_name], - "required": g["required"], - "source_ref": g["source_ref"], - "platforms": set(g.get("platforms") or ()), - } - found.rows.append(row) - elif emu_name not in row["emu_keys"]: - row["emulators"].append(data["emulator"]) - row["emu_keys"].append(emu_name) - row["required"] = row["required"] or g["required"] - row["platforms"].update(g.get("platforms") or ()) - return found - - -@dataclass(frozen=True) -class SourceListing: - """Where the list of files to source goes. With ``moved``, the list goes - to pages of its own, keyed by stem: on the page it made 662 KB of HTML. - ``placer`` gives each file to source the folder its upload goes to, the - one validate_pr asks for. Without it the link opens bios/.""" - - moved: dict[str, str] | None = None - placer: sitewanted.Placer | None = None - - -def _source_row(m: dict, profiles: dict, placer: sitewanted.Placer | None) -> str: - """The row of one file to source, with the platforms the gap report - found needing it.""" - plats = sorted(m["platforms"]) - plat_badges = ( - " ".join( - f'{p}' - for p in plats - ) - if plats - else "-" - ) - req = "yes" if m["required"] else "no" - algorithm, _, value = m["identity"].partition(":") - expected = f"{algorithm} {short_hash(value)}" if value else "-" - destination = code_span(m["path"]) if m["path"] != m["name"] else "-" - emulators = ", ".join( - f"[{escape_tags(display)}](emulators/{key}.md)" - for display, key in zip(m["emulators"], m["emu_keys"]) - ) - owner = profiles[m["emu_keys"][0]] - declared = sitewanted.gap_entries(owner, m, False) - folder = placer.folder(declared[0]) if placer and declared else "" - upload = sitewanted.upload_href(sitewanted.UPLOAD_ROOT, folder) - return ( - f"| `{m['name']}` [Have it? Upload]({upload}) | {destination} | {expected} " - f"| {emulators} | {req} | {plat_badges} | " - f"{source_ref_markdown(owner, m['source_ref'])} |" - ) - - -def _source_counted(missing: _MissingFiles) -> str: - """How many files there are to source, and the entries they come from.""" - req_src = [m for m in missing.rows if m["required"]] - return ( - f"{count_text(len(missing.rows), 'file')}, {len(req_src)} required." - + ( - f" They come from {count_text(missing.entries, 'entry', 'entries')}: a file " - "declared with the same hash at several places is listed once." - if missing.entries != len(missing.rows) else "" - ) - ) - - -def _source_table(counted: str, rows: list[str], moved: dict[str, str] | None) -> list[str]: - """The table of files to source, on the page or on pages of its own.""" - head = [ - "| File | Destination | Expected | Emulator | Required | Affects platforms | Source ref |", - "|------|-------------|----------|----------|----------|------------------|-----------|", - ] - if moved is None: - return [*head, *rows, ""] - where = list_pages( - "gaps-files-to-source", "Files to source", - f"{counted} Each is a file an emulator loads that no platform lists and " - "the collection does not hold. Part of " - "[What the packs do not hold](gaps.md#files-to-source).", - head, [rows[i:i + FILES_TO_SOURCE_PART] for i in range( - 0, len(rows), FILES_TO_SOURCE_PART)], moved, budget=1, - parent=("What the packs do not hold", "/gaps/"), - ) - return [f"Listed on {where}.", ""] - - -def _bundled_note(bundled_rows: set[tuple[str, str]]) -> list[str]: - """The files that arrive with their emulator, counted, not listed.""" - if not bundled_rows: - return [] - emulators = sorted({emulator for emulator, _name in bundled_rows}) - return [ - f"{len(bundled_rows)} further files arrive with their emulator's own " - f"package ({escape_tags(', '.join(emulators))}): documented in the profile, not " - "collected, and not listed here.", - "", - ] - - -def _undeclared_gaps(report_all: dict) -> tuple[dict[str, int], int, list[tuple[str, dict]]]: - """The files emulators load that no platform lists: counts by source, - the total, and the emulators that have any.""" - src_totals: dict[str, int] = { - "bios": 0, "data": 0, "large_file": 0, "bundled": 0, "missing": 0, - } - total_undeclared = 0 - emulator_gaps = [] - for emu_name, data in sorted(report_all.items()): - if data["gaps"] == 0: - continue - total_undeclared += data["gaps"] - for key, count in gap_source_counts(data).items(): - src_totals[key] += count - emulator_gaps.append((emu_name, data)) - return src_totals, total_undeclared, emulator_gaps - - -def _complement_rows(emulator_gaps: list[tuple[str, dict]]) -> list[str]: - """One row an emulator: its undeclared files by source.""" - rows = [] - for emu_name, data in sorted(emulator_gaps, key=lambda x: -x[1]["gaps"]): - display = data["emulator"] - sources = gap_source_counts(data) - to_source = sources["missing"] - missing_str = ( - f'{to_source}' - if to_source > 0 - else '0' - ) - rows.append( - f"| [{display}](emulators/{emu_name}.md) " - f"| {data['gaps']} " - f"| {sources['bios']} " - f"| {sources['data']} " - f"| {sources['large_file']} " - f"| {sources['bundled']} " - f"| {missing_str} |" - ) - return rows - - -def _moved_table(stem: str, title: str, intro: str, head: list[str], rows: list[str], noun: str, - moved: dict[str, str] | None) -> list[str]: - """A table on the gaps page, or on a page of its own with a line here. - Two tables of 340 and 283 rows held most of the gaps page's 8,300 - elements: their first layout was a 200 ms task on a phone.""" - if moved is None: - return [*head, *rows, ""] - where = list_pages(stem, title, intro, head, [rows], moved, budget=1, - parent=("What the packs do not hold", "/gaps/")) - return [f"{count_text(len(rows), noun)}, listed on {where}.", ""] - - -def _complement_intro(src_totals: dict[str, int], total_undeclared: int, - emulator_gaps: list[tuple[str, dict]], - moved: dict[str, str] | None = None) -> list[str]: - """Section 3 up to its per-emulator table: what the emulators load - that no platform lists, and where those files come from.""" - total_available = ( - src_totals["bios"] + src_totals["data"] + src_totals["large_file"] - ) - pct_available = ( - f"{total_available / total_undeclared * 100:.0f}%" - if total_undeclared - else "0%" - ) - return [ - "## Files emulators load that no platform lists { #core-complement }", - "", - f"Files loaded by emulators but not declared by any platform. " - f"{total_undeclared:,} files across {count_text(len(emulator_gaps), 'emulator')}, " - f"{total_available:,} available ({pct_available}), " - f"{src_totals['bundled']:,} installed with their emulator, " - f"{src_totals['missing']:,} to source.", - "", - "This counts every profiled emulator, including those no platform " - "ships yet, so it reaches past what the first table above counts: " - "it covers only the emulators each platform actually ships. " - "Whatever is not in the collection is an acquisition target, named " - "per emulator below.", - "", - "### Where the files come from", - "", - "| Source | Count | Description |", - "|--------|------:|-------------|", - f"| bios/ | {src_totals['bios']} | In repository (database.json) |", - f"| data/ | {src_totals['data']} | Data directories (buildbot, GitHub) |", - f"| release | {src_totals['large_file']} " - "| GitHub release assets (large files) |", - f"| bundled | {src_totals['bundled']} " - "| Installed with the emulator's own package, not collected |", - f"| missing | {src_totals['missing']} | Not available, needs sourcing |", - "", - "### Per emulator", - "", - *_moved_table( - PER_EMULATOR_STEM, "Files emulators load, per emulator", - f"For each of {count_text(len(emulator_gaps), 'emulator')}, the files it loads " - "that no platform lists, counted by where they come from. Part of " - "[What the packs do not hold](gaps.md#per-emulator).", - ["| Emulator | Undeclared | bios | data | release | Bundled | Missing |", - "|----------|----------:|-----:|-----:|--------:|--------:|--------:|"], - _complement_rows(emulator_gaps), "emulator", moved), - ] - - -def _not_collected_section(report_all: dict, profiles: dict, catalogued: dict | None, - moved: dict[str, str] | None = None) -> list[str]: - """Section 4: files the collection does not hold yet (unsourceable).""" - all_unsourceable: list[dict] = [ - { - "name": u["name"], - "emulator": data["emulator"], - "emu_key": emu_name, - "reason": u["reason"], - "source_ref": u.get("source_ref", ""), - # The wanted page's own rule, on the entries behind the row. - "wanted": any(sendable(entry, str(u["reason"])) for entry in sitewanted.gap_entries( - profiles.get(emu_name) or {}, u, True)), - } - for emu_name, data in sorted(report_all.items()) - for u in data.get("unsourceable", []) - ] - if not all_unsourceable: - return [] - listed = _catalogued_needs(catalogued) - # The old heading's address still leads here. - lines = [ - '', - "", - "## Not collected yet", - "", - f"{len(all_unsourceable)} files the collection does not hold. A file " - "with the same name is never served in their place. The [wanted " - f"page](wanted.md) asks for the {sum(u['wanted'] for u in all_unsourceable)} " - "marked wanted. No one can send the others: a name the code builds, a " - "file no copy of which can be shared, game data, or a file the emulator " - "installs itself. \"Listed in\" names a catalog or romset that lists a file.", - "", - ] - rows = [] - for u in sorted(all_unsourceable, key=lambda x: x["name"]): - where = listed.get((u["emu_key"], str(u["name"]).casefold()), []) - rows.append( - f"| `{u['name']}` | {u['emulator']} | {_reason_cell(u['reason'])} " - f"| {source_ref_markdown(profiles[u['emu_key']], u['source_ref'])} " - f"| {', '.join(where) or '-'} | {'yes' if u['wanted'] else 'no'} |" - ) - lines.extend(_moved_table( - NOT_COLLECTED_STEM, "Files not collected yet", - f"{count_text(len(rows), 'file')} the collection does not hold, each with the " - "emulator that loads it, why it is not collected, the catalog or romset " - "that lists it and whether the [wanted page](wanted.md) asks for it. Part of " - "[What the packs do not hold](gaps.md#not-collected-yet).", - ["| File | Emulator | Reason | Source ref | Listed in | Wanted |", - "|------|----------|--------|-----------|-----------|--------|"], - rows, "file", moved)) - return lines - - _PACK_CONTENTS_NOTE = ( "Each fraction is what the pack has over what is needed, counting " "required and optional files alike since both ship. The first column " @@ -943,7 +399,7 @@ def generate_gap_analysis( coverages, registries or PlatformRegistries(), profiles, db, ))) - lines.extend(_render_problem_files(tally.problems, tally.settled, db, tally.missing)) + lines.extend(render_problem_files(tally.problems, tally.settled, db, tally.missing)) # ---- Section 3: Core complement (cross-reference provenance) ---- @@ -951,25 +407,25 @@ def generate_gap_analysis( gap_report = whole_tree_gaps( [cov["config"] for cov in coverages.values()], db, profiles, data_names) report_all = gap_report - src_totals, total_undeclared, emulator_gaps = _undeclared_gaps(report_all) + src_totals, total_undeclared, emulator_gaps = undeclared_gaps(report_all) if total_undeclared > 0: - lines.extend(_complement_intro(src_totals, total_undeclared, emulator_gaps, + lines.extend(complement_intro(src_totals, total_undeclared, emulator_gaps, listing.moved)) # List truly missing files with platform impact - missing = _missing_files(emulator_gaps) + missing = missing_files(emulator_gaps) if missing.rows: - counted = _source_counted(missing) + counted = source_counted(missing) rows = [ - _source_row(m, profiles, listing.placer) + source_row(m, profiles, listing.placer) for m in sorted(missing.rows, key=lambda x: (not x["required"], x["name"])) ] lines.extend(["### Files to source", "", counted, "[The wanted page](wanted.md) lists them, each with its upload button.", ""]) - lines.extend(_source_table(counted, rows, listing.moved)) - lines.extend(_bundled_note(missing.bundled)) + lines.extend(source_table(counted, rows, listing.moved)) + lines.extend(bundled_note(missing.bundled)) - lines.extend(_not_collected_section(report_all, profiles, catalogued, listing.moved)) + lines.extend(not_collected_section(report_all, profiles, catalogued, listing.moved)) lines.extend(["", date_line()]) return "\n".join(lines) + "\n" diff --git a/scripts/sitegen/gapsources.py b/scripts/sitegen/gapsources.py new file mode 100644 index 000000000..09e35a0f6 --- /dev/null +++ b/scripts/sitegen/gapsources.py @@ -0,0 +1,353 @@ +"""The gaps page's core complement: the files to source and those not collected yet.""" + +from __future__ import annotations + +import dataclasses +from dataclasses import dataclass + +from packs.crossref import gap_source_counts +from resolve.sendable import sendable +from sitegen import wanted as sitewanted +from sitegen.cards import PROVENANCE_LABELS +from sitegen.gapproblems import reason_cell, short_hash +from sitegen.parts import list_pages +from sitegen.render import code_span, count_text, escape_tags +from sitegen.sources import source_ref_markdown + + +def catalog_listings(report: dict | None, labels: dict[str, str]) -> dict[tuple[str, str], list[tuple[str, str]]]: + """(profile, file name casefolded) -> (catalog or romset, the name it + lists the file under), from a provenance report built with the + profiles' needs: the "Listed in" column of the gaps page.""" + out: dict[tuple[str, str], list[tuple[str, str]]] = {} + for source, data in sorted((report or {}).items()): + label = labels.get(source, source) + for entry in data.get("missing", []): + where = [(label, str(entry.get("name", "")))] + where += [(str(hit["source"]), str(hit["archive"])) for hit in entry.get("romsets", [])] + for need in entry.get("needed_by", []): + held = out.setdefault((need["emulator"], str(need["name"]).casefold()), []) + held += [w for w in where if w not in held] + return out + + +def _catalogued_needs(report: dict | None) -> dict[tuple[str, str], list[str]]: + """(profile, file name casefolded) -> where a dump catalog or an + imported romset lists that file, from a provenance report built with + the profiles' needs.""" + return { + need: [f"{escape_tags(where)} `{escape_tags(name)}`" for where, name in listed] + for need, listed in catalog_listings(report, PROVENANCE_LABELS).items() + } + + +# GitHub's upload page for a folder of bios/: a browser upload by someone +# without write access lands on a fork and opens a pull request. +UPLOAD_URL = f"{sitewanted.UPLOAD_ROOT}bios" +# Rows of Files to source on one page: 601 on one page made a phone page +# 274,509 px long. +FILES_TO_SOURCE_PART = 100 +# The two other long tables, each on a page of its own. Emulator cards link +# the second. +PER_EMULATOR_STEM = "gaps-per-emulator" +NOT_COLLECTED_STEM = "gaps-not-collected" + + +@dataclass +class _MissingFiles: + """The files to find, one row each, and the entries they come from.""" + + rows: list[dict] = dataclasses.field(default_factory=list) + entries: int = 0 + bundled: set[tuple[str, str]] = dataclasses.field(default_factory=set) + + +def missing_files(emulator_gaps: list[tuple[str, dict]]) -> _MissingFiles: + """One row per file to find: a name two emulators share is one file + only when both declare the same hash. Keyed by name alone, Fallout + 2's master.dat vanished behind Fallout 1's, and the three Sonic + decompilations' Data.rsdk showed as one.""" + found = _MissingFiles() + by_identity: dict[tuple[str, str], dict] = {} + for emu_name, data in emulator_gaps: + for g in data["gap_details"]: + if g["source"] != "missing": + continue + if g.get("bundled"): + # It arrives with the emulator's own package, which is + # why the collection documents it and does not hold it: + # asking readers to source it sent them after a file + # every install already has. + found.bundled.add((data["emulator"], g["name"])) + continue + found.entries += 1 + key = (g["name"], g.get("identity") or f"emulator:{emu_name}") + row = by_identity.get(key) + if row is None: + row = by_identity[key] = { + "name": g["name"], + "path": g.get("path") or g["name"], + "identity": g.get("identity", ""), + "profile_path": g.get("profile_path", ""), + "emulators": [data["emulator"]], + "emu_keys": [emu_name], + "required": g["required"], + "source_ref": g["source_ref"], + "platforms": set(g.get("platforms") or ()), + } + found.rows.append(row) + elif emu_name not in row["emu_keys"]: + row["emulators"].append(data["emulator"]) + row["emu_keys"].append(emu_name) + row["required"] = row["required"] or g["required"] + row["platforms"].update(g.get("platforms") or ()) + return found + + +@dataclass(frozen=True) +class SourceListing: + """Where the list of files to source goes. With ``moved``, the list goes + to pages of its own, keyed by stem: on the page it made 662 KB of HTML. + ``placer`` gives each file to source the folder its upload goes to, the + one validate_pr asks for. Without it the link opens bios/.""" + + moved: dict[str, str] | None = None + placer: sitewanted.Placer | None = None + + +def source_row(m: dict, profiles: dict, placer: sitewanted.Placer | None) -> str: + """The row of one file to source, with the platforms the gap report + found needing it.""" + plats = sorted(m["platforms"]) + plat_badges = ( + " ".join( + f'{p}' + for p in plats + ) + if plats + else "-" + ) + req = "yes" if m["required"] else "no" + algorithm, _, value = m["identity"].partition(":") + expected = f"{algorithm} {short_hash(value)}" if value else "-" + destination = code_span(m["path"]) if m["path"] != m["name"] else "-" + emulators = ", ".join( + f"[{escape_tags(display)}](emulators/{key}.md)" + for display, key in zip(m["emulators"], m["emu_keys"]) + ) + owner = profiles[m["emu_keys"][0]] + declared = sitewanted.gap_entries(owner, m, False) + folder = placer.folder(declared[0]) if placer and declared else "" + upload = sitewanted.upload_href(sitewanted.UPLOAD_ROOT, folder) + return ( + f"| `{m['name']}` [Have it? Upload]({upload}) | {destination} | {expected} " + f"| {emulators} | {req} | {plat_badges} | " + f"{source_ref_markdown(owner, m['source_ref'])} |" + ) + + +def source_counted(missing: _MissingFiles) -> str: + """How many files there are to source, and the entries they come from.""" + req_src = [m for m in missing.rows if m["required"]] + return ( + f"{count_text(len(missing.rows), 'file')}, {len(req_src)} required." + + ( + f" They come from {count_text(missing.entries, 'entry', 'entries')}: a file " + "declared with the same hash at several places is listed once." + if missing.entries != len(missing.rows) else "" + ) + ) + + +def source_table(counted: str, rows: list[str], moved: dict[str, str] | None) -> list[str]: + """The table of files to source, on the page or on pages of its own.""" + head = [ + "| File | Destination | Expected | Emulator | Required | Affects platforms | Source ref |", + "|------|-------------|----------|----------|----------|------------------|-----------|", + ] + if moved is None: + return [*head, *rows, ""] + where = list_pages( + "gaps-files-to-source", "Files to source", + f"{counted} Each is a file an emulator loads that no platform lists and " + "the collection does not hold. Part of " + "[What the packs do not hold](gaps.md#files-to-source).", + head, [rows[i:i + FILES_TO_SOURCE_PART] for i in range( + 0, len(rows), FILES_TO_SOURCE_PART)], moved, budget=1, + parent=("What the packs do not hold", "/gaps/"), + ) + return [f"Listed on {where}.", ""] + + +def bundled_note(bundled_rows: set[tuple[str, str]]) -> list[str]: + """The files that arrive with their emulator, counted, not listed.""" + if not bundled_rows: + return [] + emulators = sorted({emulator for emulator, _name in bundled_rows}) + return [ + f"{len(bundled_rows)} further files arrive with their emulator's own " + f"package ({escape_tags(', '.join(emulators))}): documented in the profile, not " + "collected, and not listed here.", + "", + ] + + +def undeclared_gaps(report_all: dict) -> tuple[dict[str, int], int, list[tuple[str, dict]]]: + """The files emulators load that no platform lists: counts by source, + the total, and the emulators that have any.""" + src_totals: dict[str, int] = { + "bios": 0, "data": 0, "large_file": 0, "bundled": 0, "missing": 0, + } + total_undeclared = 0 + emulator_gaps = [] + for emu_name, data in sorted(report_all.items()): + if data["gaps"] == 0: + continue + total_undeclared += data["gaps"] + for key, count in gap_source_counts(data).items(): + src_totals[key] += count + emulator_gaps.append((emu_name, data)) + return src_totals, total_undeclared, emulator_gaps + + +def _complement_rows(emulator_gaps: list[tuple[str, dict]]) -> list[str]: + """One row an emulator: its undeclared files by source.""" + rows = [] + for emu_name, data in sorted(emulator_gaps, key=lambda x: -x[1]["gaps"]): + display = data["emulator"] + sources = gap_source_counts(data) + to_source = sources["missing"] + missing_str = ( + f'{to_source}' + if to_source > 0 + else '0' + ) + rows.append( + f"| [{display}](emulators/{emu_name}.md) " + f"| {data['gaps']} " + f"| {sources['bios']} " + f"| {sources['data']} " + f"| {sources['large_file']} " + f"| {sources['bundled']} " + f"| {missing_str} |" + ) + return rows + + +def _moved_table(stem: str, title: str, intro: str, head: list[str], rows: list[str], noun: str, + moved: dict[str, str] | None) -> list[str]: + """A table on the gaps page, or on a page of its own with a line here. + Two tables of 340 and 283 rows held most of the gaps page's 8,300 + elements: their first layout was a 200 ms task on a phone.""" + if moved is None: + return [*head, *rows, ""] + where = list_pages(stem, title, intro, head, [rows], moved, budget=1, + parent=("What the packs do not hold", "/gaps/")) + return [f"{count_text(len(rows), noun)}, listed on {where}.", ""] + + +def complement_intro(src_totals: dict[str, int], total_undeclared: int, + emulator_gaps: list[tuple[str, dict]], + moved: dict[str, str] | None = None) -> list[str]: + """Section 3 up to its per-emulator table: what the emulators load + that no platform lists, and where those files come from.""" + total_available = ( + src_totals["bios"] + src_totals["data"] + src_totals["large_file"] + ) + pct_available = ( + f"{total_available / total_undeclared * 100:.0f}%" + if total_undeclared + else "0%" + ) + return [ + "## Files emulators load that no platform lists { #core-complement }", + "", + f"Files loaded by emulators but not declared by any platform. " + f"{total_undeclared:,} files across {count_text(len(emulator_gaps), 'emulator')}, " + f"{total_available:,} available ({pct_available}), " + f"{src_totals['bundled']:,} installed with their emulator, " + f"{src_totals['missing']:,} to source.", + "", + "This counts every profiled emulator, including those no platform " + "ships yet, so it reaches past what the first table above counts: " + "it covers only the emulators each platform actually ships. " + "Whatever is not in the collection is an acquisition target, named " + "per emulator below.", + "", + "### Where the files come from", + "", + "| Source | Count | Description |", + "|--------|------:|-------------|", + f"| bios/ | {src_totals['bios']} | In repository (database.json) |", + f"| data/ | {src_totals['data']} | Data directories (buildbot, GitHub) |", + f"| release | {src_totals['large_file']} " + "| GitHub release assets (large files) |", + f"| bundled | {src_totals['bundled']} " + "| Installed with the emulator's own package, not collected |", + f"| missing | {src_totals['missing']} | Not available, needs sourcing |", + "", + "### Per emulator", + "", + *_moved_table( + PER_EMULATOR_STEM, "Files emulators load, per emulator", + f"For each of {count_text(len(emulator_gaps), 'emulator')}, the files it loads " + "that no platform lists, counted by where they come from. Part of " + "[What the packs do not hold](gaps.md#per-emulator).", + ["| Emulator | Undeclared | bios | data | release | Bundled | Missing |", + "|----------|----------:|-----:|-----:|--------:|--------:|--------:|"], + _complement_rows(emulator_gaps), "emulator", moved), + ] + + +def not_collected_section(report_all: dict, profiles: dict, catalogued: dict | None, + moved: dict[str, str] | None = None) -> list[str]: + """Section 4: files the collection does not hold yet (unsourceable).""" + all_unsourceable: list[dict] = [ + { + "name": u["name"], + "emulator": data["emulator"], + "emu_key": emu_name, + "reason": u["reason"], + "source_ref": u.get("source_ref", ""), + # The wanted page's own rule, on the entries behind the row. + "wanted": any(sendable(entry, str(u["reason"])) for entry in sitewanted.gap_entries( + profiles.get(emu_name) or {}, u, True)), + } + for emu_name, data in sorted(report_all.items()) + for u in data.get("unsourceable", []) + ] + if not all_unsourceable: + return [] + listed = _catalogued_needs(catalogued) + # The old heading's address still leads here. + lines = [ + '', + "", + "## Not collected yet", + "", + f"{len(all_unsourceable)} files the collection does not hold. A file " + "with the same name is never served in their place. The [wanted " + f"page](wanted.md) asks for the {sum(u['wanted'] for u in all_unsourceable)} " + "marked wanted. No one can send the others: a name the code builds, a " + "file no copy of which can be shared, game data, or a file the emulator " + "installs itself. \"Listed in\" names a catalog or romset that lists a file.", + "", + ] + rows = [] + for u in sorted(all_unsourceable, key=lambda x: x["name"]): + where = listed.get((u["emu_key"], str(u["name"]).casefold()), []) + rows.append( + f"| `{u['name']}` | {u['emulator']} | {reason_cell(u['reason'])} " + f"| {source_ref_markdown(profiles[u['emu_key']], u['source_ref'])} " + f"| {', '.join(where) or '-'} | {'yes' if u['wanted'] else 'no'} |" + ) + lines.extend(_moved_table( + NOT_COLLECTED_STEM, "Files not collected yet", + f"{count_text(len(rows), 'file')} the collection does not hold, each with the " + "emulator that loads it, why it is not collected, the catalog or romset " + "that lists it and whether the [wanted page](wanted.md) asks for it. Part of " + "[What the packs do not hold](gaps.md#not-collected-yet).", + ["| File | Emulator | Reason | Source ref | Listed in | Wanted |", + "|------|----------|--------|-----------|-----------|--------|"], + rows, "file", moved)) + return lines diff --git a/scripts/sitegen/parts.py b/scripts/sitegen/parts.py index 3ba7bcf2b..7d5a26d67 100644 --- a/scripts/sitegen/parts.py +++ b/scripts/sitegen/parts.py @@ -9,8 +9,8 @@ from typing import TypeVar from core.paths import REPO_ROOT from sitegen import starlight as sitestarlight -from sitegen.config import date_line -from sitegen.decorate import front_matter +from sitegen.config import date_line, yaml +from sitegen.decorate import DEMOTED_WEIGHT, SEARCH_WEIGHT, front_matter # A platform's file lists are split by the share of a page they render to, @@ -172,3 +172,23 @@ def list_pages( if len(stems) == 1: return f"[a page of their own]({stems[0]}.md)" return "pages of their own: " + part_links(stems) + + +def part_front_matter(parent: tuple[str, str], siblings: list[tuple[str, str]], + index: int, front: dict | None = None) -> list[str]: + """The front matter of part ``index`` of ``siblings`` ((label, link) + each): the page it belongs to, its neighbours and the part weight. + + MAME's eight card pages had no parent, so the crumbs skipped MAME, and + `prev: false`, so part 5 reached part 6 only through a sentence. + The first part's previous page is the parent, the last part has no next. + """ + data = dict(front or {}) + data["parent"] = {"label": parent[0], "link": parent[1]} + before = siblings[index - 1] if index > 0 else parent + data["prev"] = {"label": before[0], "link": before[1]} + data["next"] = ({"label": siblings[index + 1][0], "link": siblings[index + 1][1]} + if index + 1 < len(siblings) else False) + data["searchWeight"] = SEARCH_WEIGHT.get("part", DEMOTED_WEIGHT) + return ["---", yaml.safe_dump(data, sort_keys=False, allow_unicode=True).rstrip("\n"), + "---", ""] diff --git a/scripts/sitegen/sidebartopics.py b/scripts/sitegen/sidebartopics.py new file mode 100644 index 000000000..98a08309a --- /dev/null +++ b/scripts/sitegen/sidebartopics.py @@ -0,0 +1,214 @@ +"""The navigation as Starlight sidebar topics, one per tab, with the reading order through them.""" + +from __future__ import annotations + +import re +from collections.abc import Iterator +from dataclasses import dataclass, field +from pathlib import PurePosixPath + +from core.anchors import toc_slug +from sitegen.config import BASE +from sitegen.starlight import page_url, reads_in_order + + +# Navigation + + +def _sidebar_link(rel: str) -> str: + return page_url(rel)[len(BASE) - 1:] + + +# Tabs whose groups hold pages by the hundred (every system, every +# emulator): a group that does not hold the current page is drawn as one +# link to its overview, so an emulator page does not carry the links of +# every other emulator. +PRUNED_TABS = ("explore",) + +# Reading runs from one tab into the next only here: the last Start here +# page leads to Setups. Every other tab is read on its own. +CHAINED_TABS = (("start-here", "setups"),) + + +def topic_id(label: str) -> str: + return re.sub(r"[^a-z]+", "-", label.lower()).strip("-") + + +_DIGIT_RANGE = re.compile(r"[0-9] to [0-9]") + + +def by_initial(label: str, children: list[dict]) -> bool: + """A group that files its pages by the first character of their names + (A, B, "0 to 9"): a way through a long list, not a place, so it is no + crumb.""" + if not children or any("items" in child for child in children): + return False + firsts = {str(child["label"])[:1].upper() for child in children} + if len(label) == 1: + return firsts == {label} + return bool(_DIGIT_RANGE.fullmatch(label)) and not any("A" <= first <= "Z" for first in firsts) + + +def sidebar(nav: list, present: set[str], anchors: dict[str, set[str]] | None = None) -> dict: + """The navigation as Starlight topics, one per tab, with what the route + middleware (website/src/routeData.ts) reads beside it. + + A page the navigation does not list (the parts of a split page) joins + the topic that holds most pages of its directory. In a directory the + navigation lists nothing of (get/), it joins the topic of the pages of + the same name, and a page with neither joins the first topic: no page + is left out of every tab. + + A group that files names by their first letter is marked `crumb: false`: + the breadcrumbs skip it. + + `groups` gives each group, keyed by the labels from its tab down, the + page that introduces it: its own overview page, or the heading named + after it on the overview above it (`anchors` lists each page's heading + ids). A group with neither has no address, never the address of its + first page, which is a sibling of the page being read. `prune` marks the + groups drawn as one link when they do not hold the current page. + + `reading` is the order of the previous and next links, one list per run + of tabs read in sequence. + """ + walk = _NavWalk(present, anchors or {}) + topics = [] + for tab in nav: + (label, value), = tab.items() + topic = topic_id(label) + children = [child for child in (walk.item(v, topic, (label,), _overview_of(value)) for v in value) + if child] + if children: + topics.append({"id": topic, "label": label, "link": next(_links(children))["link"], + "items": children}) + extra = _unlisted_pages(walk.owner, present, topics) + return {"topics": topics, "options": {"topics": extra, "exclude": []}, + "groups": walk.groups, "reading": _reading(nav, present)} + + +def _overview_of(value: list) -> str | None: + return next((v for v in value if isinstance(v, str)), None) + + +@dataclass +class _NavWalk: + """The sidebar items of the navigation, the topic of each page it + lists, and the entry of each group in `groups`.""" + present: set[str] + anchors: dict[str, set[str]] + owner: dict[str, str] = field(default_factory=dict) + groups: dict[str, dict] = field(default_factory=dict) + + def item(self, entry: str | dict, topic: str, trail: tuple[str, ...], + parent: str | None) -> dict | None: + if isinstance(entry, str): + self.owner[entry] = topic + return {"label": "Overview", "link": _sidebar_link(entry)} if entry in self.present else None + (label, value), = entry.items() + if isinstance(value, str): + if value.startswith("http"): + return {"label": label, "link": value} + self.owner[value] = topic + return {"label": label, "link": _sidebar_link(value)} if value in self.present else None + if "/" in label: + raise ValueError(f"a navigation group label holds a slash: {label!r}") + own = _overview_of(value) + here = (*trail, label) + href = self._group_href(label, own, parent, topic) + children = [child for child in (self.item(v, topic, here, own or parent) for v in value) if child] + if not children: + return None + self.groups["/".join(here)] = {"href": href, "prune": topic in PRUNED_TABS and href is not None, + "crumb": not by_initial(label, children)} + return {"label": label, "items": children, "collapsed": True} + + def _group_href(self, label: str, own: str | None, parent: str | None, topic: str) -> str | None: + if own and own in self.present: + return page_url(own) + if parent and parent in self.present: + anchor = toc_slug(label) + if anchor in self.anchors.get(parent, set()): + return f"{page_url(parent)}#{anchor}" + if topic in PRUNED_TABS: + # Drawn as a link, it needs an address: the overview it + # sits under, never one of its own pages. + return page_url(parent) + return None + + +def _unlisted_pages(owner: dict[str, str], present: set[str], topics: list[dict]) -> dict[str, list[str]]: + """The pages each topic holds beyond the ones the navigation lists.""" + votes: dict[str, dict[str, int]] = {} + for rel, topic in owner.items(): + tally = votes.setdefault(rel.rpartition("/")[0], {}) + tally[topic] = tally.get(topic, 0) + 1 + # The page a stale link lands on opens on the first tab: its sidebar + # is the way back in. Excluded from every tab, the theme named the tabs + # by their position, 0 to 4. + extra: dict[str, list[str]] = {topics[0]["id"]: ["/404"]} if topics else {} + # A folder the navigation lists nothing of (get/, one download page per + # setup) has no vote, and excluded from every tab its pages had the + # tabs numbered 0 to 4 too. Its pages take the tab of the pages of the + # same name (get/batocera.md, platforms/batocera.md), and its overview + # the tab its pages took. + by_name: dict[str, dict[str, int]] = {} + for rel, topic in owner.items(): + tally = by_name.setdefault(PurePosixPath(rel).name, {}) + tally[topic] = tally.get(topic, 0) + 1 + unlisted = sorted(present - owner.keys()) + adopted: dict[str, dict[str, int]] = {} + for rel in unlisted: + folder, name = rel.rpartition("/")[0], PurePosixPath(rel).name + if folder in votes or name == "index.md": + continue + tally = adopted.setdefault(folder, {}) + for topic, count in by_name.get(name, {}).items(): + tally[topic] = tally.get(topic, 0) + count + for rel in unlisted: + folder = rel.rpartition("/")[0] + chosen = votes.get(folder) or adopted.get(folder) + if chosen: + topic = max(chosen, key=chosen.__getitem__) + elif topics: + topic = topics[0]["id"] + else: + continue + extra.setdefault(topic, []).append("/" + (_sidebar_link(rel).strip("/") or "index")) + return extra + + +def _reading(nav: list, present: set[str]) -> list[list[dict]]: + """The previous and next links, in runs. An overview is named after the + group or tab it opens ("Setups", not "Overview").""" + def walk(value: list, name: str) -> Iterator[dict]: + for entry in value: + if isinstance(entry, str): + if entry in present and reads_in_order(entry): + yield {"label": name, "link": page_url(entry)} + continue + (label, target), = entry.items() + if isinstance(target, list): + yield from walk(target, label) + elif not target.startswith("http") and target in present and reads_in_order(target): + yield {"label": label, "link": page_url(target)} + + tabs = {topic_id(label): list(walk(value, label)) + for tab in nav for label, value in tab.items()} + runs: list[list[dict]] = [] + previous = "" + for tab, pages in tabs.items(): + if runs and (previous, tab) in CHAINED_TABS: + runs[-1].extend(pages) + else: + runs.append(list(pages)) + previous = tab + return [run for run in runs if run] + + +def _links(items: list[dict]) -> Iterator[dict]: + for entry in items: + if "link" in entry: + yield entry + else: + yield from _links(entry["items"]) diff --git a/scripts/sitegen/starlight.py b/scripts/sitegen/starlight.py index 047bdd490..676445933 100644 --- a/scripts/sitegen/starlight.py +++ b/scripts/sitegen/starlight.py @@ -15,8 +15,8 @@ import html import json import re import urllib.parse -from collections.abc import Callable, Iterator, Mapping -from dataclasses import dataclass, field +from collections.abc import Callable, Mapping +from dataclasses import dataclass from html import unescape from pathlib import Path, PurePosixPath @@ -636,28 +636,6 @@ def _neighbours(front: dict, rel: str, body: str, authored: dict) -> None: front[side] = _neighbour(rel, authored[side]) -# Navigation - - -def _sidebar_link(rel: str) -> str: - return page_url(rel)[len(BASE) - 1:] - - -# Tabs whose groups hold pages by the hundred (every system, every -# emulator): a group that does not hold the current page is drawn as one -# link to its overview, so an emulator page does not carry the links of -# every other emulator. -PRUNED_TABS = ("explore",) - -# Reading runs from one tab into the next only here: the last Start here -# page leads to Setups. Every other tab is read on its own. -CHAINED_TABS = (("start-here", "setups"),) - - -def topic_id(label: str) -> str: - return re.sub(r"[^a-z]+", "-", label.lower()).strip("-") - - def heading_ids(text: str) -> set[str]: """The anchors a page's headings carry, as written by pin_heading_ids.""" ids = {match[1] for match in re.finditer(r"\{[^{}\n]*#([^\s}]+)[^{}\n]*\}[ \t]*$", text, re.M)} @@ -671,178 +649,6 @@ def reads_in_order(rel: str) -> bool: return not rel.startswith(CARD_PAGES) or rel.endswith("/index.md") -_DIGIT_RANGE = re.compile(r"[0-9] to [0-9]") - - -def by_initial(label: str, children: list[dict]) -> bool: - """A group that files its pages by the first character of their names - (A, B, "0 to 9"): a way through a long list, not a place, so it is no - crumb.""" - if not children or any("items" in child for child in children): - return False - firsts = {str(child["label"])[:1].upper() for child in children} - if len(label) == 1: - return firsts == {label} - return bool(_DIGIT_RANGE.fullmatch(label)) and not any("A" <= first <= "Z" for first in firsts) - - -def sidebar(nav: list, present: set[str], anchors: dict[str, set[str]] | None = None) -> dict: - """The navigation as Starlight topics, one per tab, with what the route - middleware (website/src/routeData.ts) reads beside it. - - A page the navigation does not list (the parts of a split page) joins - the topic that holds most pages of its directory. In a directory the - navigation lists nothing of (get/), it joins the topic of the pages of - the same name, and a page with neither joins the first topic: no page - is left out of every tab. - - A group that files names by their first letter is marked `crumb: false`: - the breadcrumbs skip it. - - `groups` gives each group, keyed by the labels from its tab down, the - page that introduces it: its own overview page, or the heading named - after it on the overview above it (`anchors` lists each page's heading - ids). A group with neither has no address, never the address of its - first page, which is a sibling of the page being read. `prune` marks the - groups drawn as one link when they do not hold the current page. - - `reading` is the order of the previous and next links, one list per run - of tabs read in sequence. - """ - walk = _NavWalk(present, anchors or {}) - topics = [] - for tab in nav: - (label, value), = tab.items() - topic = topic_id(label) - children = [child for child in (walk.item(v, topic, (label,), _overview_of(value)) for v in value) - if child] - if children: - topics.append({"id": topic, "label": label, "link": next(_links(children))["link"], - "items": children}) - extra = _unlisted_pages(walk.owner, present, topics) - return {"topics": topics, "options": {"topics": extra, "exclude": []}, - "groups": walk.groups, "reading": _reading(nav, present)} - - -def _overview_of(value: list) -> str | None: - return next((v for v in value if isinstance(v, str)), None) - - -@dataclass -class _NavWalk: - """The sidebar items of the navigation, the topic of each page it - lists, and the entry of each group in `groups`.""" - present: set[str] - anchors: dict[str, set[str]] - owner: dict[str, str] = field(default_factory=dict) - groups: dict[str, dict] = field(default_factory=dict) - - def item(self, entry: str | dict, topic: str, trail: tuple[str, ...], - parent: str | None) -> dict | None: - if isinstance(entry, str): - self.owner[entry] = topic - return {"label": "Overview", "link": _sidebar_link(entry)} if entry in self.present else None - (label, value), = entry.items() - if isinstance(value, str): - if value.startswith("http"): - return {"label": label, "link": value} - self.owner[value] = topic - return {"label": label, "link": _sidebar_link(value)} if value in self.present else None - if "/" in label: - raise ValueError(f"a navigation group label holds a slash: {label!r}") - own = _overview_of(value) - here = (*trail, label) - href = self._group_href(label, own, parent, topic) - children = [child for child in (self.item(v, topic, here, own or parent) for v in value) if child] - if not children: - return None - self.groups["/".join(here)] = {"href": href, "prune": topic in PRUNED_TABS and href is not None, - "crumb": not by_initial(label, children)} - return {"label": label, "items": children, "collapsed": True} - - def _group_href(self, label: str, own: str | None, parent: str | None, topic: str) -> str | None: - if own and own in self.present: - return page_url(own) - if parent and parent in self.present: - anchor = toc_slug(label) - if anchor in self.anchors.get(parent, set()): - return f"{page_url(parent)}#{anchor}" - if topic in PRUNED_TABS: - # Drawn as a link, it needs an address: the overview it - # sits under, never one of its own pages. - return page_url(parent) - return None - - -def _unlisted_pages(owner: dict[str, str], present: set[str], topics: list[dict]) -> dict[str, list[str]]: - """The pages each topic holds beyond the ones the navigation lists.""" - votes: dict[str, dict[str, int]] = {} - for rel, topic in owner.items(): - tally = votes.setdefault(rel.rpartition("/")[0], {}) - tally[topic] = tally.get(topic, 0) + 1 - # The page a stale link lands on opens on the first tab: its sidebar - # is the way back in. Excluded from every tab, the theme named the tabs - # by their position, 0 to 4. - extra: dict[str, list[str]] = {topics[0]["id"]: ["/404"]} if topics else {} - # A folder the navigation lists nothing of (get/, one download page per - # setup) has no vote, and excluded from every tab its pages had the - # tabs numbered 0 to 4 too. Its pages take the tab of the pages of the - # same name (get/batocera.md, platforms/batocera.md), and its overview - # the tab its pages took. - by_name: dict[str, dict[str, int]] = {} - for rel, topic in owner.items(): - tally = by_name.setdefault(PurePosixPath(rel).name, {}) - tally[topic] = tally.get(topic, 0) + 1 - unlisted = sorted(present - owner.keys()) - adopted: dict[str, dict[str, int]] = {} - for rel in unlisted: - folder, name = rel.rpartition("/")[0], PurePosixPath(rel).name - if folder in votes or name == "index.md": - continue - tally = adopted.setdefault(folder, {}) - for topic, count in by_name.get(name, {}).items(): - tally[topic] = tally.get(topic, 0) + count - for rel in unlisted: - folder = rel.rpartition("/")[0] - chosen = votes.get(folder) or adopted.get(folder) - if chosen: - topic = max(chosen, key=chosen.__getitem__) - elif topics: - topic = topics[0]["id"] - else: - continue - extra.setdefault(topic, []).append("/" + (_sidebar_link(rel).strip("/") or "index")) - return extra - - -def _reading(nav: list, present: set[str]) -> list[list[dict]]: - """The previous and next links, in runs. An overview is named after the - group or tab it opens ("Setups", not "Overview").""" - def walk(value: list, name: str) -> Iterator[dict]: - for entry in value: - if isinstance(entry, str): - if entry in present and reads_in_order(entry): - yield {"label": name, "link": page_url(entry)} - continue - (label, target), = entry.items() - if isinstance(target, list): - yield from walk(target, label) - elif not target.startswith("http") and target in present and reads_in_order(target): - yield {"label": label, "link": page_url(target)} - - tabs = {topic_id(label): list(walk(value, label)) - for tab in nav for label, value in tab.items()} - runs: list[list[dict]] = [] - previous = "" - for tab, pages in tabs.items(): - if runs and (previous, tab) in CHAINED_TABS: - runs[-1].extend(pages) - else: - runs.append(list(pages)) - previous = tab - return [run for run in runs if run] - - # Addresses that once held a page, and where its content went. MOVED_PAGES = {"wiki/getting-started.md": "which-pack.md"} @@ -890,14 +696,6 @@ def redirects(profiles: dict, present: set[str], return out -def _links(items: list[dict]) -> Iterator[dict]: - for entry in items: - if "link" in entry: - yield entry - else: - yield from _links(entry["items"]) - - # The picker's data diff --git a/tests/sources.py b/tests/sources.py index e350c6037..97e94991c 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -84,6 +84,8 @@ COMMANDS = { "sitegen/startwith.py", "sitegen/systempages.py", "sitegen/emulatorcards.py", "sitegen/filebadges.py", "sitegen/emulatormetadata.py", "sitegen/emulatorpage.py", "sitegen/gaps.py", "sitegen/crossref.py", "sitegen/reference.py", + "sitegen/emulatorintro.py", "sitegen/emulatordata.py", "sitegen/gapproblems.py", + "sitegen/gapsources.py", "sitegen/exportrows.py", "sitegen/whichpack.py", "sitegen/nav.py", "sitegen/build.py", "sitegen/coverage.py", "sitegen/extraction.py", "sitegen/releasepacks.py", "sitegen/archivecounts.py", "packs/crossref.py", diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index d3b091005..1e208e9bd 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -4748,16 +4748,16 @@ class TheSiteCountsSlotsNotVersions(unittest.TestCase): 59 files, 46 missing, where verify --emulator said 23 slots, 12 missing.""" def test_one_held_version_fills_the_slot(self): - from scripts.sitegen.emulatorpage import _emulator_file_summary, _emulator_held_line + from scripts.sitegen.emulatorintro import emulator_file_summary, emulator_held_line files = [ {"name": "DUKE3D.GRP", "crc32": "1"}, {"name": "DUKE3D.GRP", "crc32": "2"}, {"name": "BLOOD.RFF", "crc32": "3"}, ] - line = _emulator_file_summary(files)[0] + line = emulator_file_summary(files)[0] self.assertIn("**2 files** (3 accepted versions)", line) - held = _emulator_held_line(files, lambda f: f.get("crc32") == "2")[0] + held = emulator_held_line(files, lambda f: f.get("crc32") == "2")[0] self.assertIn("1 in repo and 1 missing", held) @@ -5677,9 +5677,9 @@ class BundledFilesAreNotToSource(unittest.TestCase): self.assertNotIn("n64.psh", summary) def test_the_site_gives_it_its_own_status(self): - from sitegen import dataexports + from sitegen import exportrows - rows = dataexports._gap_export_rows({}, {"daedalusx64": { + rows = exportrows.gap_export_rows({}, {"daedalusx64": { "emulator": "DaedalusX64", "systems": ["nintendo-64"], "gap_details": [{"name": "n64.psh", "source": "missing", "required": True, "in_repo": False, "bundled": True}], @@ -5809,13 +5809,13 @@ class GapsPageCountsOneWay(unittest.TestCase): of the same platform already holds.""" def test_settled_declarations_are_listed_apart(self): - from scripts.sitegen.gaps import _render_problem_files + from scripts.sitegen.gapproblems import render_problem_files problems = [{"platform": "RetroDECK", "name": "dsifirmware.bin", "status": "untested", "required": True, "reason": "x", "discrepancy": ""}] settled = [{"platform": "RetroDECK", "name": "cdibios.zip", "status": "untested", "held_by": "arcade"}] - text = "\n".join(_render_problem_files(problems, settled)) + text = "\n".join(render_problem_files(problems, settled)) self.assertIn("0 missing, 1 untested", text) self.assertIn("Other revisions of a held destination", text) self.assertIn("`cdibios.zip`", text) @@ -5823,12 +5823,12 @@ class GapsPageCountsOneWay(unittest.TestCase): def test_missing_says_the_destination_count_of_the_opening_sentence(self): # The page opened on "48 are missing" (by destination) above a # heading that said "10 files": one row per name. - from scripts.sitegen.gaps import _render_problem_files + from scripts.sitegen.gapproblems import render_problem_files problems = [{"platform": "AmberELEC", "name": "hardwareconfig.xml", "status": "missing", "required": True, "reason": "", "discrepancy": "", "category": "unread"}] * 3 - text = "\n".join(_render_problem_files(problems, missing_total=3)) + text = "\n".join(render_problem_files(problems, missing_total=3)) self.assertIn("3 missing under 1 name,", text) self.assertIn('rb-badge-danger">1 name', text) self.assertNotIn("1 missing", text) @@ -5836,13 +5836,13 @@ class GapsPageCountsOneWay(unittest.TestCase): def test_a_missing_row_links_each_entry_and_names_its_folder(self): """The row said `N88_KNJ1.ROM | unread | yes | AmberELEC` in plain text: neither where the list puts it nor which cores were examined.""" - from scripts.sitegen.gaps import _render_problem_files + from scripts.sitegen.gapproblems import render_problem_files problems = [{"platform": "AmberELEC", "platform_key": "amberelec", "name": "N88_KNJ1.ROM", "status": "missing", "required": True, "reason": "", "discrepancy": "", "category": "unread", "system": "nec-pc-88", "destination": "bios/quasi88/N88_KNJ1.ROM"}] - text = "\n".join(_render_problem_files(problems)) + text = "\n".join(render_problem_files(problems)) self.assertIn("| [AmberELEC](platforms/amberelec.md#nec-pc-88) " "`bios/quasi88/N88_KNJ1.ROM` |", text) diff --git a/tests/test_cross_reference_sources.py b/tests/test_cross_reference_sources.py index 90eca1f75..e46b7ac3a 100644 --- a/tests/test_cross_reference_sources.py +++ b/tests/test_cross_reference_sources.py @@ -170,10 +170,10 @@ class PlatformScopedEntries(unittest.TestCase): def test_the_page_and_the_text_count_sources_alike(self): """The gaps page kept a held bundled file under bios where the text report counted it bundled: 410 files in different columns.""" - from sitegen import gaps + from sitegen import gapsources report = cross_reference(self.PROFILES, {}, self.DB, platform="plat") - totals, _total, _rows = gaps._undeclared_gaps(report) + totals, _total, _rows = gapsources.undeclared_gaps(report) self.assertEqual(totals["bundled"], 1) self.assertEqual(totals["bios"], 0) self.assertEqual(totals["missing"], 1) diff --git a/tests/test_provenance.py b/tests/test_provenance.py index f4fe1f819..e6a77fc68 100644 --- a/tests/test_provenance.py +++ b/tests/test_provenance.py @@ -717,7 +717,7 @@ class TheWantedPageAsksOnlyForWhatCannotBeMade(unittest.TestCase): already produces (a Kickstart's odd bytes, a character ROM's halves).""" def test_a_derivable_dump_moves_out_of_the_wanted_list(self): - from scripts.sitegen import dataexports, provenance as sitegen_provenance + from scripts.sitegen import exportrows, provenance as sitegen_provenance report = {"tosec": { "imported_at": "2026-01-01", "dats": {}, "total": 2, "matched": 0, @@ -734,7 +734,7 @@ class TheWantedPageAsksOnlyForWhatCannotBeMade(unittest.TestCase): # The report stays whole: the coverage table and the gaps page # count every missing dump. self.assertEqual(len(report["tosec"]["missing"]), 2) - rows = dataexports._provenance_wanted_rows(dumps) + rows = exportrows.provenance_wanted_rows(dumps) self.assertEqual([row["name"] for row in rows], ["lost.rom"]) wanted, _, derived = page.partition("## Derivable") self.assertIn("**1** dumps a catalog", wanted) diff --git a/tests/test_site_emulators.py b/tests/test_site_emulators.py index cea25a6df..51cf88e5b 100644 --- a/tests/test_site_emulators.py +++ b/tests/test_site_emulators.py @@ -43,6 +43,8 @@ from sitegen import emulatorcards from sitegen import emulatormetadata from sitegen import filebadges from sitegen import emulatorpage +from sitegen import emulatordata +from sitegen import emulatorintro from sitegen import emulatorsindex from sitegen import install as sitegen_install from sitegen import lookup @@ -86,7 +88,7 @@ class TheIntroSaysWhatIsNeeded(unittest.TestCase): # region fills it, and every member is marked required by the loader. profile = _profile("duckstation") members = [f for f in profile["files"] if f.get("group") == "ps-bios"] - intro = emulatorpage._emulator_intro("DuckStation", profile) + intro = emulatorintro.emulator_intro("DuckStation", profile) self.assertIn( f"It needs one BIOS for the game's region, among the {len(members)} it accepts.", intro) @@ -94,7 +96,7 @@ class TheIntroSaysWhatIsNeeded(unittest.TestCase): self.assertIn("DuckStation emulates Sony PlayStation.", intro) def test_three_required_bios_of_three_regions_read_as_one_choice(self): - intro = emulatorpage._emulator_intro("X", {"systems": ["sony-playstation"], "files": [ + intro = emulatorintro.emulator_intro("X", {"systems": ["sony-playstation"], "files": [ {"name": "j.bin", "required": True, "region": ["japan"]}, {"name": "u.bin", "required": True, "region": ["north-america"]}, {"name": "e.bin", "required": True, "region": ["europe"]}, @@ -104,16 +106,16 @@ class TheIntroSaysWhatIsNeeded(unittest.TestCase): self.assertNotIn("3 of them required", intro) def test_required_files_without_regions_keep_the_count(self): - intro = emulatorpage._emulator_intro("X", {"files": [ + intro = emulatorintro.emulator_intro("X", {"files": [ {"name": "a.bin", "required": True}, {"name": "b.bin"}]}) self.assertIn("It reads 2 files, 1 of them required", intro) def test_several_machines_say_who_needs_a_required_file(self): - intro = emulatorpage._emulator_intro("X", { + intro = emulatorintro.emulator_intro("X", { "systems": ["sony-playstation", "sega-saturn"], "files": [{"name": "a.bin", "required": True}]}) self.assertIn("A required file is needed only by the machines that use it.", intro) - one = emulatorpage._emulator_intro("X", { + one = emulatorintro.emulator_intro("X", { "systems": ["sony-playstation"], "files": [{"name": "a.bin", "required": True}]}) self.assertNotIn("machines that use it", one) @@ -205,7 +207,7 @@ class TheSummaryLineIsProse(unittest.TestCase): {"name": "a.pak", "category": "game_data"}, {"name": "b.pak", "category": "game_data"}] for f in files[:164]: f["required"] = True - text = "\n".join(emulatorpage._emulator_file_summary(files)) + text = "\n".join(emulatorintro.emulator_file_summary(files)) self.assertNotIn(" | ", text) self.assertNotIn("1399", text) self.assertIn("1,401 optional", text) @@ -368,7 +370,7 @@ class DataDirectoryPagesStayOutOfSearch(unittest.TestCase): registry = PageRegistry( data_members={"dolphin-sys": {"a.bin": {"sha1": "a" * 40, "size": 1}}}, data_readers={"dolphin-sys": [("dolphin-mmjr", "Dolphin MMJR"), ("dolphin", "Dolphin")]}) - page = emulatorpage._data_tree_page("dolphin-sys", {}, [("data-dolphin-sys", ["a.bin"])], 0, registry) + page = emulatordata._data_tree_page("dolphin-sys", {}, [("data-dolphin-sys", ["a.bin"])], 0, registry) front = yaml.safe_load(page.split("---\n")[1]) self.assertEqual(front["search"], "exclude") self.assertEqual(front["parent"], {"label": "Dolphin", "link": "dolphin.md"}) @@ -449,7 +451,7 @@ class AnAppThatReadsAnyBios(unittest.TestCase): self.assertIsNotNone(emulatorcards.any_name_bios(_profile("pcsx2"))) def test_the_download_links_the_collection_card(self): - steps = emulatorpage._any_name_steps("X", _profile("aethersx2"), + steps = emulatorintro._any_name_steps("X", _profile("aethersx2"), emulatorcards.any_name_bios(_profile("aethersx2")), "../systems/sony.md#sha1-abc") self.assertIn("1. Download [`ps2-0230a-20080220.bin`](../systems/sony.md#sha1-abc).", steps) @@ -488,7 +490,7 @@ class PartsKnowWhereTheySit(unittest.TestCase): registry = PageRegistry(data_members={ref: members}, data_readers={ref: [("x", "X")]}) pages = lookup.data_tree_pages(ref, members) self.assertEqual(len(pages), 3) - middle = _front(emulatorpage._data_tree_page(ref, {}, pages, 1, registry)) + middle = _front(emulatordata._data_tree_page(ref, {}, pages, 1, registry)) self.assertEqual(middle["parent"], {"label": "X", "link": "x.md"}) self.assertEqual(middle["prev"]["link"], f"{pages[0][0]}.md") self.assertEqual(middle["next"]["link"], f"{pages[2][0]}.md") @@ -704,7 +706,7 @@ class DataFolderPrinted(unittest.TestCase): def test_aethersx2_step_names_the_android_folder(self) -> None: profile = _profile("aethersx2") - steps = emulatorpage._any_name_steps("AetherSX2", profile, emulatorcards.any_name_bios(profile), "", "aethersx2") + steps = emulatorintro._any_name_steps("AetherSX2", profile, emulatorcards.any_name_bios(profile), "", "aethersx2") self.assertIn("2. Put it in this folder:", steps) self.assertIn("`Android/data/xyz.aethersx2.android/files/bios/`, on the internal storage.", steps) @@ -818,7 +820,7 @@ class SmallFixes(unittest.TestCase): def test_region_choice_summary(self) -> None: profile = _profile("duckstation") members = sum(1 for f in profile["files"] if f.get("group") == "ps-bios") - lines = emulatorpage._emulator_file_summary(profile["files"], profile.get("groups")) + lines = emulatorintro.emulator_file_summary(profile["files"], profile.get("groups")) self.assertIn(f"One of {members} is required, for the games' region.", lines[0]) self.assertNotIn(f"{members} required", lines[0]) @@ -826,7 +828,7 @@ class SmallFixes(unittest.TestCase): files = [{"name": "a.rom", "required": True, "group": "boot"}, {"name": "b.rom", "required": True, "group": "boot"}, {"name": "c.rom", "required": True}, {"name": "d.rom"}] - line = emulatorpage._emulator_file_summary(files, {"boot": {"required": True}})[0] + line = emulatorintro.emulator_file_summary(files, {"boot": {"required": True}})[0] self.assertIn("2 required, 1 optional. Any one file of a required set fills it.", line) def test_no_emulator_part_says_where_it_sits(self) -> None: diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py index 2ce6c7569..2c2446799 100644 --- a/tests/test_site_exports.py +++ b/tests/test_site_exports.py @@ -448,12 +448,12 @@ class TheGapsSayWhatToSupplyAndWhere(unittest.TestCase): the emulator page only, and Data.rsdk's three rows looked identical.""" def test_export_rows(self): - from sitegen.dataexports import _gap_export_rows + from sitegen.exportrows import gap_export_rows report = {"bstone": {"emulator": "BStone", "systems": ["blake-stone"], "gap_details": [ {"name": "EANIM.BS6", "path": "AOG/EANIM.BS6", "source": "missing", "required": False, "identity": "sha1:" + "a" * 40}]}} - row = next(r for r in _gap_export_rows({}, report) if r["name"] == "EANIM.BS6") + row = next(r for r in gap_export_rows({}, report) if r["name"] == "EANIM.BS6") self.assertEqual(row["destination"], "AOG/EANIM.BS6") self.assertEqual(row["expected"], "sha1:" + "a" * 40) @@ -466,7 +466,7 @@ class TheGapCategoryTravelsOnTheRow(unittest.TestCase): def test_every_row_carries_the_profile_category(self): from packs.crossref import cross_reference - from sitegen.dataexports import _gap_export_rows + from sitegen.exportrows import gap_export_rows profiles = {"emu": {"emulator": "Emu", "systems": ["sys"], "files": [ {"name": "a.bin", "path": "a.bin", "system_dir": "emu", "category": "game_data"}, @@ -477,7 +477,7 @@ class TheGapCategoryTravelsOnTheRow(unittest.TestCase): db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_crc32": {}, "by_sha256": {}, "by_path_suffix": {}}} report = cross_reference(profiles, {}, db) - rows = {r["name"]: r for r in _gap_export_rows({}, report)} + rows = {r["name"]: r for r in gap_export_rows({}, report)} self.assertEqual(rows["a.bin"]["destination"], "emu/a.bin") self.assertEqual(rows["a.bin"]["category"], "game_data") self.assertEqual(rows["b.o2r"]["category"], "game_data") @@ -533,12 +533,12 @@ class ArchiveMembersAreAcceptedHashes(unittest.TestCase): calls the one to ask.""" def test_member_rows(self): - from sitegen.dataexports import _accepted_hash_rows + from sitegen.exportrows import accepted_hash_rows item = {"id": "fbalpha2019", "profile": {"files": [ {"name": "nmk004.zip", "system": "arcade", "contents": [{"name": "nmk004.bin", "crc32": "83b6f611"}]}]}} - rows = _accepted_hash_rows([], [item]) + rows = accepted_hash_rows([], [item]) self.assertIn( ("nmk004.bin", "nmk004.zip/nmk004.bin", "crc32", "83b6f611"), {(r["name"], r["path"], r["algorithm"], r["value"]) for r in rows}, @@ -1116,7 +1116,7 @@ class AMismatchNamesTheDumpTheCollectionHolds(unittest.TestCase): the collection held that exact dump for every row.""" def test_the_held_copy_is_named(self): - from sitegen.gaps import _held_accepted + from sitegen.gapproblems import _held_accepted db = {"files": {"s1": {"path": "bios/Microsoft/MSX/CLK/msx-japanese.rom"}}, "indexes": {"by_sha256": {"ab" * 32: "s1"}, "by_crc32": {"84f68bf9": "s1"}}} diff --git a/tests/test_site_integration.py b/tests/test_site_integration.py index 7ed4c18cf..a2a7614fb 100644 --- a/tests/test_site_integration.py +++ b/tests/test_site_integration.py @@ -24,7 +24,8 @@ import yaml from freshness.findings import OK, STALE from freshness.profiles import check_source_paths -from sitegen import emulatorpage +from sitegen import emulatordata +from sitegen import emulatorintro from sitegen import startwith from sitegen import pageprep from sitegen.pageregistry import PageRegistry @@ -44,7 +45,7 @@ class DataTreeReaders(unittest.TestCase): ref = "y-sys" registry = PageRegistry(data_members={ref: {"a.bin": {"size": 1, "sha1": "0" * 40}}}, data_readers={ref: [("dolphin", "Dolphin"), ("ishiiruka", "Ishiiruka")]}) - page = emulatorpage._data_tree_page(ref, {}, [("y-sys", ["a.bin"])], 0, registry) + page = emulatordata._data_tree_page(ref, {}, [("y-sys", ["a.bin"])], 0, registry) self.assertIn("Read by [Dolphin](dolphin.md#data-directories) and " "[Ishiiruka](ishiiruka.md#data-directories).", page) self.assertNotIn("('dolphin'", page) @@ -58,7 +59,7 @@ class EngineIntros(unittest.TestCase): continue name = Path(path).stem with self.subTest(profile=name): - intro = emulatorpage._emulator_intro(str(profile.get("emulator") or name), profile) + intro = emulatorintro.emulator_intro(str(profile.get("emulator") or name), profile) self.assertNotRegex(intro, r"emulates\s*(?:\.|game\b|and\b|,)") self.assertNotIn(" ", intro) diff --git a/tests/test_site_nav.py b/tests/test_site_nav.py index e6407e43a..bab629c37 100644 --- a/tests/test_site_nav.py +++ b/tests/test_site_nav.py @@ -39,6 +39,7 @@ from sitegen import emulatorsindex from sitegen import nav as sitegen_nav from sitegen import parts from sitegen import starlight as sitestarlight +from sitegen import sidebartopics from core import anchors as core_anchors from model.registry import list_registered_platforms, load_platform_registry from model.platforms import load_platform_config @@ -94,7 +95,7 @@ ANCHORS = { class NotFoundPage(unittest.TestCase): def test_the_404_opens_on_the_first_tab(self): - side = sitestarlight.sidebar(_nav(), _present(_nav()), ANCHORS) + side = sidebartopics.sidebar(_nav(), _present(_nav()), ANCHORS) self.assertNotIn("/404", side["options"]["exclude"]) self.assertIn("/404", side["options"]["topics"]["start-here"]) @@ -122,7 +123,7 @@ class NotFoundPage(unittest.TestCase): class GroupsAreGroups(unittest.TestCase): def setUp(self): nav = _nav() - self.side = sitestarlight.sidebar(nav, _present(nav), ANCHORS) + self.side = sidebartopics.sidebar(nav, _present(nav), ANCHORS) self.groups = self.side["groups"] def test_setup_groups_stay_groups_and_point_at_their_section(self): @@ -193,7 +194,7 @@ class EmulatorsOneLevelDeep(unittest.TestCase): class OneNextPerPage(unittest.TestCase): def setUp(self): nav = _nav() - self.runs = sitestarlight.sidebar(nav, _present(nav), ANCHORS)["reading"] + self.runs = sidebartopics.sidebar(nav, _present(nav), ANCHORS)["reading"] self.links = [[entry["link"] for entry in run] for run in self.runs] def test_start_here_runs_into_your_setup_and_stops(self): diff --git a/tests/test_site_platform_hashes.py b/tests/test_site_platform_hashes.py index 243561c99..f3177a7a2 100644 --- a/tests/test_site_platform_hashes.py +++ b/tests/test_site_platform_hashes.py @@ -52,7 +52,7 @@ class AnUntestedRowNamesBothHashes(unittest.TestCase): def test_declared_and_held(self): from core.hashing import declared_hash_lists - from sitegen import gaps + from sitegen import gapproblems path = "bios/Nintendo/Nintendo DS/dsifirmware.bin" declared, held = "1" * 64, "2" * 64 @@ -63,7 +63,7 @@ class AnUntestedRowNamesBothHashes(unittest.TestCase): "declared": declared_hash_lists(entry), "path": path, } db = {"files": {"f" * 40: {"path": path, "sha256": held}}} - table = "\n".join(gaps._render_problem_files([problem], db=db)) + table = "\n".join(gapproblems.render_problem_files([problem], db=db)) row = next(line for line in table.splitlines() if "dsifirmware" in line) # Cut to 12 characters in the cell, the whole value in its title. self.assertIn(f'sha256 {declared[:12]}', row) diff --git a/tests/test_site_reference.py b/tests/test_site_reference.py index bd0edcb9a..234e750da 100644 --- a/tests/test_site_reference.py +++ b/tests/test_site_reference.py @@ -59,8 +59,11 @@ from sitegen import cards from sitegen import config as sitegen_config from sitegen import crossref from sitegen import dataexports +from sitegen import exportrows from sitegen import datapage from sitegen import gaps +from sitegen import gapproblems +from sitegen import gapsources from sitegen import lookup from sitegen import parts as sitegen_parts from sitegen import platformfiles @@ -408,7 +411,7 @@ class ExportsComplete(unittest.TestCase): {"name": "h.xml", "system": "s", "status": "missing"}, {"name": "h.xml", "system": "s", "status": "missing"}, detail]}} db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8")) - rows = dataexports._gap_export_rows(coverages, {}, db) + rows = exportrows.gap_export_rows(coverages, {}, db) self.assertEqual([r["name"] for r in rows], ["h.xml", "x.bin"]) held = rows[1] self.assertEqual(held["collection_path"], path) @@ -420,7 +423,7 @@ class ExportsComplete(unittest.TestCase): db = {"files": {"a" * 40: {"path": "bios/X/x.bin"}}} coverages = {"p": {"platform": "P", "details": [ {"name": "x.bin", "system": "s", "status": "untested", "path": "bios/./X/x.bin"}]}} - rows = dataexports._gap_export_rows(coverages, {}, db) + rows = exportrows.gap_export_rows(coverages, {}, db) self.assertEqual(rows[0]["resolved_sha1"], "a" * 40) def test_platform_rows_carry_status_and_file(self): @@ -431,25 +434,25 @@ class ExportsComplete(unittest.TestCase): {"name": "a.bin", "system": "s", "status": "ok", "path": entry["path"], "category": "bios"}, {"name": "b.bin", "system": "s", "status": "missing", "category": "game_data"}]}} - _items, rows = dataexports._platform_export_rows(coverages, db) + _items, rows = exportrows.platform_export_rows(coverages, db) self.assertEqual((rows[0]["status"], rows[0]["resolved_sha1"]), ("ok", sha1)) self.assertEqual(rows[0]["collection_path"], entry["path"]) self.assertEqual((rows[1]["status"], rows[1]["category"], rows[1]["collection_path"]), ("missing", "game_data", "")) def test_commit_and_wanted_list(self): - commit = dataexports.source_commit() + commit = exportrows.source_commit() self.assertRegex(commit, r"^[0-9a-f]{40}$") schema = json.loads((REPO_ROOT / "schemas" / "site-api-envelope.schema.json") .read_text(encoding="utf-8")) self.assertIn("commit", schema["properties"]) db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8")) - rows = dataexports._provenance_wanted_rows(provenance.wanted_dumps( + rows = exportrows.provenance_wanted_rows(provenance.wanted_dumps( build_report(db, load_provenance_snapshots()), provenance.load_derivable())) self.assertTrue(rows) self.assertTrue(all(r["catalog"] and r["name"] for r in rows)) - text = dataexports._csv_document(list(dataexports.WANTED_FIELDS), rows) - self.assertEqual(next(csv.reader(io.StringIO(text))), list(dataexports.WANTED_FIELDS)) + text = dataexports._csv_document(list(exportrows.WANTED_FIELDS), rows) + self.assertEqual(next(csv.reader(io.StringIO(text))), list(exportrows.WANTED_FIELDS)) class DatesAndNames(unittest.TestCase): @@ -526,7 +529,7 @@ class TheExportsKeepWhatACheckNeeds(unittest.TestCase): }} def test_rows_carry_the_member_and_the_flags(self): - _items, rows = dataexports._platform_export_rows(self.COVERAGE) + _items, rows = exportrows.platform_export_rows(self.COVERAGE) zipped, flagged = rows self.assertEqual(zipped["zipped_file"], "basic1.rom") self.assertIs(flagged["hash_match_mandatory"], True) @@ -537,10 +540,10 @@ class TheExportsKeepWhatACheckNeeds(unittest.TestCase): def test_the_csv_header_and_the_table_name_them(self): source = script_source("generate_site.py") self.assertIn('"collection_path", "resolved_sha1", *ENTRY_EXPORT_FIELDS,', source) - for field in dataexports.ENTRY_EXPORT_FIELDS: + for field in exportrows.ENTRY_EXPORT_FIELDS: self.assertIn(f":{field}", source) for field in ("zipped_file", "hash_match_mandatory", "mandatory_declared", "curated"): - self.assertIn(field, dataexports.ENTRY_EXPORT_FIELDS) + self.assertIn(field, exportrows.ENTRY_EXPORT_FIELDS) def test_the_built_csv_has_the_column(self): text = _built(PUBLIC / "downloads" / "platform-files.csv").read_text(encoding="utf-8") @@ -663,7 +666,7 @@ class TheContractsValidate(unittest.TestCase): platforms = str(REPO_ROOT / "platforms") for name in list_registered_platforms(platforms): config = load_platform_config(name, platforms) - contract, registry = dataexports._split_contract(config) + contract, registry = exportrows._split_contract(config) with self.subTest(platform=name): errors = [error.message for error in validator.iter_errors(contract)] self.assertEqual(errors, []) @@ -738,7 +741,7 @@ class EveryEnvelopeCarriesTheCommit(unittest.TestCase): def test_every_built_envelope_has_it(self): _built(API / "catalog.json") - if not dataexports.source_commit(): + if not exportrows.source_commit(): raise unittest.SkipTest("not a git checkout") lacking = [ path.relative_to(API).as_posix() for path in sorted(API.rglob("*.json")) @@ -919,13 +922,13 @@ class TablesFitTheirColumn(unittest.TestCase): def test_the_gaps_tables(self): problem = {"platform": "Batocera", "name": "x.bin", "status": "untested", "required": True, "reason": "expected md5 differs", "declared": {"md5": ["b" * 32]}, "path": ""} - table = "\n".join(gaps._render_problem_files([problem], db={"files": {}})) + table = "\n".join(gapproblems.render_problem_files([problem], db={"files": {}})) row = next(line for line in table.splitlines() if "x.bin" in line) self.assertIn(f'{"b" * 12}', row) self.assertIn('expected md5 differs', row) source = script_source("generate_site.py") self.assertIn('expected = f"{algorithm} {short_hash(value)}"', source) - self.assertIn("{_reason_cell(u['reason'])}", source) + self.assertIn("{reason_cell(u['reason'])}", source) class SourceLinksGoWhereTheFileIs(unittest.TestCase): @@ -1301,9 +1304,9 @@ class FilesToSourceOnAPhone(unittest.TestCase): for part in parts: rows = [line for line in part.read_text(encoding="utf-8").splitlines() if line.startswith("| `")] - self.assertLessEqual(len(rows), gaps.FILES_TO_SOURCE_PART, part.name) + self.assertLessEqual(len(rows), gapsources.FILES_TO_SOURCE_PART, part.name) for row in rows: - self.assertIn(f"[Have it? Upload]({gaps.UPLOAD_URL}", row) + self.assertIn(f"[Have it? Upload]({gapsources.UPLOAD_URL}", row) def test_the_upload_lands_in_the_folder_the_review_asks_for(self): """The link read the profile's first system: Raze's Duke Nukem 3D @@ -1334,13 +1337,13 @@ class LongGapTablesOnPagesOfTheirOwn(unittest.TestCase): "unsourceable": [unsourced], "gap_details": [gap]}} return gaps.generate_gap_analysis( {"xm7": {"emulator": "XM7", "files": []}}, {}, {"files": {}, "indexes": {}}, - gap_report=report, listing=gaps.SourceListing(moved=moved)) + gap_report=report, listing=gapsources.SourceListing(moved=moved)) def test_both_tables_leave_with_their_anchors_kept(self): moved: dict[str, str] = {} page = self._page(moved) self.assertEqual(set(moved) - {"gaps-files-to-source"}, - {gaps.PER_EMULATOR_STEM, gaps.NOT_COLLECTED_STEM}) + {gapsources.PER_EMULATOR_STEM, gapsources.NOT_COLLECTED_STEM}) self.assertNotIn("| Emulator | Undeclared |", page) self.assertNotIn("| File | Emulator | Reason |", page) self.assertIn("### Per emulator", page) @@ -1348,11 +1351,11 @@ class LongGapTablesOnPagesOfTheirOwn(unittest.TestCase): self.assertIn('', page) self.assertIn("## Not collected yet", page) self.assertIn("[a page of their own](gaps-not-collected.md)", page) - own = moved[gaps.NOT_COLLECTED_STEM] + own = moved[gapsources.NOT_COLLECTED_STEM] self.assertIn('link: "/gaps/"', own) self.assertIn("| `KANJI2.ROM` | XM7 |", own) self.assertIn("gaps.md#not-collected-yet", own) - self.assertIn("| [XM7](emulators/xm7.md) | 1 |", moved[gaps.PER_EMULATOR_STEM]) + self.assertIn("| [XM7](emulators/xm7.md) | 1 |", moved[gapsources.PER_EMULATOR_STEM]) def test_without_pages_the_tables_stay(self): page = self._page(None) @@ -1372,12 +1375,12 @@ class OneAnswerOnReleasePacks(unittest.TestCase): """8.1: the API, the picker's data and the pages read the registry.""" def test_a_child_does_not_inherit_its_parents_pack(self): - _contract, registry = dataexports._split_contract( + _contract, registry = exportrows._split_contract( {"_key": "lakka", "inherits": "retroarch", "release_pack": True}) self.assertIs(registry["release_pack"], "lakka" in _released()) - _contract, registry = dataexports._split_contract({"_key": "minui"}) + _contract, registry = exportrows._split_contract({"_key": "minui"}) self.assertNotIn("release_pack", registry) - _contract, registry = dataexports._split_contract({"_key": "retroarch"}) + _contract, registry = exportrows._split_contract({"_key": "retroarch"}) self.assertIs(registry["release_pack"], "retroarch" in _released()) def test_api_release_pack_set_equals_the_registry(self): diff --git a/tests/test_site_search.py b/tests/test_site_search.py index ec99a4e97..df88e2798 100644 --- a/tests/test_site_search.py +++ b/tests/test_site_search.py @@ -38,6 +38,7 @@ from sitegen import getpages from sitegen.pageregistry import PageRegistry from sitegen import structured from sitegen import starlight as sitestarlight +from sitegen import sidebartopics from sitegen import validate from model.registry import list_registered_platforms from model.profiles import load_emulator_profiles @@ -387,7 +388,7 @@ def _sidebar_with_get_pages() -> tuple[dict, list[str]]: nav = _nav() names = list_registered_platforms(PLATFORMS) get_pages = ["get/index.md", *(f"get/{name}.md" for name in names)] - return sitestarlight.sidebar(nav, _present(nav) | set(get_pages), ANCHORS), get_pages + return sidebartopics.sidebar(nav, _present(nav) | set(get_pages), ANCHORS), get_pages class GetPagesSitInYourSetup(unittest.TestCase): @@ -400,7 +401,7 @@ class GetPagesSitInYourSetup(unittest.TestCase): setup = set(side["options"]["topics"].get("setups", [])) for rel in get_pages: with self.subTest(page=rel): - self.assertIn("/" + sitestarlight._sidebar_link(rel).strip("/"), setup) + self.assertIn("/" + sidebartopics._sidebar_link(rel).strip("/"), setup) def test_a_get_page_is_dated_by_its_release(self): """The sitemap gave no date to the pages that change only with a release.""" @@ -423,7 +424,7 @@ class GetPagesSitInYourSetup(unittest.TestCase): def test_no_page_is_left_out_of_every_tab(self): nav = _nav() present = _present(nav) | {"orphans/alone.md"} - side = sitestarlight.sidebar(nav, present, ANCHORS) + side = sidebartopics.sidebar(nav, present, ANCHORS) self.assertEqual(side["options"]["exclude"], []) placed = {path for paths in side["options"]["topics"].values() for path in paths} self.assertIn("/orphans/alone", placed) @@ -585,15 +586,15 @@ class LetterGroupsAreNoCrumb(unittest.TestCase): def test_by_initial(self): names = [{"label": "Dolphin", "link": "/d"}, {"label": "DuckStation", "link": "/e"}] - self.assertTrue(sitestarlight.by_initial("D", names)) - self.assertFalse(sitestarlight.by_initial("E", names)) + self.assertTrue(sidebartopics.by_initial("D", names)) + self.assertFalse(sidebartopics.by_initial("E", names)) digits = [{"label": "2600.emu", "link": "/a"}, {"label": "81", "link": "/b"}] - self.assertTrue(sitestarlight.by_initial("0 to 9", digits)) - self.assertFalse(sitestarlight.by_initial("Sony", names)) - self.assertFalse(sitestarlight.by_initial("D", [{"label": "D", "items": names}])) + self.assertTrue(sidebartopics.by_initial("0 to 9", digits)) + self.assertFalse(sidebartopics.by_initial("Sony", names)) + self.assertFalse(sidebartopics.by_initial("D", [{"label": "D", "items": names}])) def test_emulator_letter_groups_are_marked(self): - side = sitestarlight.sidebar(_nav(), _present(_nav()), ANCHORS) + side = sidebartopics.sidebar(_nav(), _present(_nav()), ANCHORS) letters = {key: value for key, value in side["groups"].items() if key.startswith("Explore/Emulators/")} self.assertTrue(letters) diff --git a/tests/test_site_wanted.py b/tests/test_site_wanted.py index 21af41289..0240585fc 100644 --- a/tests/test_site_wanted.py +++ b/tests/test_site_wanted.py @@ -26,6 +26,7 @@ import zlib from pathlib import Path from sitegen import gaps +from sitegen import gapsources from sitegen import lookup from sitegen import wanted as sitewanted from resolve import review, reviewhashes, sendable @@ -474,7 +475,7 @@ class EveryFolderIsTheReviewsFolder(_World): self.assertEqual(sitewanted.upload_href(sitewanted.UPLOAD_ROOT, "bios/Maker/Sub Dir/"), "https://github.com/Abdess/retrobios/upload/main/bios/Maker/Sub%20Dir") self.assertEqual(sitewanted.upload_href(sitewanted.UPLOAD_ROOT, ""), - gaps.UPLOAD_URL) + gapsources.UPLOAD_URL) def _node(script: str) -> str: