refactor: split four oversized site modules

The emulator page sheds its intro and data directories, the gaps page its problem files and core complement, starlight its sidebar topics, the data exports their rows. Names another module now reads lose their underscore.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 06:02:03 +01:00
1 parent 2786b3be34
commit 6c48409912
25 files changed
+1730 -1629

No files matched your search

+5 -3
View File
@@ -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,
+19 -351
View File
@@ -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 <algorithm>_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(
+133
View File
@@ -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'<span id="{anchor}"></span>'
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
+285
View File
@@ -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"<p><small>In this collection: {series(held)}.</small></p>", ""]
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 = ['<div id="data-folder" class="rb-anchor"></div>', "",
*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 ['<div id="data-folder" class="rb-anchor"></div>', "", 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")
+11 -428
View File
@@ -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"<p><small>In this collection: {series(held)}.</small></p>", ""]
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'<span id="{anchor}"></span>'
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 = ['<div id="data-folder" class="rb-anchor"></div>', "",
*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 ['<div id="data-folder" class="rb-anchor"></div>', "", 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)}",
+352
View File
@@ -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 <algorithm>_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
+220
View File
@@ -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'<code title="{html.escape(value)}">{html.escape(value[:12])}</code>'
def _hash_cell(hashes: dict[str, list[str]]) -> str:
return "<br>".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'<span class="rb-reason">{text}</span>' 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}<br>{_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 <span class="rb-badge rb-badge-danger">'
f"{count_text(len(missing_files), 'name')}</span>",
"",
"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 <span class="rb-badge rb-badge-warning">'
f"{count_text(len(untested_files), 'file')}</span>",
"",
"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 <span class="rb-badge rb-badge-warning">'
f"{count_text(len(mismatch_files), 'file')}</span>",
"",
"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
+22 -566
View File
@@ -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'<code title="{html.escape(value)}">{html.escape(value[:12])}</code>'
def _hash_cell(hashes: dict[str, list[str]]) -> str:
return "<br>".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'<span class="rb-reason">{text}</span>' 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}<br>{_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 <span class="rb-badge rb-badge-danger">'
f"{count_text(len(missing_files), 'name')}</span>",
"",
"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 <span class="rb-badge rb-badge-warning">'
f"{count_text(len(untested_files), 'file')}</span>",
"",
"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 <span class="rb-badge rb-badge-warning">'
f"{count_text(len(mismatch_files), 'file')}</span>",
"",
"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'<span class="rb-badge rb-badge-info">{p}</span>'
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'<span class="rb-badge rb-badge-danger">{to_source}</span>'
if to_source > 0
else '<span class="rb-badge rb-badge-success">0</span>'
)
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 = [
'<span id="acknowledged-gaps"></span>',
"",
"## 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"
+353
View File
@@ -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'<span class="rb-badge rb-badge-info">{p}</span>'
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'<span class="rb-badge rb-badge-danger">{to_source}</span>'
if to_source > 0
else '<span class="rb-badge rb-badge-success">0</span>'
)
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 = [
'<span id="acknowledged-gaps"></span>',
"",
"## 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
+22 -2
View File
@@ -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"),
"---", ""]
+214
View File
@@ -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"])
+2 -204
View File
@@ -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