refactor: site modules into the sitegen package

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 19:31:27 +01:00
1 parent 29f5c48a2c
commit 206dae3163
57 files changed
+98 -97

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""The documentation site: pages, navigation, data files and the README, from the project data."""
+302
View File
@@ -0,0 +1,302 @@
"""What the site tells an AI agent about itself.
- ``llms.txt`` (https://llmstxt.org): the pages and data an agent should
read first, in Markdown, at the site's root.
- ``skills/setup-bios/SKILL.md``: an Agent Skill that sets up a device's
BIOS files with the fewest downloads.
- ``ard.json``: an Agentic Resource Discovery manifest
(https://github.com/ards-project/ard-spec) listing that skill and the
JSON API, linked from every page's head with ``rel="ard"``.
Both are written from the registry at each build, so a new platform or a
moved page cannot leave them stale. The WebMCP tools a page registers live
in website/src/scripts/agent-tools.ts.
"""
from __future__ import annotations
import json
from collections.abc import Callable
from pathlib import Path
from model.guides import PACKAGE_COMMAND
SITE = "https://abdess.github.io/retrobios/"
PUBLISHER = "abdess.github.io"
SH = "curl -fsSL https://abdess.github.io/retrobios/i | sh -s --"
PS = "& ([scriptblock]::Create((irm https://abdess.github.io/retrobios/i.ps1)))"
# What a folder put into a command may not hold, as agent-tools.ts refuses
# it: PowerShell also ends a single-quoted string on the typographic quotes.
REFUSED = "any quote, straight or typographic (' \" ‘ ’ ‚ ‛ “ ” „), a backtick or a control character"
QUOTING = (f"A folder goes in single quotes, attached to its option. One that holds {REFUSED}, "
"or starts with `-`, is a question for the user, never a value to escape into the "
"command. On a page of the site, the `device_setup_command` WebMCP tool writes the "
"command and refuses such a folder.")
UVX = PACKAGE_COMMAND
# EVENT_SCHEMA of install.py, and the schema generate_event_schema.py writes
# from EVENT_KEYS, as the site publishes it. tests/test_site_agents.py holds
# both to install.py.
EVENT_SCHEMA = 1
EVENTS_SCHEMA_PATH = "api/v1/schemas/install-events.schema.json"
# Every code of the Exit status table of wiki/installer.md, in short.
EXIT_CODES = (
(0, "everything asked for is installed or already in place"),
(1, "a failure: a download, a file list or a folder that cannot be used"),
(2, "nothing was done: an option refused, every file failed, or the user quit"),
(3, "`--check` found files missing or wrong, nothing having failed"),
(4, "`--find` read the hash and the list holds no one file for it"),
(130, "stopped with Ctrl+C"),
(141, "the output went to a reader that closed early"),
)
START_PAGES = (
("Which pack is needed", "which-pack/", "pick a device or setup, get the folder its BIOS files go in, "
"one command that installs and checks them, or a ZIP pack"),
("First install", "wiki/first-install/", "the steps from nothing to a working BIOS folder"),
("What are BIOS files", "wiki/what-are-bios-files/", "why emulators need them and where they come from"),
("Troubleshooting", "wiki/troubleshooting/", "a file the emulator does not find or refuses"),
("Common questions", "wiki/faq/", "short answers"),
)
DATA = (
("API index", "api/v1/index.json", "every dataset of the JSON API, versioned"),
("Catalog", "api/v1/catalog.json", "each dataset, manifest, export and download with its size, SHA-256 and schema"),
("Emulators", "api/v1/emulators.json", "every emulator profile: the files it reads, required or not, "
"their hashes and the source line that reads each. One document "
"per emulator at api/v1/emulators/<id>.json"),
("Core names", "api/v1/cores.json", "each core name and alias, with the profile it designates"),
("Systems", "api/v1/systems.json", "each system id, its name and the section holding its files"),
("Platforms", "api/v1/platforms.json", "each setup (RetroArch, Batocera...), its BIOS folder and files"),
("Hash lookup", "api/v1/lookup/00.json", "what a hash (MD5, SHA-1, SHA-256, CRC32) designates, sharded "
"by its first two hex characters: api/v1/lookup/<xx>.json"),
)
MORE = (
("Emulators", "emulators/", "one page per emulator"),
("Systems", "systems/", "one page per console maker, every file with its hashes"),
("Installer", "wiki/installer/", "every option of install.py"),
("What is counted", "wiki/privacy/", "the site's cookie-free counting"),
("Is it legal?", "wiki/legal/", "the project's position"),
("Contributing", "contributing/", "add a missing file or an emulator profile"),
)
def llms_txt(platforms: list[tuple[str, str]]) -> str:
"""The site's llms.txt. ``platforms`` lists (id, display name) of every
registered setup, each with its page."""
lines = [
"# RetroBIOS",
"",
"> BIOS and firmware files for emulators, each checked against the emulator's source "
"code: which files an emulator reads, whether it starts without them, where each one "
"goes on every setup, their hashes, and an installer that puts them in place.",
"",
"Each emulator's files are read from its code, and most cite the file and line that "
"read them. The files themselves are served by the GitHub repository "
"(https://github.com/Abdess/retrobios) and its releases.",
"",
"## Answering a user",
"",
*(f"- {rule}" for rule in ANSWER_RULES),
"",
"## Setting up a device for its user",
"",
"Most people want to play now, with the fewest files. The installer does that in one "
"command: it finds the setup and its BIOS folder, reads the games on the card, and with "
"`--for-games --required-only` installs only the files those games cannot start "
"without. `--yes` alone installs what the card's games need, optional files "
"included, and `--all-files` the setup's whole list (gigabytes).",
"",
f"1. Preview, nothing written: `{SH} --for-games --required-only --dry-run`",
f"2. Install, no questions: `{SH} --for-games --required-only --yes`",
f"3. On Windows (PowerShell): `{PS} --for-games --required-only --yes`",
"",
"- Run it on the device itself (its terminal or SSH), or on a computer with the device's "
"card plugged in. The installer recognises the handheld systems on the card, among them "
"ArkOS, dArkOS, ArchR and UnofficialOS (R36S and its clones), muOS, KNULLI, ROCKNIX, "
"AmberELEC, EmuELEC, Onion, spruceOS and MinUI. "
"The [Linux handhelds page](" + SITE + "platforms/linux-handhelds/) maps each device "
"to its system and folder.",
"- From a computer, if the card is not found, name its BIOS folder: `--dest='<card>/bios'` "
"(ArkOS and dArkOS: the `bios` folder of the EASYROMS part).",
"- A games folder somewhere else: `--for-games='<folder>'`, one subfolder per system.",
f"- {QUOTING}",
"- Later, to see what is missing or wrong: `--check`. Machine-readable progress: "
"`--events` (JSON lines, one per event, documented on the installer page).",
"- A game the installer cannot identify gets every BIOS of its system, and the run names it.",
f"- The same steps as an Agent Skill: [SKILL.md]({SITE}{SKILL_PATH}).",
"",
"## Driving the installer for a user",
"",
f"With Python 3.8 or newer, the installer is also a package: `{UVX} --for-games "
f"--required-only --dry-run`, or `pipx run retrobios` with the same options.",
"",
"1. Plan: run it with `--dry-run --events`. Nothing is written, and standard output carries "
f"one JSON object per line, event schema {EVENT_SCHEMA} "
f"([JSON Schema]({SITE}{EVENTS_SCHEMA_PATH})): a `file` event per file with its "
"`state`, `check` with the totals and `bytes_needed`, then `summary` with `pending`.",
"2. Consent: show the user what will be installed, where, and the size, and ask.",
"3. Act, only on a yes: the same command with `--yes` in place of `--dry-run`.",
"",
"- `--yes` asks nothing: use it in a run without a terminal. A run that needs an "
"answer (two setups found, none found) stops and names the option to give.",
"- The exit code, also the `code` of the last `end` event. An option refused at once "
"writes no event at all:",
*(f" - `{code}`: {meaning}" for code, meaning in EXIT_CODES),
"",
"## Start",
"",
*(f"- [{title}]({SITE}{path}): {what}" for title, path, what in START_PAGES),
"",
"## Setups",
"",
*(f"- [{name}]({SITE}platforms/{pid}/): its BIOS folder and files" for pid, name in platforms),
"",
"## Data",
"",
*(f"- [{title}]({SITE}{path}): {what}" for title, path, what in DATA),
"",
"## Optional",
"",
*(f"- [{title}]({SITE}{path}): {what}" for title, path, what in MORE),
]
return "\n".join(lines) + "\n"
# How an assistant answers from the site and not from memory: file names,
# folders and hashes change with each setup, and a guessed one is the
# answer that fails. The same rules end the skill.
ANSWER_RULES = (
"Each Markdown copy, llms.txt and llms-full.txt name the commit and the date they "
f"were built from. When a copy read earlier or found through a search engine names a "
f"commit other than {SITE}version.json, fetch it again: the site changes with each commit.",
"Answer from the pages and data, not from memory. Every page has a Markdown copy: add "
"`index.md` to its address (https://abdess.github.io/retrobios/which-pack/index.md). "
f"[llms-full.txt]({SITE}llms-full.txt) holds the guides and every setup's page in one file.",
"Name files exactly as the pages write them: names are case-sensitive on most devices, and a renamed file is "
"not found. Never invent a file name, a folder or a hash.",
"The BIOS folder depends on the setup, and for RetroArch on the device: give the folder the "
"setup's page names, under \"Where the files go\".",
"To check a file the user has, compare its MD5 or SHA-1 with the file's card, or look the hash "
f"up: {SITE}files/?hash=<value> (the page) or api/v1/lookup/<first two hex>.json (the data).",
"Prefer the installer to a manual copy: it puts each file in its folder and checks its hash. "
"Give the command the setup's page gives, with `--for-games --required-only` for the fewest files.",
"Say where an answer comes from: link the source page.",
"On a page of the site, the WebMCP tools answer from the data: setup_bios_files (folder and "
"files of a setup), emulator_bios_files, lookup_bios_hash, device_setup_command, search_retrobios.",
f"Whether sharing BIOS files is legal depends on the country: point to [Is it legal?]({SITE}wiki/legal/), "
"do not give legal advice.",
)
SKILL_PATH = "skills/setup-bios/SKILL.md"
# The Agent Skills media type ARD names: Markdown with this profile.
SKILL_TYPE = 'text/markdown; profile="urn:air:agent-skills"'
def skill_md() -> str:
"""An Agent Skill (SKILL.md: YAML front matter, then instructions) that
sets up a device's BIOS files with the fewest downloads."""
return "\n".join([
"---",
"name: setup-bios",
"description: Install the BIOS and firmware files a retrogaming device or computer needs "
"(RetroArch, Batocera, EmuDeck, ArkOS, dArkOS, muOS, KNULLI, ROCKNIX and others), only "
"what the games on its card need to start. Use when a user asks to set up emulators, "
"a handheld (R36S, Miyoo, Anbernic), BIOS files or firmware.",
"---",
"",
"# Set up BIOS files with RetroBIOS",
"",
"Most users want to play now, with the fewest files. Install only what the games on the "
"card need, unless the user asks for everything.",
"",
"## Steps",
"",
"1. Ask where the games are: on the device itself (with its terminal or SSH), or on "
"its card plugged into this computer.",
f"2. Preview, nothing is written: `{SH} --for-games --required-only --dry-run` "
f"(Windows PowerShell: `{PS} --for-games --required-only --dry-run`).",
"3. Show the user the plan it prints: the setup found, the BIOS folder, the files and "
"their size. Ask before going on if the setup or the folder is not the one expected.",
"4. Install with the same command, `--yes` in place of `--dry-run`.",
"5. Report the summary line. A game the installer could not identify got every BIOS of "
"its system: say which.",
"",
"## When the setup or the card is not found",
"",
"- From a computer, name the card's BIOS folder: `--dest='<card>/bios'`. ArkOS and dArkOS "
"keep it on the EASYROMS part.",
"- Games outside the card: `--for-games='<folder>'`, one subfolder per system.",
"- A setup not detected: `--platform=<name>`, a name exactly as `--list-platforms` prints "
"it (letters, digits, `-` and `_`).",
f"- {QUOTING}",
"",
"## Later",
"",
"- `--check` says what is missing or wrong, without downloading.",
"- `--events` writes the run as JSON lines, for reading by a program.",
"",
"## Answering from the site",
"",
*(f"- {rule}" for rule in ANSWER_RULES),
"",
f"Every option: {SITE}wiki/installer/. Devices and their folders: "
f"{SITE}platforms/linux-handhelds/. The site's guide for agents: {SITE}llms.txt.",
"",
])
def ard_manifest() -> dict:
"""The ARD manifest: the setup skill and the JSON API, each with the
questions it answers. llms.txt is found at the site root, as its
convention says."""
return {
"entries": [
{
"identifier": f"urn:air:{PUBLISHER}:retrobios:setup-bios",
"displayName": "Set up BIOS files with RetroBIOS",
"type": SKILL_TYPE,
"url": f"{SITE}{SKILL_PATH}",
"description": "An agent skill that installs the BIOS files a device needs, only "
"what the games on its card need to start.",
"representativeQueries": [
"install the minimum BIOS files for the games on an R36S running dArkOS",
"set up BIOS files for RetroArch on a Steam Deck",
"the emulator says BIOS missing, fix it",
],
"capabilities": ["SetupBios"],
"tags": ["bios", "firmware", "emulation", "retrogaming"],
},
{
"identifier": f"urn:air:{PUBLISHER}:retrobios:api",
"displayName": "RetroBIOS JSON API",
"type": "application/json",
"url": f"{SITE}api/v1/index.json",
"description": "Versioned JSON datasets: emulator profiles, platforms, systems, core "
"names and a hash lookup.",
"representativeQueries": [
"what file has the MD5 490f666e1afb15b7362b406ed1cea246",
"which files does the beetle_psx core read",
"where do PlayStation BIOS files go on Batocera",
],
"capabilities": ["HashLookup", "EmulatorFiles", "PlatformFiles"],
"tags": ["api", "json", "bios"],
},
]
}
# IndexNow: the key search engines read back from the site before they take
# a list of changed pages from it (scripts/indexnow.py). Public by design.
INDEXNOW_KEY = "23329654933fb67280e8e7ac749eb869"
INDEXNOW_FILE = "indexnow.txt"
def write(public: Path, platforms: list[tuple[str, str]],
write_if_changed: Callable[[str, str], object]) -> None:
write_if_changed(str(public / "llms.txt"), llms_txt(platforms))
write_if_changed(str(public / INDEXNOW_FILE), INDEXNOW_KEY + "\n")
(public / SKILL_PATH).parent.mkdir(parents=True, exist_ok=True)
write_if_changed(str(public / SKILL_PATH), skill_md())
write_if_changed(str(public / "ard.json"), json.dumps(ard_manifest(), indent=1) + "\n")
+107
View File
@@ -0,0 +1,107 @@
"""The one-line bootstraps the site serves at its own address.
`curl -fsSL https://abdess.github.io/retrobios/i | sh` and
`irm https://abdess.github.io/retrobios/i.ps1 | iex` fetch copies of
install.sh and install.ps1 written when the site is built. Each copy
downloads install.py from the commit the site is built from, the commit
whose bootstrap pins that installer's SHA-256. The site deploys minutes
after a push: until then it serves the previous commit's pair, never the
bootstrap of one commit with the installer of the next.
GitHub Pages serves both names as application/octet-stream (no type in
mime-db for .ps1 or for a bare name). curl ignores the type, and
Invoke-RestMethod reads any type that is neither JSON nor XML as text.
"""
from __future__ import annotations
import hashlib
import os
import re
import subprocess
from pathlib import Path
from core.artifacts import write_if_changed
from model.guides import PS1_NAME, SH_NAME
REPO_RAW = "https://raw.githubusercontent.com/Abdess/retrobios"
# Served name: the bootstrap it copies and the one line naming the
# installer's address there.
SOURCES: dict[str, tuple[str, re.Pattern[str]]] = {
SH_NAME: ("install.sh", re.compile(r'^(DEFAULT_INSTALL_URL=")[^"]*(")', re.M)),
PS1_NAME: ("install.ps1", re.compile(r'^(\s*\$defaultInstallUrl = ")[^"]*(")', re.M)),
}
# The line each bootstrap says a refused installer with, and the pin.
ADVICE: dict[str, re.Pattern[str]] = {
SH_NAME: re.compile(r'^(MISMATCH_ADVICE=")[^"]*(")', re.M),
PS1_NAME: re.compile(r'^(\s*\$mismatchAdvice = ")[^"]*(")', re.M),
}
PIN: dict[str, re.Pattern[str]] = {
SH_NAME: re.compile(r'^DEFAULT_INSTALL_SHA256="([0-9a-f]{64})"', re.M),
PS1_NAME: re.compile(r'^\s*\$defaultInstallSha256 = "([0-9a-f]{64})"', re.M),
}
# What the served copy says of a refused installer. It names a commit's
# install.py, which never changes, and both downloaders fail on a short
# transfer before the hash is read: neither a cut download nor caches of
# two ages explain a mismatch there.
SERVED_ADVICE = ("The file was changed on its way here, most often by a proxy or an "
"antivirus that rewrites downloads. Run the command again from another "
"network, or with that web protection paused.")
def build_commit(root: Path) -> str:
"""The commit the site is built from: GITHUB_SHA in CI, HEAD locally."""
commit = os.environ.get("GITHUB_SHA", "").strip()
if not commit:
commit = subprocess.run(
["git", "rev-parse", "HEAD"], cwd=root, check=True,
capture_output=True, text=True,
).stdout.strip()
if not re.fullmatch(r"[0-9a-f]{40}", commit):
raise ValueError(f"not a commit id: {commit!r}")
return commit
def installer_url(commit: str) -> str:
return f"{REPO_RAW}/{commit}/install.py"
def served_text(name: str, root: Path, commit: str) -> str:
"""The bootstrap served as name, its installer read from commit and its
advice fitted to that. A pin that is not the SHA-256 of root's
install.py stops the build: published, that copy refused every install
until the next good deploy, where a failed build keeps the last good
pair served."""
source, line = SOURCES[name]
text = (root / source).read_text(encoding="utf-8")
pinned = PIN[name].findall(text)
if len(pinned) != 1:
raise ValueError(f"{source}: {len(pinned)} installer pins, expected one")
actual = hashlib.sha256((root / "install.py").read_bytes()).hexdigest()
if pinned[0] != actual:
raise ValueError(f"{source} pins {pinned[0][:12]}, install.py is {actual[:12]}: "
"re-pin the bootstrap before the site serves it")
served, count = line.subn(
lambda m: f"{m.group(1)}{installer_url(commit)}{m.group(2)}", text
)
if count != 1:
raise ValueError(f"{source}: {count} installer address lines, expected one")
served, count = ADVICE[name].subn(
lambda m: f"{m.group(1)}{SERVED_ADVICE}{m.group(2)}", served
)
if count != 1:
raise ValueError(f"{source}: {count} mismatch advice lines, expected one")
return served
def write_bootstraps(public: Path, root: Path, commit: str | None = None) -> list[Path]:
"""Write every served bootstrap at the root of the site's public folder."""
commit = commit or build_commit(root)
public.mkdir(parents=True, exist_ok=True)
written = []
for name in SOURCES:
path = public / name
write_if_changed(str(path), served_text(name, root, commit))
written.append(path)
return written
+121
View File
@@ -0,0 +1,121 @@
"""Long lists as one filterable table, each row opening to its details.
MAME's card pages read 13,000 to 16,000 words, one card after another,
before a reader found the archive they came for. Here each entry is one
row: its name, the facts that tell rows apart, and the full card in a
closed block under the name. The table is written as HTML so the block can
hold the card's Markdown. It carries what rehype-stack-tables.mjs gives a
Markdown table: `data-rb-stack` (one block per row on a phone) and the
filter box above, which site.ts wires. Without JavaScript the rows show and
every block opens. A closed block stays in the page, so the browser's find
and the site search still reach every name it holds.
"""
from __future__ import annotations
import html
from dataclasses import dataclass, field
from sitegen import markup
# rehype-stack-tables.mjs RECORD_ROWS: from this many rows a table has a
# filter box, and its stacked labels are written by site.ts, not the build.
RECORD_ROWS = 20
# filterPlaceholder in rehype-stack-tables.mjs: the column names offered.
PLACEHOLDER_COLUMNS = 4
@dataclass
class Row:
"""One entry: ``title`` is the inline HTML of its name (a heading, so
the site search lands on it), ``body`` the Markdown lines shown when the
row opens, ``cells`` the HTML of the other columns."""
title: str
body: list[str]
cells: list[str] = field(default_factory=list)
def filter_placeholder(labels: list[str]) -> str:
""""File, contents, status..." as rehype-stack-tables.mjs words it."""
words = [label for label in labels if label][:PLACEHOLDER_COLUMNS]
if not words:
return "Type to filter..."
lowered = [word if index == 0 or not (word[:1].isupper() and word[1:2].islower())
else word[0].lower() + word[1:] for index, word in enumerate(words)]
return f"{', '.join(lowered)}..."
def filter_box(ident: str, heading: str, labels: list[str], rows: int, noun: str = "rows") -> str:
"""The filter box rehype-stack-tables.mjs writes above a long table.
It is `hidden` until site.ts wires it: without the script it filters
nothing, so a reader with no JavaScript, a text dump and the search
skip it while the rows stay. retrobios.css keeps its room meanwhile,
so the table does not move when it shows. The count is the input's
description, and spaces keep label, field and count apart in any text
read from the HTML."""
return (
f'<div class="rb-table-filter" hidden {markup.search_exclude()}>'
f'<label for="{ident}">Filter {html.escape(heading)}</label> '
f'<input id="{ident}" type="search" autocomplete="off" '
f'placeholder="{html.escape(filter_placeholder(labels))}" aria-describedby="{ident}-count"> '
f'<span id="{ident}-count" class="rb-table-filter-count" aria-live="polite">'
f"{rows:,} {noun}</span></div>"
)
def card_title_and_body(card: list[str]) -> tuple[str, list[str]]:
"""A card's heading line and the lines under it, its wrapping block
(the first line and the last closing tag) taken off."""
title_at = next(index for index, line in enumerate(card) if line.startswith("<h3"))
closing = max(index for index, line in enumerate(card) if line.strip() == "</div>")
body = card[title_at + 1:closing]
while body and not body[0].strip():
body.pop(0)
while body and not body[-1].strip():
body.pop()
return card[title_at], body
def entry_table(rows: list[Row], heads: list[str], ident: str, heading: str,
stacked: list[str] | None = None,
searched: frozenset[str] = frozenset()) -> list[str]:
"""``rows`` under ``heads`` (the first names the column of titles).
``stacked`` gives a column's short label on a phone, as a header's
`title` does in a Markdown table. A column every row leaves empty
(``""``) is not written. The site search skips every column but the
titles and those ``searched`` names: a count or a short hash is no word
anyone types.
"""
keep = [0] + [column for column in range(1, len(heads))
if any(row.cells[column - 1] for row in rows)]
labels = [heads[c] for c in keep]
short = [(stacked or heads)[c] for c in keep]
skip = markup.search_exclude()
# The block holds the box and the table: an open card spans its width.
lines = ["", '<div class="rb-entries-wrap">']
if len(rows) >= RECORD_ROWS:
lines.append(filter_box(ident, heading, labels, len(rows)))
lines.append('<table class="rb-entries" data-rb-stack="true">')
head_cells = ""
for label, name in zip(labels, short):
title = f' title="{html.escape(name)}"' if name != label else ""
head_cells += f'<th scope="col"{title}>{html.escape(label)}</th>'
lines.extend(["<thead>", f"<tr>{head_cells}</tr>", "</thead>", "<tbody>"])
for row in rows:
lines.append("<tr>")
if row.body:
lines.extend(["<td>", '<details class="rb-entry">', f"<summary>{row.title}</summary>",
"", *row.body, "", "</details>", "</td>"])
else:
lines.append(f"<td>{row.title}</td>")
for column in keep[1:]:
label = (f' data-label="{html.escape(short[keep.index(column)])}"'
if len(rows) < RECORD_ROWS else "")
ignored = "" if heads[column] in searched else f" {skip}"
lines.append(f"<td{label}{ignored}>{row.cells[column - 1] or '-'}</td>")
lines.append("</tr>")
lines.extend(["</tbody>", "</table>", "</div>", ""])
return lines
+354
View File
@@ -0,0 +1,354 @@
"""The site page that publishes each platform's corrected BIOS file.
export_native.py writes the platform's own file, corrected, under
exports/<platform>/ and what it changed beside it as exports/<platform>.json.
This page reads those reports: the reader finds a platform, the file its
maintainers keep, the corrected copy, and every change named.
"""
from __future__ import annotations
import json
from pathlib import Path
from sitegen import markup
EXPORTS_DIR = "exports"
REPO_BLOB = "https://github.com/Abdess/retrobios/blob/main"
REPO_TREE = "https://github.com/Abdess/retrobios/tree/main"
REPO_RAW = "https://raw.githubusercontent.com/Abdess/retrobios/main"
# Where the site publishes each report, beside the API (generate_site).
API_EXPORTS = "api/v1/exports"
# Report key, then how a line of it reads on the page.
CHANGE_KINDS = (
("hashes_updated", "Hashes updated to the emulator source"),
("hashes_filled", "Hashes added where the original lists none"),
("sizes_updated", "Sizes updated to the emulator source"),
("sizes_removed", "Sizes no longer stated"),
("hashes_cleared", "Hashes no longer listed"),
("withheld", "Changes not applied"),
)
# Report key, then the kind each line of `changes` carries.
CHANGE_RECORDS = {
"hashes_updated": "hash_updated",
"hashes_filled": "hash_filled",
"sizes_updated": "size_updated",
"sizes_removed": "size_removed",
"hashes_cleared": "hash_cleared",
}
def _value(value: object) -> str:
"""One value in code, or a list the checker reads as any of its values."""
if isinstance(value, list):
return " or ".join(f"`{v}`" for v in value) if value else "`[]`"
return f"`{value}`"
def describe_change(change: dict) -> str:
"""One change in words, with the value before and after it."""
label = f"`{change['system']}/{change['name']}` {change['field']}"
kind, old, new = change["kind"], change["old"], change["new"]
if kind in ("hash_updated", "size_updated"):
return f"{label} {_value(old)} becomes {_value(new)}"
if kind == "hash_filled":
return f"{label} {_value(new)} added"
if kind == "required_aligned":
return f"`{change['system']}/{change['name']}` becomes {'required' if new else 'optional'}"
return f"{label} {_value(old)} no longer listed"
def change_items(report: dict, key: str) -> list[str]:
"""The lines a kind of change shows. A report written before values
were recorded names the entries only."""
kind = CHANGE_RECORDS.get(key)
changes = report.get("changes")
if kind and changes is not None:
return [describe_change(c) for c in changes if c["kind"] == kind]
items = report.get(key) or []
return [str(i) if key == "withheld" else f"`{i}`" for i in items]
def requirement_lines(report: dict) -> list[str]:
"""Each required flag aligned with the code, and what it is now."""
items = [
describe_change(c) for c in report.get("changes") or []
if c["kind"] == "required_aligned"
]
if not items:
return []
return _lookup_only(markup.details(
"note", f"Required flags aligned with the code ({len(items)})",
[f"- {item}" for item in items]))
def _lookup_only(block: list[str]) -> list[str]:
"""A list of entries changed, out of the site search: 129 "md5" in them
put this page above the one that explains MD5 checks."""
return ["", markup.block_open("section", markup.search_exclude()), "", *block, "", "</section>", ""]
def _plural(count: int, noun: str, plural: str = "") -> str:
return f"{count:,} {noun if count == 1 else plural or noun + 's'}"
def change_text(report: dict) -> str:
"""What the updated file changes, from the report's numbers.
The command line prints its own terse summary. The page states each
kind of change once, in plain terms, and leaves out what did not
happen. RetroPie's unit is a package, so its own sentence is kept.
"""
counts = report.get("counts")
if not counts:
return report["summary"]
parts = [f"{_plural(counts['kept'], 'entry', 'entries')} kept"]
extra = [
(counts["added"], "file", "files", "added"),
(len(report.get("hashes_updated") or []), "hash", "hashes", "updated"),
(report.get("required_aligned") or 0, "required flag", "required flags",
"aligned with the code"),
(len(report.get("hashes_filled") or []), "hash", "hashes", "added"),
(len(report.get("sizes_updated") or []), "size", "sizes", "updated"),
]
parts += [f"{_plural(n, one, many)} {verb}" for n, one, many, verb in extra if n]
return ", ".join(parts)
# Beyond this many entries a reason's list folds away.
LONG_LIST = 10
def candidate_lines(candidates: list[dict]) -> list[str]:
"""The entries no emulator the platform runs is known to open.
Each stays in the updated file. The count comes first, then the entries
grouped by reason, a long group in a block the reader opens.
"""
if not candidates:
return []
open_question = sum(c.get("verdict") == "undetermined" for c in candidates)
count = _plural(len(candidates), "entry", "entries")
sentence = (
f"{count} of the original {'is' if len(candidates) == 1 else 'are'} not "
"named, by name, path or hash, in the profile of any emulator this "
"platform runs. "
f"{'It stays' if len(candidates) == 1 else 'They stay'} in the updated file"
)
if open_question:
sentence += (
f", and {open_question} of them may still be read by an emulator "
"this project has not profiled in full"
)
lines = [sentence + ".", ""]
groups: dict[str, list[dict]] = {}
for candidate in candidates:
groups.setdefault(candidate.get("reason", ""), []).append(candidate)
for reason, entries in groups.items():
title = (reason[:1].upper() + reason[1:]).replace('"', "'")
items = [f"`{c['system']}` `{c['destination']}`" for c in entries]
if len(entries) > LONG_LIST:
lines.extend(_lookup_only(markup.details(
"note", f"{title} ({len(entries)})", [f"- {item}" for item in items])))
else:
lines.extend([f"{title}:", "", *[f"- {item}" for item in items], ""])
return lines
def _declaration(declaration: dict) -> str:
"""One declaration of a doubled destination: who declares it, its hash,
and the emulators that read the file it names."""
where = f"`{declaration['system']}`"
if declaration.get("component"):
where += f" (`{declaration['component']}`)"
parts = [where] + [
f"{field} {_value(values[0] if len(values) == 1 else values)}"
for field, values in (declaration.get("hashes") or {}).items()
]
readers = declaration.get("readers") or []
read = (
"read by " + ", ".join(
r["emulator"] + (f" (`{r['source_ref']}`)" if r.get("source_ref") else "")
for r in readers
)
if readers else "no emulator this platform runs is known to read this file"
)
return " ".join(parts) + f": {read}"
def doubled_lines(doubled: list[dict]) -> list[str]:
"""The destinations the original declares twice, for two files.
One path holds one file, so one of the two checks fails on every
install. Both entries stay in the updated file.
"""
if not doubled:
return []
count = _plural(len(doubled), "destination")
lines = [
f"{count} of the original {'is' if len(doubled) == 1 else 'are'} declared "
"twice, for two different files. One path holds one file, so one of the "
"two checks fails on every install. Both entries stay in the updated file.",
"",
]
for item in doubled:
lines.append(f"- `{item['destination']}`")
lines.extend(f" - {_declaration(d)}" for d in item["declarations"])
lines.append("")
return lines
def load_export_reports(directory: str = EXPORTS_DIR) -> list[dict]:
"""Every platform report the export wrote, by platform name."""
root = Path(directory)
if not root.is_dir():
return []
return [
json.loads(path.read_text(encoding="utf-8"))
for path in sorted(root.glob("*.json"))
]
def _display(platform: str, names: dict[str, str]) -> str:
return names.get(platform) or platform
def _updated_link(report: dict) -> str:
platform, files = report["platform"], report["files"]
if len(files) == 1:
path = f"{EXPORTS_DIR}/{platform}/{files[0]}"
return f"[`{Path(files[0]).name}`]({REPO_BLOB}/{path})"
return f"[{len(files)} files]({REPO_TREE}/{EXPORTS_DIR}/{platform})"
def _original_link(report: dict) -> str:
originals = report.get("originals") or {}
if len(originals) == 1:
(name, url), = originals.items()
return f"[`{Path(name).name}`]({url})"
return f"{len(originals)} files"
def generate_exports_page(reports: list[dict], names: dict[str, str]) -> str:
"""The page, names mapping each platform key to the name it displays."""
lines = [
"# Updated platform files",
"",
"Each platform keeps its own list of the BIOS files it checks: "
"libretro's `System.dat`, Batocera's `batocera-systems`, Recalbox's "
"`es_bios.xml` and so on. This project reads the emulators' source "
"code file by file, and offers each platform its own file with those "
"findings applied: a hash is updated where the emulator source states "
"another, and files the platform's emulators read are added. An entry "
"that no emulator the platform runs is known to open stays in the "
"file and is listed as a removal candidate, with the reason, on the "
"platform's section. It would leave the file only once the code of "
"every emulator that platform runs for the system is shown not to "
"read it. Where a value of an entry is "
"dropped, the platform's section lists it. Code the file carries is "
"patched in place. With the original files on hand, the tests run "
"the updated Batocera and ROCKNIX scripts (`--createReadme`), parse "
"`checkBIOS.sh` and the RetroPie scriptmodules with `bash -n`, and "
"check that every Recalbox entry carries the attributes the "
"`es_bios.xsd` Recalbox publishes requires.",
"",
"Each file starts from the revision of the original that this project "
"last read, so it compares cleanly with it, and every change can be "
"taken or left on its own. Each value comes from an emulator profile, "
"whose page cites where it was read. If a change does not fit a platform, an "
"issue on the [repository](https://github.com/Abdess/retrobios/issues) "
"is welcome: this project's profile is revised, and every platform's "
"file follows.",
"",
"A file is added only when the format can carry it. A platform that "
"checks an md5 needs one, so a file whose emulator source states no "
"md5 is not added, and neither is a file under a system the "
"platform's checker does not read. Those are counted on each "
"platform's section.",
"",
]
if not reports:
lines.extend([
"No updated file has been published yet. They are written by "
"`python scripts/export_native.py --all --fetch`.",
"",
])
return "\n".join(lines)
lines.extend([
"| Platform | Original file | Updated file | Changes |",
"|----------|------------|----------------|--------------|",
])
for report in reports:
platform = report["platform"]
lines.append(
f"| [{_display(platform, names)}](#{platform}) | "
f"{_original_link(report)} | {_updated_link(report)} | "
f"{change_text(report)} |"
)
lines.append("")
for report in reports:
platform = report["platform"]
lines.extend([f"## {_display(platform, names)} {{ #{platform} }}", ""])
text = change_text(report)
lines.extend([text[:1].upper() + text[1:] + ".", ""])
counts = report.get("counts") or {}
if counts.get("not_added"):
lines.extend([
f"{_plural(counts['not_added'], 'other file')} the emulators read "
f"{'is' if counts['not_added'] == 1 else 'are'} not added, for the "
"reasons above.",
"",
])
if counts.get("not_kept"):
lines.extend([
f"{_plural(counts['not_kept'], 'entry', 'entries')} of the original "
"cannot be written in this format and should be checked by hand.",
"",
])
lines.extend(candidate_lines(report.get("removal_candidates") or []))
lines.extend(doubled_lines(report.get("doubled") or []))
if report.get("invalid"):
lines.extend(markup.aside(
"warning", "The updated file does not pass the platform's own checks",
[f"- {issue}" for issue in report["invalid"]]))
originals = report.get("originals") or {}
files = report["files"]
raw = [f"{REPO_RAW}/{EXPORTS_DIR}/{platform}/{name}" for name in files]
# Every change as JSON, the report the page is written from.
changes = markup.button("Every change (JSON)", f"{API_EXPORTS}/{platform}.json")
if len(files) == 1:
lines.extend([
markup.button("Download the updated file", raw[0], primary=True) + " "
+ markup.button("See it on GitHub", f"{REPO_BLOB}/{EXPORTS_DIR}/{platform}/{files[0]}")
+ " " + changes,
"",
])
else:
lines.extend([
markup.button(f"Browse the {len(files)} updated files",
f"{REPO_TREE}/{EXPORTS_DIR}/{platform}", primary=True)
+ " " + changes,
"",
])
if len(originals) > 1:
lines.extend(markup.details(
"note", f"The {len(originals)} original files it is based on",
[f"- [`{name}`]({url})" for name, url in sorted(originals.items())]))
elif originals:
(name, url), = originals.items()
lines.extend([f"Based on [`{name}`]({url}).", ""])
lines.extend(requirement_lines(report))
for key, title in CHANGE_KINDS:
items = change_items(report, key)
if not items:
continue
lines.extend(_lookup_only(markup.details(
"note", f"{title} ({len(items)})", [f"- {item}" for item in items])))
return "\n".join(lines)
+76
View File
@@ -0,0 +1,76 @@
"""The guide part of the site: where each setup keeps its BIOS files.
A platform page opens on what someone holding the device needs: the folder,
the command, the pack, how to check. The words live in
``platforms/_guides.yml``, one guide per registered platform, beside the
device groups, the terminal tabs and the safety notes every guide shares.
This module loads that file, checks it against the registry and renders the
parts the pages share. The registry keeps the folder the pack unzips into
(``extract_to``) and the group a platform belongs to (``device_group``).
"""
from __future__ import annotations
from sitegen import markup
from model.guides import Guide, TERMINALS, TRUST_ITEMS, install_command
# The title over each command block, by the shell it is written for.
FENCE_TITLES = {"sh": "Terminal", "powershell": "PowerShell"}
def fence(shell: str, command: str, indent: str = "") -> list[str]:
"""A command block with its title, as every command on the site is shown."""
return [f'{indent}```{shell} title="{FENCE_TITLES[shell]}"', f"{indent}{command}", f"{indent}```"]
# Terminals named by where the command runs, not by the system it runs on.
PLACES = ("device", "server")
def terminal_tabs(
tabs: tuple[str, ...], args: dict[str, str], indent: str = "", steps: bool = True,
how: dict[str, str] | None = None,
under_steps: dict[str, list[str]] | None = None,
under_command: dict[str, list[str]] | None = None,
) -> list[str]:
"""Content tabs, one per place the command runs, each with how to open
the terminal there. Tab labels are shared across the site, so the reader's
choice carries from page to page. *how* replaces the shared text of a tab
for one setup. *under_steps* and *under_command* add lines to a tab
after its text and after its command (sitesteps.install_box)."""
items = []
for key in tabs:
label, shared, shell = TERMINALS[key]
if len(tabs) == 1 and key in PLACES:
label = "" # one place, which the text around already names
text = (how or {}).get(key) or shared
body = [text, ""] if steps else []
body += (under_steps or {}).get(key, [])
items.append((label, body + fence(shell, install_command(shell, args.get(key, "")))
+ [""] + (under_command or {}).get(key, [])))
return markup.tabs(items, indent)
def platform_args(name: str, guide: Guide) -> dict[str, str]:
"""The options of the command on a platform page, per tab."""
args: dict[str, str] = {}
for key in guide.run:
if guide.on_card:
card = "E:\\" if key == "windows" else "/path/to/card"
args[key] = f"--platform {name} --dest {card}"
elif guide.dest:
args[key] = f"--platform {name} --dest {guide.dest}"
else:
args[key] = f"--platform {name}"
return args
def trust_box(prefix: str, indent: str = "") -> list[str]:
"""Is it safe, under every command on a guide page: the trust items."""
return markup.details("note", "Is it safe?", [
*(f"- {item}" for item in TRUST_ITEMS),
"",
f"[Read the script first]({prefix}wiki/faq.md#is-piping-the-installer-into-a-shell-safe)",
], indent)
+258
View File
@@ -0,0 +1,258 @@
"""The handheld launchers the site serves, and where each one goes.
The four archives scripts/build_port.py writes carry install.py pinned by
SHA-256, so they change with the installer, not with the BIOS packs. The
site builds them from the commit it is built from and serves them under
get/handheld/, beside the bootstraps that pin the same installer
(sitebootstrap.py). build_archive refuses an install.py that install.sh
does not pin: a stale pin stops the site build, the last good archives
staying served.
LAUNCHERS is the one description of where each archive goes on the card
and which menu starts it. The handheld tables of wiki/installer.md are
written from it (scripts/generate_installer_doc.py), and so is the block
each get/<platform>/ page and the handheld page carry.
"""
from __future__ import annotations
import hashlib
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from sitegen import markup
from core.artifacts import write_bytes_atomic
from build_port import ARCHIVES, BATOCERA_ZIP, MUOS_APP, PORT_ZIP, TOOLS_ZIP, build_archive
from core.paths import REPO_ROOT
# Below the site's root: get/handheld/RetroBIOS.zip.
SERVED_DIR = "get/handheld"
# The page of the systems no registered platform answers for. It shares
# its name with the handheld guide (platforms/linux-handhelds.md), so the
# sidebar files it with that guide, as get/batocera.md is with
# platforms/batocera.md.
GROUP_PAGE = "linux-handhelds"
GROUP_TITLE = "RetroBIOS app for handhelds"
@dataclass(frozen=True)
class Launcher:
"""One row of the installer's handheld table.
*systems* are named as the installer page names them. *copy_to* is
where the file goes, and *places* gives a system its own folder when
the row's systems differ there. *lead* opens the row's first cell.
"""
archive: str
systems: tuple[str, ...]
copy_to: str
start: str
extracted: bool = False
lead: str = ""
places: tuple[tuple[str, tuple[str, ...]], ...] = field(default=())
def folder_for(self, system: str) -> str:
return next((folder for folder, systems in self.places if system in systems),
self.copy_to)
LAUNCHERS: tuple[Launcher, ...] = (
Launcher(MUOS_APP, ("muOS",),
"`ARCHIVE` at the root of the card, then install it from the Archive Manager",
"Applications"),
Launcher(PORT_ZIP, ("ArkOS", "dArkOS", "ROCKNIX", "AmberELEC", "JELOS", "KNULLI"),
"PortMaster's `autoinstall` folder", "Ports, after opening PortMaster once",
lead="Any other system with [PortMaster](https://portmaster.games/)",
places=(("`/roms/ports/PortMaster/autoinstall/`", ("ROCKNIX", "AmberELEC")),
("`/roms/tools/PortMaster/autoinstall/`", ("ArkOS",)),
("`/userdata/system/.local/share/PortMaster/autoinstall/`", ("KNULLI",)))),
Launcher(BATOCERA_ZIP, ("Batocera", "KNULLI"), "`roms/ports` on the SHARE partition",
"Ports, after updating the game list", extracted=True),
Launcher(TOOLS_ZIP, ("ArkOS", "dArkOS"), "`tools` on the EASYROMS partition",
"Options, then Tools", extracted=True),
Launcher(TOOLS_ZIP, ("ROCKNIX", "JELOS"),
"`/storage/.config/modules`, over the network share or SSH", "Tools",
extracted=True),
Launcher(TOOLS_ZIP, ("AmberELEC",), "`/storage/.config/distribution/modules`", "Tools",
extracted=True),
)
# The registered platform whose get/ page answers for a system. A system
# outside this map is on the handheld page.
PLATFORM_OF = {"Batocera": "batocera", "KNULLI": "knulli", "ROCKNIX": "rocknix",
"AmberELEC": "amberelec"}
def systems() -> list[str]:
"""Every system a launcher runs on, in table order."""
return list(dict.fromkeys(name for launcher in LAUNCHERS for name in launcher.systems))
def group_systems() -> list[str]:
return [name for name in systems() if name not in PLATFORM_OF]
def joined(names: list[str], last: str = "and") -> str:
"""muOS, ArkOS and JELOS."""
return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} {last} {names[-1]}"
def page_of(system: str) -> str:
"""The site page that holds the download for *system*."""
return f"get/{PLATFORM_OF.get(system, GROUP_PAGE)}.md"
def launchers_for(system: str) -> list[Launcher]:
"""The launchers of *system*, its own menu first and PortMaster last."""
own = [launcher for launcher in LAUNCHERS if system in launcher.systems]
return sorted(own, key=lambda launcher: launcher.archive == PORT_ZIP)
@dataclass(frozen=True)
class Served:
data: bytes
@property
def size(self) -> int:
return len(self.data)
@property
def sha256(self) -> str:
return hashlib.sha256(self.data).hexdigest()
_built: dict[tuple[str, str], Served] = {}
def served(name: str, root: Path = REPO_ROOT) -> Served:
"""The bytes of archive *name* as build_port builds it from *root*,
built once per run: the page states the size and hash of the file the
same run writes."""
key = (str(root.resolve()), name)
if key not in _built:
scratch_root = root / "tmp"
scratch_root.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=scratch_root, prefix="handheld-") as scratch:
path = build_archive(name, Path(scratch) / name, root)
_built[key] = Served(path.read_bytes())
return _built[key]
def write_launchers(public: Path, root: Path = REPO_ROOT) -> list[Path]:
"""Write every launcher archive under the site's public folder, each
only when its bytes moved."""
folder = public / SERVED_DIR
folder.mkdir(parents=True, exist_ok=True)
written = []
for name in ARCHIVES:
path = folder / name
data = served(name, root).data
if not path.is_file() or path.read_bytes() != data:
write_bytes_atomic(str(path), data)
written.append(path)
return written
def table_rows() -> list[str]:
"""The handheld table of the installer page, each system linked to the
page that holds its download. The page sits in wiki/."""
def name(system: str) -> str:
return f"[{system}](../{page_of(system)})"
rows = ["| System | File | Copy it to | Start it from |",
"|--------|------|------------|---------------|"]
for launcher in LAUNCHERS:
names = ", ".join(name(system) for system in launcher.systems)
first = f"{launcher.lead}: {names}" if launcher.lead else names
file = f"`{launcher.archive}`" + (", extracted" if launcher.extracted else "")
copy_to = launcher.copy_to
if launcher.places:
copy_to += ": " + ", ".join(
f"{folder} on {' and '.join(where)}" for folder, where in launcher.places)
rows.append(f"| {first} | {file} | {copy_to} | {launcher.start} |")
return rows
def _anchor(system: str) -> str:
"""Where *system*'s downloads sit on its page."""
return "on-the-handheld" if system in PLATFORM_OF else system.casefold()
def download_rows() -> list[str]:
"""The short table that opens the installer's handheld section: each
system, its files as links to the site's copies, and its page. The
page sits in wiki/."""
rows = ["| System | Download | Steps |", "|--------|----------|-------|"]
for system in systems():
files = ", ".join(
f"[{launcher.archive}](../{SERVED_DIR}/{launcher.archive})"
+ (" (PortMaster)" if launcher.archive == PORT_ZIP else "")
for launcher in launchers_for(system))
page = f"../{page_of(system)}#{_anchor(system)}"
rows.append(f"| {system} | {files} | [{system} steps]({page}) |")
return rows
def _launcher_block(launcher: Launcher, system: str, root: Path) -> list[str]:
archive = served(launcher.archive, root)
verb = "Unzip it into" if launcher.extracted else "Copy it to"
via = " (with PortMaster)" if launcher.archive == PORT_ZIP else ""
return [
markup.button(f"Download {launcher.archive}", f"handheld/{launcher.archive}",
primary=True) + via,
"",
f"- {verb} {launcher.folder_for(system)}.",
f"- Start it from {launcher.start}.",
f"- {_size(archive.size)}. SHA-256: `{archive.sha256}`",
"",
]
def _size(count: int) -> str:
if count >= 1024 * 1024:
return f"{count / 1024 ** 2:.1f} MB"
return f"{count / 1024:.0f} KB"
APP_LINE = "RetroBIOS also runs on the handheld, with the controller."
# The installer's handheld section opens on the download of every system.
INSTALLER_SECTION = "wiki/installer.md#on-a-handheld-the-retrobios-port"
DETAILS_LINK = f"[Every system's file](../{INSTALLER_SECTION})"
def platform_block(platform: str, root: Path = REPO_ROOT) -> list[str]:
"""The app section of get/<platform>/, empty for a platform no launcher
runs on."""
system = next((name for name, key in PLATFORM_OF.items() if key == platform), None)
if system is None:
return []
lines = ["## On the handheld { #on-the-handheld }", "", APP_LINE, ""]
for launcher in launchers_for(system):
lines += _launcher_block(launcher, system, root)
return [*lines, DETAILS_LINK, ""]
def group_page(root: Path = REPO_ROOT) -> str:
"""get/linux-handhelds/: the app for the systems no setup page answers
for, then the setup pages that carry it for the others."""
names = group_systems()
listed = joined(names)
lines = [
"---", "search: exclude",
f'description: "The RetroBIOS app for {listed}: the file to put on the card '
'and the menu that starts it."',
"---", "",
f"# {GROUP_TITLE}", "",
f"{APP_LINE} Each system has its file below.", "",
]
for system in names:
lines += [f"## {system}", ""]
for launcher in launchers_for(system):
lines += _launcher_block(launcher, system, root)
others = [f"[{name}]({PLATFORM_OF[name]}.md#on-the-handheld)"
for name in sorted(PLATFORM_OF, key=str.casefold)]
lines += ["## Other systems", "", f"On {joined(others, 'or')}: on its page.", "",
DETAILS_LINK, ""]
return "\n".join(lines)
+279
View File
@@ -0,0 +1,279 @@
"""The page constructs the generator writes, in the syntax of the site engine.
Every block that is not plain Markdown (a callout, a collapsible block, OS
tabs, a button, a card grid) is written through one of these functions, so
the generator holds no engine syntax of its own. Bodies are passed without
indentation: the function indents them as the engine reads them.
The site is built with Astro Starlight. The MkDocs Material syntax the site
was first written in stays as one thing only: the yardstick of the size
budgets that split long pages (system pages, platform sections). Those
budgets were set on that Markdown, and measuring it keeps every page cut
at the same file, so no card changes address.
"""
from __future__ import annotations
import html
import re
from collections.abc import Iterator
from contextlib import contextmanager
ENGINES = ("mkdocs", "starlight")
_engine = "starlight"
# Material's callout kinds, by the role Starlight gives them.
ASIDE_ROLES = {
"note": "note", "info": "note", "abstract": "note", "example": "note",
"question": "note", "quote": "note", "tip": "tip", "success": "tip",
"warning": "caution", "failure": "danger", "danger": "danger", "bug": "danger",
}
# The attribute that keeps an element out of the site search.
SEARCH_EXCLUDE = {"mkdocs": "data-search-exclude", "starlight": "data-pagefind-ignore"}
def set_engine(name: str) -> None:
global _engine
if name not in ENGINES:
raise ValueError(f"unknown site engine {name!r}, expected one of {ENGINES}")
_engine = name
def engine() -> str:
return _engine
@contextmanager
def using(name: str) -> Iterator[None]:
"""Write in another syntax for a while: a page split by size is
measured in the MkDocs Markdown its budgets were set on."""
previous = _engine
set_engine(name)
try:
yield
finally:
set_engine(previous)
def starlight() -> bool:
return _engine == "starlight"
def search_exclude() -> str:
return SEARCH_EXCLUDE[_engine]
def inline_html(text: str) -> str:
"""Inline Markdown (code, bold, links) for text placed inside raw HTML,
where Markdown is not read."""
parts = re.split(r"(`[^`]+`)", text)
out = []
for part in parts:
if part.startswith("`") and part.endswith("`") and len(part) > 1:
out.append(f"<code>{html.escape(part[1:-1], quote=False)}</code>")
continue
part = html.escape(part, quote=False)
part = re.sub(r"\*\*([^*]+)\*\*", r"<strong>\1</strong>", part)
part = re.sub(r"\[([^\]]+)\]\(([^)\s]+)\)", _link, part)
out.append(part)
return "".join(out)
# A scheme before any slash: javascript:, data:, vbscript: and the like.
_SCHEME = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")
def _link(match: re.Match) -> str:
"""A Markdown link as an anchor when its target is http(s) or relative,
else left as the text it was. The target is already escaped for text,
quotes are escaped for the attribute."""
label, href = match.group(1), match.group(2)
if _SCHEME.match(href) and not re.match(r"^https?://", href, re.IGNORECASE):
return match.group(0)
return f'<a href="{href.replace(chr(34), "&quot;").replace(chr(39), "&#x27;")}">{label}</a>'
def _indented(lines: list[str], pad: str) -> list[str]:
return [f"{pad}{line}" if line.strip() else "" for line in lines]
def _trim(lines: list[str]) -> list[str]:
start, end = 0, len(lines)
while start < end and not lines[start].strip():
start += 1
while end > start and not lines[end - 1].strip():
end -= 1
return list(lines[start:end])
def aside(kind: str, title: str, body: list[str], indent: str = "") -> list[str]:
"""A callout that is always open."""
body = _trim(body)
if _engine == "mkdocs":
return [f'{indent}!!! {kind} "{title}"', "", *_indented(body, indent + " "), ""]
label = title.replace("[", "\\[").replace("]", "\\]")
fence = "::::" if any(line.lstrip().startswith(":::") for line in body) else ":::"
return [f"{indent}{fence}{ASIDE_ROLES.get(kind, 'note')}[{label}]",
*_indented(body, indent), f"{indent}{fence}", ""]
def details(kind: str, title: str, body: list[str], indent: str = "", opened: bool = False) -> list[str]:
"""A collapsible block, closed unless *opened*."""
body = _trim(body)
if _engine == "mkdocs":
marker = "???+" if opened else "???"
return [f'{indent}{marker} {kind} "{title}"', "", *_indented(body, indent + " "), ""]
role = ASIDE_ROLES.get(kind, "note")
state = " open" if opened else ""
return [
f'{indent}<details class="rb-details rb-details-{role}"{state}>',
f"{indent}<summary>{inline_html(title)}</summary>",
"",
*_indented(body, indent),
"",
f"{indent}</details>",
"",
]
def tabs(items: list[tuple[str, list[str]]], indent: str = "", sync: str = "os") -> list[str]:
"""Content tabs. Tabs that share a label share the reader's choice
across pages.
One item is no choice: 142 bars offered a single tab, most of them
"On the device" under a heading that says so. Its body stands alone,
led by its label when it has one: the RetroPie card is read from Linux
only, and the label is where the page said so."""
lines: list[str] = []
if len(items) == 1:
label, body = items[0]
lead = [f"{indent}**{label}**", ""] if label else []
return [*lead, *_indented(_trim(body), indent), ""]
if _engine == "mkdocs":
for label, body in items:
lines += [f'{indent}=== "{label}"', "", *_indented(_trim(body), indent + " "), ""]
return lines
lines.append(f'{indent}<Tabs syncKey="{sync}">')
for label, body in items:
lines += [f'{indent}<TabItem label="{html.escape(label)}">', "",
*_indented(_trim(body), indent), "", f"{indent}</TabItem>"]
return [*lines, f"{indent}</Tabs>", ""]
def button(text: str, target: str, primary: bool = False) -> str:
"""A link drawn as a button."""
if _engine == "mkdocs":
classes = ".md-button .md-button--primary" if primary else ".md-button"
return f"[{text}]({target}){{ {classes} }}"
classes = "rb-button rb-button-primary" if primary else "rb-button"
return f'<a class="{classes}" href="{html.escape(target)}">{inline_html(text)}</a>'
def image(alt: str, src: str, **attributes: str) -> str:
"""An image with HTML attributes (width, align)."""
if _engine == "mkdocs":
attrs = " ".join(f"{key}={value}" for key, value in attributes.items())
return f"![{alt}]({src}){{ {attrs} }}"
attrs = "".join(f' {key}="{html.escape(str(value))}"' for key, value in attributes.items())
return f'<img src="{html.escape(src)}" alt="{html.escape(alt)}"{attrs}>'
def hash_value(value: object, copy: bool = False) -> str:
"""A hash printed whole, in the hash style. One element under Starlight:
a span around a code span was 1,400 extra elements on a page of cards.
*copy* marks it for the copy button the site script adds after it."""
text = str(value).replace("`", "'")
if _engine == "mkdocs":
return f'<span class="rb-hash">`{text}`</span>'
marker = ' data-copy=""' if copy else ""
return f'<code class="rb-hash"{marker}>{html.escape(text, quote=False)}</code>'
def block_open(tag: str, attributes: str = "") -> str:
"""The opening tag of an HTML block whose content is Markdown."""
attributes = f" {attributes.strip()}" if attributes.strip() else ""
if _engine == "mkdocs":
return f"<{tag}{attributes} markdown>"
return f"<{tag}{attributes}>"
def card_grid(cards: list[tuple[str, list[str]]]) -> list[str]:
"""Cards in a grid: a bold title line and a body each."""
lines = [block_open("div", 'class="grid cards"' if _engine == "mkdocs" else 'class="rb-cards"'), ""]
for title, body in cards:
if _engine == "mkdocs":
lines += [f"- **{title}**", "", *_indented(_trim(body), " "), ""]
else:
lines += ['<div class="rb-card">', "", f"**{title}**", "", *_trim(body), "", "</div>", ""]
return [*lines, "</div>", ""]
def initials(name: str) -> str:
"""Up to two capitals of a name, for a setup that has no logo: MyMinUI is MM.
A name written from a lowercase prefix keeps it: iPhone is iP, not PP."""
if len(name) > 1 and name[0].islower() and name[1].isupper():
return name[:2]
capitals = [c for c in name if c.isupper()]
return "".join(capitals[:2]) or name[:2].upper()
def _tile_mark(name: str, logo: str, lazy: bool = False) -> str:
"""A tile's logo, or its initials. *lazy* for a tile below the first
screen: the browser fetches its logo when the reader scrolls near it."""
if logo:
loading = ' loading="lazy"' if lazy else ""
return (f'<img class="rb-card-logo" src="{html.escape(logo)}" alt="" '
f'width="40" height="40"{loading}>')
# The same square as a logo, drawn on white like the logos are. The
# letters are the stylesheet's (::before), not text of the page: the
# tile's name follows, and a copy or a text dump read "MMMyMinUI".
return (f'<span class="rb-card-logo rb-card-initials" data-initials="{html.escape(initials(name))}" '
'aria-hidden="true"></span>')
# Tiles in the first row of a grid at its widest, two columns of 15rem in
# the content column: the logos the reader may see without scrolling.
FIRST_ROW_TILES = 2
def platform_tiles(tiles: list[tuple[str, str, str, str]], eager: int = 0) -> list[str]:
"""One link per setup: its logo (or its initials), its name and where it
runs. *tiles* are (name, target, logo, runs_on). The first *eager*
logos load with the page, the others when the reader scrolls to them.
One HTML line: a grid of links is a menu, not prose, and the Markdown
around it reads none of it."""
links = "".join(
f'<a class="rb-card rb-tile" href="{html.escape(target)}">'
f"{_tile_mark(name, logo, lazy=index >= eager)}"
f'<strong class="rb-tile-name">{html.escape(name)}</strong> '
f'<span class="rb-tile-runs">{inline_html(runs_on)}</span></a> '
for index, (name, target, logo, runs_on) in enumerate(tiles)
)
return [f'<div class="rb-cards rb-tiles">{links}</div>', ""]
def steps(items: list[str]) -> list[str]:
"""An ordered list drawn as numbered steps."""
return [block_open("div", 'class="rb-steps"'), "",
*(f"{number}. {item}" for number, item in enumerate(items, 1)), "", "</div>", ""]
def heading_attributes(anchor: str = "", classes: str = "", search: bool = True) -> str:
"""The attribute block of a heading: its id, classes, and whether the
search reads it."""
parts = [f"#{anchor}" if anchor else "", *(f".{c}" for c in classes.split())]
if not search:
parts.append(search_exclude())
parts = [part for part in parts if part]
return f" {{ {' '.join(parts)} }}" if parts else ""
def site_href(path: str) -> str:
"""A link to a site address written in raw HTML (``files/?sha1=...``),
which no Markdown resolution reaches: rooted at the site under Starlight,
relative to a page two levels deep under MkDocs."""
if _engine == "mkdocs":
return f"../../{path}"
return f"/retrobios/{path}"
+759
View File
@@ -0,0 +1,759 @@
"""The measurements the site shows, from the records under measurements/.
The records are core probe runs, one append-only .jsonl per emulator with one
full record per line (measurement_records.py). From them the build writes,
never committed:
public/data/measurements/index.json the compact index the explorer and
the emulator pages read, one item
per emulator and subject
public/downloads/measurements.sqlite every record, normalised
public/downloads/measurements/<emu>.sqlite one database per emulator
Three places read the index: the Proof lines of an emulator page (only the
records a profile's `evidence:` names, or one tied to an issue), the
Measurements explorer page and the host table of the methodology page. Runs
are made on demand, to settle a dispute or an issue, to back a correction
sent to a platform, or to smoke-test packs before a release: there is no
showcase of every run. A record links its line at the last commit that
touched measurements/. Benchmarks stay in the records and the SQLite files,
never on a page.
"""
from __future__ import annotations
import html
import json
import os
import re
import sqlite3
import sys
from dataclasses import dataclass
from pathlib import Path
import measurement_records as mr
from sitegen import markup
from core.artifacts import json_text, write_if_changed
from sitegen.render import _escape_tags
from core.paths import REPO_ROOT
ROOT = REPO_ROOT
REPO = "https://github.com/Abdess/retrobios"
EXPLORER_PAGE = "measurements.md"
METHOD_PAGE = "wiki/measurements.md"
HOSTS_MARKER = "<!-- measurements-hosts -->"
INDEX_PATH = Path("data") / "measurements" / "index.json"
SQLITE_PATH = Path("downloads") / "measurements.sqlite"
PER_EMULATOR_DIR = Path("downloads") / "measurements"
SQLITE_SCHEMA_VERSION = "3"
# Observables the variants table leaves out: one value per sampled frame.
BULKY_OBSERVABLES = ("frame_hashes",)
INDEX_SCHEMA_VERSION = 1
# What a maintainer saw in an issue's runs, by record subject.
OBSERVATIONS = Path("tests") / "campaign" / "observations.yml"
# A Proof line lists this many record links at most, else one link to the file.
MAX_RECORD_LINKS = 8
# --------------------------------------------------------------------------
# Index
# --------------------------------------------------------------------------
def host_summary(host: dict) -> str:
parts = [host.get("cpu_model") or "unknown CPU"]
if host.get("cpu_count"):
parts.append(f"{host['cpu_count']} CPUs")
parts.append(f"{host.get('machine', '')} Linux {host.get('kernel', '')}".strip()
if "Linux" in host.get("os", "") else host.get("os", ""))
parts.append(f"Python {host.get('python', '')}")
before, after = host.get("load_before"), host.get("load_after")
if before and after:
parts.append(f"load {before[0]} before, {after[0]} after")
return ", ".join(part for part in parts if part)
def permalink(repo: str, commit: str, path: str, line: int | None = None) -> str:
return f"{repo}/blob/{commit}/{path}" + (f"#L{line}" if line else "")
BOOTS_BUILTIN = "boots on built-in BIOS"
def shown_verdict(variant: dict) -> str:
"""A variant's verdict as the pages say it: a boot on the core's
built-in BIOS is named so, never taken for the staged file's."""
if variant["verdict"] == "boots" and variant.get("bios_used") == "builtin":
return BOOTS_BUILTIN
return variant["verdict"]
def verdicts_of(record: dict) -> list[dict]:
"""Each variant's boot verdict, from record version 4 on, and the BIOS
it ran from version 5 on."""
return [{"variant": v["label"], "verdict": shown_verdict(v), "bios_used": v.get("bios_used", "unknown"),
"detail": (v.get("verdict_evidence") or {}).get("detail", ""),
"staged": sorted(name for name, sha1 in (v.get("system_files") or {}).items() if sha1)}
for v in record["variants"] if "verdict" in v]
def result_of(record: dict) -> tuple[str, str]:
"""The status and statement a page shows for a record.
A run, or a check compared on the sampled frames, is shown by its boot
verdicts: one verdict when every variant has it, else `mixed`, each
variant named in the statement. A check on another observable keeps
its comparison. A frame comparison recorded before the boot oracle
shows `no verdict`: frames that differ prove nothing about a boot.
"""
check = record.get("check") or {}
result = check.get("result") or {}
verdicts = verdicts_of(record)
by_frames = record["kind"] == "run" or check.get("observable") == "frame_hashes"
if verdicts and by_frames:
values = {v["verdict"] for v in verdicts}
status = values.pop() if len(values) == 1 else "mixed"
if record["kind"] == "run":
return status, verdicts[0]["detail"]
return status, ". ".join(f"{v['variant']}: {v['verdict']}" for v in verdicts)
if by_frames:
return "no verdict", ("recorded before the boot oracle. Its frames were compared, which "
"settles nothing about a boot")
return result.get("status") or "ran", result.get("statement") or ""
def opened(record: dict) -> str | None:
"""The staged name a check varied, when strace saw the core open it in
every repetition of a variant that staged it."""
name = (record.get("check") or {}).get("variable")
if not isinstance(name, str):
return None
for variant in record["variants"]:
reps = variant.get("repetitions") or []
if (variant.get("system_files") or {}).get(name) and reps and all(
any(f.get("path") == name for f in rep.get("files_opened") or ()) for rep in reps):
return name
return None
def load_observations(path: Path) -> dict[str, dict]:
"""Each record id or subject an observation covers, with its issue
number and words."""
import yaml
if not path.is_file():
return {}
out = {}
for issue, entries in (yaml.safe_load(path.read_text(encoding="utf-8")) or {}).items():
named = ISSUE_SUBJECT.match(f"{issue}-")
if named is None:
raise ValueError(f"{path}: {issue!r} is not an issue<number> key")
number = named["number"]
for entry in entries:
for key in [*entry.get("records", ()), *entry.get("subjects", ())]:
out[key] = {"issue": number, "said": entry["said"]}
return out
def shown_of(record: dict) -> list | None:
"""What a record showed that a page can state: ["text", words] from
its boot verdicts, ["opened", name] for a staged name strace saw the
core open, or None."""
verdicts = verdicts_of(record)
if verdicts:
return ["text", proof_result(verdicts)]
name = opened(record)
return ["opened", name] if name else None
def index_item(entry: mr.Stored, runs: int, source: dict, profiles: dict,
system_names: dict[str, str], ancestry: set[str] | None = None,
records: list[dict] | None = None) -> dict:
record = entry.record
profile = profiles.get(entry.emulator) or {}
check = record.get("check") or {}
core = record["core"]
content = (record["inputs"].get("content") or {})
return {
"emulator": entry.emulator,
"emulator_name": str(profile.get("emulator", entry.emulator)),
"profiled": bool(profile),
"systems": sorted(set(profile.get("systems") or [])),
"system_names": [system_names.get(s) or s for s in sorted(set(profile.get("systems") or []))],
"subject": record["subject"],
"kind": record["kind"],
"claim": check.get("claim"),
"method": check.get("method"),
"observable": check.get("observable"),
"variable": check.get("variable"),
"status": result_of(record)[0],
"statement": result_of(record)[1],
"verdicts": verdicts_of(record),
"content": content.get("label"),
"variants": len(record["variants"]),
"repetitions": record["inputs"]["repetitions"],
"flags": len(record["flags"]),
"date": record["recorded_at"],
"host": host_summary(record["host"]),
"core": {
"library": " ".join(filter(None, [core.get("library_name"), core.get("library_version")])),
"file": core["file"], "sha256": core["sha256"], "repo": core.get("repo"),
"commit": core.get("commit"), "build": core.get("build_command"),
},
"frontend_commit": record["frontend"].get("commit"),
"id": record["id"],
"runs": runs,
"record_url": permalink(source["repo"], source["commit"], mr.records_path(entry.emulator), entry.line),
"records": records if records is not None else [],
"sqlite": f"downloads/measurements/{entry.emulator}.sqlite",
"proves": proves(ancestry or {record["id"]}, profile),
}
def build_index(stored: list[mr.Stored], source: dict | None, profiles: dict,
system_names: dict[str, str] | None = None,
observations: dict[str, dict] | None = None) -> dict:
"""One item per (emulator, subject): its latest record not superseded."""
by_subject: dict[tuple[str, str], list[mr.Stored]] = {}
live_ids = {r["id"] for r in mr.live(s.record for s in stored)}
ancestors = lineage(stored)
for entry in stored:
# A benchmark only chooses between variants: it stays in the records.
if entry.record["id"] in live_ids and entry.record["kind"] != "bench":
by_subject.setdefault((entry.emulator, entry.record["subject"]), []).append(entry)
items = []
for key in sorted(by_subject):
entries = by_subject[key]
latest = max(entries, key=lambda s: (s.record["recorded_at"], s.line))
profile = profiles.get(key[0]) or {}
records = [{"url": permalink((source or {})["repo"], (source or {})["commit"],
mr.records_path(s.emulator), s.line),
"proves": proves(ancestors.get(s.record["id"]) or {s.record["id"]}, profile),
"shown": shown_of(s.record),
"observed": (observations or {}).get(s.record["id"]) or (observations or {}).get(key[1])}
for s in sorted(entries, key=lambda s: s.line)]
items.append(index_item(latest, len(entries), source or {}, profiles, system_names or {},
ancestors.get(latest.record["id"]), records))
items.sort(key=lambda item: (item["emulator"], item["date"], item["subject"]))
return {
"schema_version": INDEX_SCHEMA_VERSION,
"kind": "measurements",
"repo": (source or {}).get("repo"),
"commit": (source or {}).get("commit"),
"records": len(stored),
"count": len(items),
"items": items,
}
# --------------------------------------------------------------------------
# SQLite
# --------------------------------------------------------------------------
SCHEMA_SQL = """
PRAGMA journal_mode = OFF;
PRAGMA synchronous = OFF;
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE cores (
sha256 TEXT PRIMARY KEY, file TEXT NOT NULL, repo TEXT, commit_sha TEXT,
build_command TEXT, compiler TEXT, library_name TEXT, library_version TEXT
);
CREATE TABLE hosts (
id INTEGER PRIMARY KEY, cpu_model TEXT, cpu_count INTEGER, os TEXT NOT NULL,
kernel TEXT NOT NULL, machine TEXT NOT NULL, python TEXT NOT NULL
);
CREATE TABLE emulator_systems (
emulator TEXT NOT NULL, system TEXT NOT NULL, PRIMARY KEY (emulator, system)
);
CREATE TABLE runs (
id TEXT PRIMARY KEY, emulator TEXT NOT NULL, subject TEXT NOT NULL,
kind TEXT NOT NULL, recorded_at TEXT NOT NULL, supersedes TEXT,
superseded INTEGER NOT NULL, core_sha256 TEXT NOT NULL REFERENCES cores(sha256),
host_id INTEGER NOT NULL REFERENCES hosts(id), load_before TEXT, load_after TEXT,
max_load REAL, frontend_commit TEXT, script_sha256 TEXT NOT NULL,
script_modified INTEGER, flags TEXT NOT NULL, record_url TEXT NOT NULL,
line INTEGER NOT NULL,
migrated_from_version INTEGER
);
CREATE TABLE inputs (
run_id TEXT PRIMARY KEY REFERENCES runs(id), content_label TEXT, content_sha1 TEXT,
content_size INTEGER, options TEXT NOT NULL, env TEXT NOT NULL, frames INTEGER NOT NULL,
warmup INTEGER NOT NULL, repetitions INTEGER NOT NULL, presses TEXT NOT NULL,
observables TEXT NOT NULL, frame_hash_every INTEGER NOT NULL, joypad_ports INTEGER NOT NULL
);
CREATE TABLE content_tracks (
run_id TEXT NOT NULL REFERENCES runs(id), position INTEGER NOT NULL,
file TEXT NOT NULL, sha1 TEXT NOT NULL, size INTEGER NOT NULL,
PRIMARY KEY (run_id, position)
);
CREATE TABLE checks (
run_id TEXT PRIMARY KEY REFERENCES runs(id), claim TEXT NOT NULL, method TEXT NOT NULL,
observable TEXT NOT NULL, variable TEXT NOT NULL, status TEXT NOT NULL,
statement TEXT NOT NULL
);
CREATE TABLE check_groups (
run_id TEXT NOT NULL REFERENCES runs(id), position INTEGER NOT NULL,
value TEXT, value_sha1 TEXT, variants TEXT NOT NULL, PRIMARY KEY (run_id, position)
);
CREATE TABLE variants (
run_id TEXT NOT NULL REFERENCES runs(id), position INTEGER NOT NULL,
label TEXT NOT NULL, repetitions INTEGER NOT NULL, loaded INTEGER NOT NULL,
flags TEXT NOT NULL, observables TEXT NOT NULL, files_opened TEXT,
files_probed_absent TEXT, tracing TEXT, verdict TEXT, verdict_evidence TEXT,
PRIMARY KEY (run_id, position)
);
CREATE TABLE system_files (
run_id TEXT NOT NULL REFERENCES runs(id), variant_position INTEGER NOT NULL,
destination TEXT NOT NULL, sha1 TEXT,
PRIMARY KEY (run_id, variant_position, destination)
);
CREATE TABLE benchmarks (
run_id TEXT NOT NULL REFERENCES runs(id), metric TEXT NOT NULL,
median REAL NOT NULL, mean REAL NOT NULL, stdev REAL NOT NULL,
min REAL NOT NULL, max REAL NOT NULL, PRIMARY KEY (run_id, metric)
);
CREATE INDEX runs_emulator_idx ON runs(emulator, subject);
CREATE INDEX runs_subject_idx ON runs(subject);
CREATE INDEX emulator_systems_system_idx ON emulator_systems(system);
CREATE INDEX checks_claim_idx ON checks(claim);
CREATE INDEX system_files_sha1_idx ON system_files(sha1);
"""
TABLES = ("meta", "cores", "hosts", "emulator_systems", "runs", "inputs", "content_tracks",
"checks", "check_groups", "variants", "system_files", "benchmarks")
def _host_key(host: dict) -> tuple:
return tuple(json_text(host.get(k)) for k in ("cpu_model", "cpu_count", "os", "kernel",
"machine", "python"))
def write_sqlite(destination: Path, stored: list[mr.Stored], source: dict | None, profiles: dict,
scratch: Path) -> None:
"""A deterministic database of the records: sorted rows, no clock."""
scratch.mkdir(parents=True, exist_ok=True)
temp = scratch / f"{destination.stem}-{os.getpid()}.sqlite"
temp.unlink(missing_ok=True)
destination.parent.mkdir(parents=True, exist_ok=True)
stored = sorted(stored, key=lambda s: (s.emulator, s.line))
live_ids = {r["id"] for r in mr.live(s.record for s in stored)}
hosts = {key: number for number, key in enumerate(sorted({_host_key(s.record["host"]) for s in stored}), 1)}
connection = sqlite3.connect(temp)
try:
connection.executescript(SCHEMA_SQL)
meta = {
"schema_version": SQLITE_SCHEMA_VERSION,
"record_version": str(mr.RECORD_VERSION),
"measurements_repo": (source or {}).get("repo") or "",
"measurements_commit": (source or {}).get("commit") or "",
"license": "MIT",
"scope": "core probe records, one per line of measurements/<emulator>.jsonl",
}
connection.executemany("INSERT INTO meta VALUES (?, ?)", sorted(meta.items()))
cores = {s.record["core"]["sha256"]: s.record["core"] for s in stored}
connection.executemany("INSERT INTO cores VALUES (?, ?, ?, ?, ?, ?, ?, ?)", [
(sha, core["file"], json_text(core.get("repo")), json_text(core.get("commit")),
json_text(core.get("build_command")), json_text(core.get("compiler")),
json_text(core.get("library_name")), json_text(core.get("library_version")))
for sha, core in sorted(cores.items())])
connection.executemany("INSERT INTO hosts VALUES (?, ?, ?, ?, ?, ?, ?)", [
(number, *key) for key, number in sorted(hosts.items(), key=lambda kv: kv[1])])
emulators = sorted({s.emulator for s in stored})
connection.executemany("INSERT INTO emulator_systems VALUES (?, ?)", [
(emu, system) for emu in emulators
for system in sorted(set((profiles.get(emu) or {}).get("systems") or []))])
for entry in stored:
_insert_run(connection, entry, source or {}, hosts, entry.record["id"] not in live_ids)
connection.commit()
connection.execute("VACUUM")
finally:
connection.close()
os.replace(temp, destination)
def _insert_run(connection: sqlite3.Connection, entry: mr.Stored, source: dict,
hosts: dict, superseded: bool) -> None:
r = entry.record
host, front, inputs = r["host"], r["frontend"], r["inputs"]
rid = r["id"]
connection.execute("INSERT INTO runs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (
rid, entry.emulator, r["subject"], r["kind"], r["recorded_at"], r.get("supersedes"),
int(superseded), r["core"]["sha256"], hosts[_host_key(host)],
json_text(host.get("load_before")), json_text(host.get("load_after")), host.get("max_load"),
front.get("commit"), front["script_sha256"],
None if front.get("script_modified") is None else int(front["script_modified"]),
json_text(r["flags"]),
permalink(source.get("repo", ""), source.get("commit", ""), mr.records_path(entry.emulator), entry.line),
entry.line, r.get("migrated_from_version")))
content = inputs.get("content") or {}
connection.execute("INSERT INTO inputs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (
rid, content.get("label"), content.get("sha1"), content.get("size"),
json_text(inputs["options"]), json_text(inputs["env"]), inputs["frames"], inputs["warmup"],
inputs["repetitions"], json_text(inputs["presses"]), json_text(inputs["observables"]),
inputs["frame_hash_every"], inputs["joypad_ports"]))
connection.executemany("INSERT INTO content_tracks VALUES (?, ?, ?, ?, ?)", [
(rid, position, track["file"], track["sha1"], track["size"])
for position, track in enumerate(content.get("tracks") or [])])
check = r.get("check")
if check:
result = check["result"]
connection.execute("INSERT INTO checks VALUES (?, ?, ?, ?, ?, ?, ?)", (
rid, check["claim"], check["method"], check["observable"], check["variable"],
result["status"], result["statement"]))
connection.executemany("INSERT INTO check_groups VALUES (?, ?, ?, ?, ?)", [
(rid, position, json_text(group["value"]),
mr.value_sha1(group["value"]) if isinstance(group["value"], (list, dict)) else None,
json_text(group["variants"]))
for position, group in enumerate(result["groups"])])
for position, variant in enumerate(r["variants"]):
reps = variant["repetitions"]
first = reps[0]
# The first repetition stands for the variant, its per-frame hashes left out.
observables = {key: value for key, value in (first.get("observables") or {}).items()
if key not in BULKY_OBSERVABLES}
connection.execute("INSERT INTO variants VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (
rid, position, variant["label"], len(reps), int(all(rep.get("loaded") for rep in reps)),
json_text(variant["flags"]), json_text(observables),
json_text(first.get("files_opened")), json_text(first.get("files_probed_absent")),
json_text(first.get("tracing")), variant.get("verdict"),
json_text(variant.get("verdict_evidence")) if "verdict_evidence" in variant else None))
connection.executemany("INSERT INTO system_files VALUES (?, ?, ?, ?)", [
(rid, position, dest, sha1) for dest, sha1 in sorted(variant["system_files"].items())])
for metric, stats in sorted((r.get("timing") or {}).items()):
connection.execute("INSERT INTO benchmarks VALUES (?, ?, ?, ?, ?, ?, ?)", (
rid, metric, stats["median"], stats["mean"], stats["stdev"], stats["min"], stats["max"]))
# --------------------------------------------------------------------------
# Building the site's files
# --------------------------------------------------------------------------
@dataclass
class Built:
index: dict
paths: list[Path]
def load_profiles(emulators_dir: Path) -> dict:
from model.profiles import load_emulator_profiles
return load_emulator_profiles(str(emulators_dir), skip_aliases=False)
def records_commit(root: Path) -> str | None:
"""The commit the record links name, with a warning when the records on
disk are not the ones it holds."""
commit = mr.last_commit(root)
if commit is None:
print(f"WARNING: no commit holds {root / mr.RECORDS_DIR}: the record links "
"lead nowhere until the records are committed.", file=sys.stderr)
return None
on_disk = {path: file.read_bytes() for path, file in mr.tree_files(root).items()}
if mr.committed_files(root, commit) != on_disk:
print(f"WARNING: {mr.RECORDS_DIR}/ differs from {commit[:12]}, the last commit that "
"touched it: links to records added since lead nowhere until they are "
"committed.", file=sys.stderr)
return commit
def build(public: Path, root: Path = ROOT, emulators_dir: Path = ROOT / "emulators",
scratch: Path = ROOT / "tmp" / "site", system_names: dict[str, str] | None = None,
repo: str = REPO, commit: str | None = None) -> Built:
"""Write the index and the databases under the site's public folder.
``commit`` is the revision the record links name, by default the last
commit that touched the records.
"""
stored = mr.read_records(root)
source = {"repo": repo, "commit": commit or (records_commit(root) if stored else None)}
profiles = load_profiles(emulators_dir)
index = build_index(stored, source, profiles, system_names, load_observations(root / OBSERVATIONS))
paths = [public / INDEX_PATH]
(public / INDEX_PATH).parent.mkdir(parents=True, exist_ok=True)
write_if_changed(str(public / INDEX_PATH),
json.dumps(index, ensure_ascii=False, indent=1, sort_keys=True) + "\n")
write_sqlite(public / SQLITE_PATH, stored, source, profiles, scratch)
paths.append(public / SQLITE_PATH)
for emulator in sorted({s.emulator for s in stored}):
target = public / PER_EMULATOR_DIR / f"{emulator}.sqlite"
write_sqlite(target, [s for s in stored if s.emulator == emulator], source, profiles, scratch)
paths.append(target)
return Built(index, paths)
# --------------------------------------------------------------------------
# Pages
# --------------------------------------------------------------------------
def by_emulator(index: dict) -> dict[str, list[dict]]:
"""Each emulator's items. A pack probe's run proves a pack, not the
emulator's page."""
out: dict[str, list[dict]] = {}
for item in index.get("items", []):
if not item["subject"].startswith(mr.PACK_SUBJECT_PREFIX):
out.setdefault(item["emulator"], []).append(item)
return out
ISSUE_SUBJECT = re.compile(r"^issue(?P<number>\d+)-")
VERDICT_WORDS = {"boots": "boots", "bios_error": "shows a BIOS error", "crash": "crashes",
"hang": "hangs", "unknown": "gives no verdict"}
def proof_result(verdicts: list[dict]) -> str:
"""What a record showed, in words, naming the BIOS each boot ran: a
boot on the core's built-in BIOS is never the staged file's. A single
run says what was staged, a check names each variant."""
def said(verdict: dict) -> str:
used = verdict.get("bios_used") or "unknown"
if verdict["verdict"] == BOOTS_BUILTIN:
return "boots on the core's built-in BIOS"
if verdict["verdict"] == "boots" and used.startswith("staged:"):
return f"boots on {used.removeprefix('staged:')}"
return VERDICT_WORDS.get(verdict["verdict"], verdict["verdict"].replace("_", " "))
if len(verdicts) == 1:
staged = verdicts[0].get("staged") or []
given = " and ".join(staged) if len(staged) < 3 else f"{', '.join(staged[:-1])} and {staged[-1]}"
return f"with {given or 'no BIOS'}, it {said(verdicts[0])}"
return ". ".join(f"{v['variant']}: {said(v)}" for v in verdicts)
def proof_claims(item: dict, record: dict) -> tuple[list[str], list | None]:
"""The claims one record of an item backs on its emulator's page, and
what it showed. An issue observation is the claim and needs no more.
No claim when the record shows nothing a page can state."""
observed = record.get("observed")
if observed:
return [f"issue {observed['issue']}: {observed['said']}"], None
shown = record.get("shown")
if shown is None:
return [], None
if record.get("proves"):
return record["proves"], shown
issue = ISSUE_SUBJECT.match(item["subject"])
if issue and shown[0] == "text":
return [f"issue {issue['number']}"], shown
return [], None
def _md(value: object) -> str:
"""Record text placed in a Markdown line: no span, link or tag out of it."""
return _cell(value).translate(_MARKDOWN)
def _records(urls: list[str]) -> str:
"""The record links of one statement, escaped and safe targets only."""
def place(url: str) -> tuple[str, int]:
path, _, line = url.partition("#L")
return path, int(line) if line.isdigit() else 0
targets = sorted(dict.fromkeys(t for u in urls if (t := _href(u))), key=place)
if not targets:
return ""
if len(targets) == 1:
return f" ([record]({targets[0]}))"
files = {t.split("#", 1)[0] for t in targets}
if len(targets) > MAX_RECORD_LINKS and len(files) == 1:
return f" ([{len(targets)} records]({files.pop()}))"
return " (records " + ", ".join(f"[{n}]({t})" for n, t in enumerate(targets, 1)) + ")"
def proof_line(claim: str, shown: list[tuple[list | None, list[str]]]) -> str:
"""One line per claim, its records collapsed: the files strace saw
opened in one list, each distinct result once with its records."""
names: dict[str, list[str]] = {}
texts: dict[str, list[str]] = {}
bare: list[str] = []
for what, urls in shown:
if what is None:
bare.extend(urls)
elif what[0] == "opened":
names.setdefault(what[1], []).extend(urls)
else:
texts.setdefault(what[1], []).extend(urls)
parts = []
if names:
parts.append("the core opened " + ", ".join(_md(n) for n in names)
+ _records([u for urls in names.values() for u in urls]))
parts.extend(_md(text) + _records(urls) for text, urls in texts.items())
if not parts:
return f"- {_md(claim)}{_records(bare)}."
return f"- {_md(claim)}: " + ". ".join(part[:1].upper() + part[1:] if n else part
for n, part in enumerate(parts)) + "."
def proof_section(items: list[dict]) -> list[str]:
"""The Proof lines of an emulator page: only the claims of the page a
run backs, one line per claim. Every other record stays on the
Measurements page."""
by_claim: dict[str, list] = {}
for item in sorted(items, key=lambda i: i["subject"]):
for record in item.get("records") or ():
claims, what = proof_claims(item, record)
for claim in claims:
by_claim.setdefault(claim, []).append((what, [record["url"]]))
if not by_claim:
return []
return ["## Proof", "",
f"Real runs that back this page ([how they are made](../../{METHOD_PAGE.removesuffix('.md')}/)):",
"", *(proof_line(claim, by_claim[claim]) for claim in sorted(by_claim)), ""]
def _text(value: object) -> str:
"""Record text as the page shows it. A semicolon joining two clauses
ends a sentence on the site: the record keeps the words as written."""
text = " ".join(str(value or "").split())
text = re.sub(r";\s+(\w)", lambda m: ". " + m[1].upper(), text)
return _escape_tags(text)
def _short(commit: str | None) -> str:
return f"`{commit[:12]}`" if commit else "unknown"
def proves(record_ids: set[str], profile: dict) -> list[str]:
"""The profile fields a record is evidence for, as `field of file`. A
record judged again stands for the ones it supersedes."""
out = []
for entry in profile.get("files") or ():
for name, ids in sorted((entry.get("evidence") or {}).items()):
if record_ids & set(ids):
out.append(f"{name} of {entry.get('name')}")
return out
def lineage(stored: list[mr.Stored]) -> dict[str, set[str]]:
"""Each record id with every id it supersedes, through the chain."""
parent = {s.record["id"]: s.record.get("supersedes") for s in stored}
out = {}
for rid in parent:
seen = {rid}
node = parent[rid]
while node and node not in seen:
seen.add(node)
node = parent.get(node)
out[rid] = seen
return out
# An MDX page reads a brace as the start of an expression, in text and in
# an attribute alike.
_BRACES = str.maketrans({"{": "&#123;", "}": "&#125;"})
def _attr(value: object) -> str:
return html.escape(" ".join(str(value or "").split()), quote=True).translate(_BRACES)
def _cell(value: object) -> str:
"""Record text placed in raw HTML: escaped as text, never read as
Markdown (a run's output is no markup), braces made inert for MDX. A
semicolon joining two clauses ends a sentence, as on the rest of the
site."""
text = " ".join(str(value or "").split())
text = re.sub(r";\s+(\w)", lambda m: ". " + m[1].upper(), text)
return html.escape(text, quote=True).translate(_BRACES)
# The proof line is Markdown: a character that starts a span, a link or
# an image in a run's output stays a character.
_MARKDOWN = str.maketrans({c: f"&#{ord(c)};" for c in "`*_[]()~!|\\"})
_SAFE_HREF = re.compile(r"^(?:https?://[^\s\"'<>]+|/[^\s\"'<>]*|\.{0,2}/?[\w.~-][^\s\"'<>:]*)$")
def _href(url: object) -> str | None:
"""A link target from a record: http(s) or relative only, else none."""
text = str(url or "")
return _attr(text) if text and _SAFE_HREF.match(text) and not text.lower().startswith(
("javascript:", "data:", "vbscript:")) else None
def hosts_table(index: dict) -> list[str]:
hosts: dict[str, int] = {}
for item in index.get("items", []):
# The load average differs per run: the computer is what comes before it.
computer = item["host"].split(", load ")[0]
hosts[computer] = hosts.get(computer, 0) + 1
if not hosts:
return ["No result is recorded yet.", ""]
return [
"| Computer | Tests |",
"|----------|------:|",
*(f"| {_text(host)} | {count} |" for host, count in sorted(hosts.items())),
"",
]
def with_hosts(page: str, index: dict) -> str:
"""The methodology page with the computers the results ran on."""
return page.replace(HOSTS_MARKER, "\n".join(hosts_table(index)).rstrip("\n"))
def generate_explorer_page(index: dict) -> str:
commit = index.get("commit")
repo = index.get("repo") or ""
source = (f"[`measurements/`]({repo}/tree/{commit}/{mr.RECORDS_DIR}) at {_short(commit)}"
if commit else f"`{mr.RECORDS_DIR}/` of this repository")
return "\n".join([
"# Measurements",
"",
f"Emulators run in real conditions: {index.get('records', 0)} records, "
f"{index.get('count', 0)} tests, read from {source}. "
f"[How they are made]({METHOD_PAGE}).",
"",
" ".join([
markup.button("SQLite of every record", "downloads/measurements.sqlite", primary=True),
markup.button("Index as JSON", "data/measurements/index.json"),
]),
"",
"Each row is the latest record of one test, with its verdict, the BIOS it ran, its "
"method and the computer it ran on. Runs are made on demand: to settle a dispute or an "
"issue, to back a correction sent to a platform, or to check the packs before a release. "
"One SQLite file per emulator sits under `downloads/measurements/`.",
"",
"<MeasurementsExplorer />",
"",
])
def sqlite_tables(path: Path) -> list[tuple[str, list[str]]]:
"""Each table of a database with its columns, in the order created."""
connection = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
try:
names = [row[0] for row in connection.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY rowid")]
return [(name, [row[1] for row in connection.execute(f"PRAGMA table_info({name})")])
for name in names]
finally:
connection.close()
def data_page_section(path: Path) -> list[str]:
"""The Data page's description of measurements.sqlite."""
return [
"## Measurements",
"",
"[`measurements.sqlite`](downloads/measurements.sqlite) holds every core probe "
f"record kept in [`{mr.RECORDS_DIR}/`]({REPO}/tree/main/{mr.RECORDS_DIR}), and "
"`downloads/measurements/<emulator>.sqlite` the records of one emulator. The "
f"[Measurements]({EXPLORER_PAGE}) page reads "
"[`data/measurements/index.json`](data/measurements/index.json). A record line is "
"valid against [`core-probe-record.schema.json`](api/v1/schemas/core-probe-record.schema.json).",
"",
"| Table | Columns |",
"|-------|---------|",
*(f"| `{name}` | {', '.join(f'`{c}`' for c in columns)} |" for name, columns in sqlite_tables(path)),
"",
"`meta` names the commit the record links point to and the record version. A list or object "
"value is JSON text, an absent one empty. `runs.superseded` is 1 for a record a "
"later one corrects.",
"",
"```sql",
"SELECT r.emulator, c.claim, c.status, r.recorded_at, h.cpu_model",
"FROM runs r JOIN checks c ON c.run_id = r.id JOIN hosts h ON h.id = r.host_id",
"WHERE r.superseded = 0 ORDER BY r.recorded_at;",
"```",
"",
]
+759
View File
@@ -0,0 +1,759 @@
"""Small renderings shared by every page."""
from __future__ import annotations
import re
import urllib.parse
from collections.abc import Callable
from model import siteinputs
from sitegen import markup
from core.paths import REPO_ROOT
from model.collection import _PROGRAM_TOPS, _card_moves, _manufacturer_slug
from model.systemnames import (
SYSTEM_PARENTS,
_boards_built,
_console_anchors,
_ensure_console_sections,
_own_section,
_program_names,
_section_pairs,
_sections_by_name,
system_name,
)
WIKI_SRC_DIR = "wiki" # manually maintained wiki sources
SYSTEM_ICON_BASE = "https://raw.githubusercontent.com/libretro/retroarch-assets/master/xmb/systematic/png"
# Local copies of the upstream icons, named as upstream names them.
ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons"
# Icon names the site holds a copy of. A name mapped to False has none.
_icon_available: dict[str, bool] = {}
_CODE_SPAN = re.compile(r"(`+).+?\1", re.S)
def _code(value: object) -> str:
"""A value as an inline code span it cannot leave.
Markdown shows HTML inside a code span as text, so the one way out is a
backtick in the value closing the span early. Data from a profile, a
platform file or a file name is not ours to trust that far.
"""
return "`" + str(value).replace("`", "'") + "`"
def _count(number: int, noun: str, plural: str = "") -> str:
"""A count and its noun, singular for one: the site printed "1 files" 234 times."""
return f"{number:,} {noun if number == 1 else plural or noun + 's'}"
def _escape_tags(text: str) -> str:
"""Show a placeholder such as ``<system_dir>`` as it was written.
Profile prose names paths with angle brackets. Passed through as HTML
they are unknown tags and vanish from the page, and ``<title id>`` opens
a title element that swallows everything after it. Code spans keep their
brackets, and an autolink stays a link.
"""
def outside(chunk: str) -> str:
return re.sub(r"<(?!https?://|mailto:)", "&lt;", chunk)
out: list[str] = []
position = 0
for match in _CODE_SPAN.finditer(text):
out.append(outside(text[position:match.start()]))
out.append(match.group(0))
position = match.end()
out.append(outside(text[position:]))
return "".join(out)
def _admonition_body(text: str) -> str:
"""Indent prose without turning source tokens such as ``#if`` into H1s."""
escaped = re.sub(r"(?m)^(\s*)#", r"\1\\#", _escape_tags(text))
return escaped.replace("\n", "\n ")
def _icon_name(manufacturer: str, console_name: str) -> str:
return f"{manufacturer} - {console_name}".replace("/", " ")
def _icon_url(icon_name: str) -> str:
return f"{SYSTEM_ICON_BASE}/{urllib.parse.quote(icon_name)}.png"
def prime_system_icons(names: set[str]) -> None:
"""Record which system icons the site holds a copy of.
The icons are copied once into ``docs_assets/system-icons/`` by
``scripts/fetch_site_images.py``: the build reads that folder and never
the network. A system without a copy gets no icon, because a heading
with a broken image reads worse than a heading without one.
"""
held = {path.stem for path in ICON_DIR.glob("*.png")}
_icon_available.update({name: name in held for name in names})
missing = sum(1 for name in names if name not in held)
if missing:
print(f" {missing} systems have no icon in {ICON_DIR.relative_to(ICON_DIR.parents[1])}")
def system_icon_markdown(manufacturer: str, console_name: str) -> str:
"""Icon image for a system heading, empty when the site holds none.
The link names the upstream file: ``sitediagrams.localize_images``
points it at the local copy, whose source is recorded beside it.
"""
name = _icon_name(manufacturer, console_name)
if not _icon_available.get(name):
return ""
return markup.image(console_name, _icon_url(name), width="24") + " "
# Global index: maps system_id -> (manufacturer_slug, console_name) for cross-linking
_system_page_map: dict[str, tuple[str, str]] = {}
def _slugify_anchor(text: str) -> str:
"""Slugify text for MkDocs anchor compatibility."""
import re
slug = text.lower()
slug = re.sub(r"[^\w\s-]", "", slug)
slug = re.sub(r"[\s]+", "-", slug)
slug = slug.strip("-")
return slug
_norm_page_map: dict[str, tuple[str, str] | None] = {}
def set_system_page_map(mapping: dict[str, tuple[str, str]]) -> None:
"""Install the system id -> page table every link on the site reads.
The table replaces the previous one, and the index of other spellings is
derived from it here. Kept anywhere else, it outlived a table of the same
size and linked to the pages of the previous one.
"""
from model.systems import _norm_system_id
_system_page_map.clear()
_system_page_map.update(mapping)
_norm_page_map.clear()
for known, page in _system_page_map.items():
key = _norm_system_id(known)
if _norm_page_map.get(key, page) != page:
_norm_page_map[key] = None
else:
_norm_page_map[key] = page
def _page_by_norm(sys_id: str) -> tuple[str, str] | None:
"""The page an id leads to under another spelling of the same system.
Emulator cards name sega-megadrive or sinclair-zxspectrum, the pages are
keyed by the platforms' spellings: 2,431 of 4,195 cards had no link. A
spelling two pages share leads nowhere rather than to either.
"""
from model.systems import _norm_system_id
return _norm_page_map.get(_norm_system_id(sys_id))
# A manufacturer page too large for one page is a summary, each console on
# pages of its own: (slug, console) -> its page stems under systems/, and
# (slug, console, sha1) -> the stem holding that card. A console of a page
# kept whole has no entry, its section is on the manufacturer's page.
_console_pages: dict[tuple[str, str], list[str]] = {}
_card_pages: dict[tuple[str, str, str], str] = {}
def reset_console_pages() -> None:
"""Forget where the system pages put consoles, cards and boards."""
_console_pages.clear()
_card_pages.clear()
_board_sections.clear()
def record_console_pages(
slug: str, console: str, stems: list[str], sha1s: list[list[str]]
) -> None:
"""Where a split manufacturer page put one console: its page stems, in
order, and the sha1 of each card on each of them."""
_console_pages[(slug, console)] = list(stems)
for stem, part in zip(stems, sha1s):
for sha1 in part:
_card_pages.setdefault((slug, console, sha1), stem)
def split_system_stems() -> set[str]:
"""Every page stem of a console moved to a page of its own."""
return {stem for stems in _console_pages.values() for stem in stems}
def console_anchor(manufacturer: str, console: str) -> str:
"""The id of a console's heading on its manufacturer's page."""
from core.anchors import toc_slug
key = (_manufacturer_slug(manufacturer), console)
return _console_anchors.get(key) or toc_slug(console)
def console_href(slug: str, console: str, prefix: str = "") -> str:
"""Where a console's files are: its own page, or its section of the
manufacturer's page (also where a console cut into parts lists them).
An arcade board's section is the page of its own name, no heading
repeating its title."""
if slug == "arcade" and _board_sections:
board = _board_ids_by_name().get(console.casefold())
if board in _board_sections:
return f"{prefix}systems/arcade-{urllib.parse.quote(board_slug(board))}.md"
stems = _console_pages.get((slug, console))
if stems and len(stems) == 1:
return f"{prefix}systems/{urllib.parse.quote(stems[0])}.md"
return f"{prefix}systems/{urllib.parse.quote(slug)}.md#{console_anchor(slug, console)}"
def card_page(path: str, sha1: str) -> str:
"""The systems/ page stem holding the card of the copy at ``path``
(bios/<Manufacturer>/<Console>/...). A board's set is on the board's
page whatever folder holds the copy."""
parts = path.split("/")
slug = parts[1].lower().replace(" ", "-")
console = parts[2] if len(parts) > 2 else ""
if _board_sections:
board = arcade_board(sha1)
if board in _board_sections:
return f"arcade-{board_slug(board)}"
slug, console = _card_moves.get((slug, console, str(sha1)), (slug, console))
return _card_pages.get((slug, console, sha1), slug)
# Emulator cards moved off a page too long for one: (emulator, anchor) ->
# the page stem under emulators/ that holds the card.
_emulator_card_pages: dict[tuple[str, str], str] = {}
def record_emulator_cards(emulator: str, stem: str, anchors: list[str]) -> None:
for anchor in anchors:
_emulator_card_pages[(emulator, anchor)] = stem
def emulator_card_page(emulator: str, anchor: str) -> str:
"""The emulators/ page stem holding a card: the emulator's own page, or
the page its cards went to."""
return _emulator_card_pages.get((emulator, anchor), emulator)
def system_section(sys_id: str) -> tuple[str, str] | None:
"""The console section a system id leads to, as (manufacturer slug,
console): its own section, else the parent SYSTEM_PARENTS names, else
the arcade board it names once record_board_section() wrote it
(``("arcade", <board name>)``, which console_href turns into
``systems/arcade-<board slug>.md#<board slug>``), else the one section
whose heading reads system_name(). The folder a system's files sit in
is no answer by itself: Emerson's Arcadia 2001 led to the Saturn and
Sega's NAOMI to the Dreamcast.
A heading under Arcade counts when it reads the name exactly (Namco
System 246). One under Other never does, its headings name programs."""
if sys_id in BOARD_PARENTS and _board_sections:
board = _board_of_id(BOARD_PARENTS[sys_id])
if board in _board_sections:
return "arcade", system_name(board)
section = _section_without_boards(sys_id)
if (not _board_sections or sys_id in SYSTEM_PARENTS
or (section is not None and section[0] != "arcade")):
return section
board = _board_of_id(sys_id)
if board in _board_sections:
return "arcade", system_name(board)
return section
def _section_without_boards(sys_id: str) -> tuple[str, str] | None:
"""system_section before arcade boards: what the folders and the
reviewed parents give."""
own = _own_section(sys_id)
if own is not None:
return _manufacturer_slug(own[0]), own[1]
parent = SYSTEM_PARENTS.get(sys_id)
if parent is not None and parent in _section_pairs:
return _manufacturer_slug(parent[0]), parent[1]
try:
name = system_name(sys_id)
except KeyError:
return None
places = _sections_by_name.get(name.casefold(), set())
if len(places) != 1:
return None
mfr, console = next(iter(places))
if mfr in _NAMELESS_TOPS or (
mfr in _PROGRAM_TOPS and console.casefold() in _program_names
):
return None
return _manufacturer_slug(mfr), console
def _system_link(sys_id: str, prefix: str = "") -> str:
"""A system id linked to the section named after it, or the bare id."""
section = system_section(sys_id)
if section:
slug, console = section
return f"[{sys_id}]({console_href(slug, console, prefix)})"
return sys_id
# Arcade boards. A board is a system id that a profile entry with
# ``category: bios_zip`` names, through its ``system:``/``systems:`` or the
# profile's single system, whose archive the collection holds, and that has
# no section under a machine's maker. The archive is found by its name and,
# where the entry lists ``contents:``, kept only when it holds one of those
# CRC32s: maclc3.zip names a MAME set and an unrelated 189 MB file. The
# folder a copy sits in decides nothing.
_arcade_source: list[tuple[dict, dict] | None] = [None]
# sha1 -> the board id the archive is the BIOS of.
_archive_boards: dict[str, str] = {}
# Casefolded board name -> the board id that stands for it.
_board_names: dict[str, str] = {}
# sha1 -> the (manufacturer, console) sections of the machines whose own
# set the archive is: neogeo.zip for the Neo Geo, mz2000.zip for the MZ.
_archive_machines: dict[str, set[tuple[str, str] | None]] = {}
def set_arcade_boards(profiles: dict[str, dict], db: dict) -> None:
"""Install the profiles and database the arcade boards are read from.
Without it they are read from the repository on first use."""
_arcade_source[0] = (profiles, db)
_boards_built[0] = False
def _owner_ids(entry: dict, systems: list[str]) -> set[str]:
"""The system ids a profile entry is declared for."""
owners = {str(entry["system"])} if entry.get("system") else set()
owners.update(str(sys_id) for sys_id in entry.get("systems") or [])
if not owners and len(systems) == 1:
owners = set(systems)
return owners
# _board_role for an id whose archive is its machine's: a section under the
# machine's maker, or a reviewed parent outside Arcade.
_MACHINE = "\0machine"
def _board_role(sys_id: str) -> str | None:
"""A board's name, _MACHINE for an id that names a machine with a
section of its own, None for an id that names neither (the generic
arcade id, an id with no name)."""
parent = SYSTEM_PARENTS.get(sys_id)
if parent is not None:
return None if parent[0] == "Arcade" else _MACHINE
section = _section_without_boards(sys_id)
if section is not None and section[0] != "arcade":
return _MACHINE
try:
return system_name(sys_id)
except KeyError:
return None
def _in_arcade(sha1: str, db: dict) -> bool:
"""Whether a copy of the content sits under bios/Arcade/."""
entry = db.get("files", {}).get(sha1) or {}
if str(entry.get("path", "")).startswith("bios/Arcade/"):
return True
return sha1 in _arcade_suffix_sha1s(db)
_suffix_cache: list[tuple[dict, frozenset[str]] | None] = [None]
def _arcade_suffix_sha1s(db: dict) -> frozenset[str]:
# Holding the database itself, never id(db): a database freed and
# replaced at the same address answered with the first one's set.
cached = _suffix_cache[0]
if cached is not None and cached[0] is db:
return cached[1]
found = frozenset(
sha1s[0]
for tail, sha1s in db.get("indexes", {}).get("by_path_suffix", {}).items()
if tail.startswith("Arcade/") and len(sha1s) == 1
)
_suffix_cache[0] = (db, found)
return found
def _build_boards() -> None:
if _boards_built[0]:
return
_ensure_console_sections()
source = _arcade_source[0]
if source is None:
source = _read_arcade_source()
if source is None:
_archive_boards.clear()
_board_names.clear()
_boards_built[0] = True
return
_arcade_source[0] = source
profiles, db = source
files = db.get("files", {})
by_name = db.get("indexes", {}).get("by_name", {})
# sha1 -> board name -> the profiles naming it. None: a machine's own.
votes: dict[str, dict[str, set[str]] | None] = {}
_archive_machines.clear()
ids_by_name: dict[str, set[str]] = {}
for key in sorted(profiles):
profile = profiles[key]
if profile.get("role") == "test":
continue
systems = [str(sys_id) for sys_id in profile.get("systems") or []]
for entry in profile.get("files") or []:
if not isinstance(entry, dict) or entry.get("category") != "bios_zip":
continue
owners = _owner_ids(entry, systems)
if not owners:
continue
archives = _entry_archives(entry, files, by_name)
_cast_votes(key, entry, owners, archives, votes, ids_by_name)
_elect_boards(votes, ids_by_name, db)
_boards_built[0] = True
def _read_arcade_source() -> tuple[dict, dict] | None:
"""The profiles and database of the repository, None without a database."""
import json
from model.profiles import load_emulator_profiles
inputs = siteinputs.current()
database = inputs.db
if not database.exists():
return None
with open(database, encoding="utf-8") as handle:
db = json.load(handle)
profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False)
return profiles, db
def _entry_archives(entry: dict, files: dict, by_name: dict) -> set[str]:
"""The archives of the collection a ``bios_zip`` entry names."""
from core.ziptools import zip_member_crcs
crcs = {
str(member["crc32"]).lower()
for member in entry.get("contents") or []
if isinstance(member, dict) and member.get("crc32")
}
names = {str(entry.get("name", ""))}
names.update(str(alias) for alias in entry.get("aliases") or [])
archives: set[str] = set()
for name in names:
found = by_name.get(name.rsplit("/", 1)[-1]) or []
for sha1 in [found] if isinstance(found, str) else found:
if sha1 not in files:
continue
if crcs:
held = zip_member_crcs(str(_REPO_ROOT / files[sha1]["path"]))
# An archive the build cannot read keeps its name.
if held and not held & crcs:
continue
archives.add(sha1)
return archives
def _cast_votes(key: str, entry: dict, owners: set[str], archives: set[str],
votes: dict[str, dict[str, set[str]] | None],
ids_by_name: dict[str, set[str]]) -> None:
for owner in owners:
role = _board_role(owner)
if role == _MACHINE:
# The profile's only system stands for an entry that names
# none: MAME's printer and expansion sets in a Dragon
# profile. Only an entry naming the machine moves its set,
# and only when every machine it names has that section:
# epson_fx80.zip, which sixteen machines load, has none.
declared = entry.get("system") or entry.get("systems")
places = {_machine_section(o) for o in owners
if _board_role(o) == _MACHINE} if declared else {None}
section = next(iter(places)) if len(places) == 1 else None
for sha1 in archives:
votes[sha1] = None
_archive_machines.setdefault(sha1, set()).add(section)
continue
if role is None:
continue
ids_by_name.setdefault(role.casefold(), set()).add(owner)
for sha1 in archives:
ballot = votes.setdefault(sha1, {})
if ballot is not None:
ballot.setdefault(role.casefold(), set()).add(key)
def _elect_boards(votes: dict[str, dict[str, set[str]] | None],
ids_by_name: dict[str, set[str]], db: dict) -> None:
_archive_boards.clear()
_board_names.clear()
for sha1, ballot in votes.items():
if not ballot:
continue
ranked = sorted(ballot.items(), key=lambda item: (-len(item[1]), item[0]))
# Two boards named as often: a device ROM several boards share.
if len(ranked) > 1 and len(ranked[0][1]) == len(ranked[1][1]):
continue
name = ranked[0][0]
board = sorted(ids_by_name[name])[0]
_archive_boards[sha1] = board
if _in_arcade(sha1, db):
_board_names[name] = board
# A board none of whose archives sits under Arcade has no section there.
for sha1, board in list(_archive_boards.items()):
if system_name(board).casefold() not in _board_names:
del _archive_boards[sha1]
def _machine_section(sys_id: str) -> tuple[str, str] | None:
"""The (manufacturer, console) section SYSTEM_PARENTS files a machine
id under, outside Arcade. Only a reviewed parent moves an archive out
of the folder holding it: an id with a section of its own keeps its
archives where the collection files them."""
parent = SYSTEM_PARENTS.get(sys_id)
if parent is None or parent[0] == "Arcade" or parent not in _section_pairs:
return None
return parent
def archive_machine(sha1: str) -> tuple[str, str] | None:
"""The (manufacturer, console) section of the machine an archive is
the set of, when a profile declares it for one machine only: the Neo
Geo's neogeo.zip, the MZ-2000's mz2000.zip. Read from the same
``category: bios_zip`` entries as arcade_board(), never the folder."""
_build_boards()
places = _archive_machines.get(str(sha1), set())
return next(iter(places)) if len(places) == 1 else None
def _board_ids_by_name() -> dict[str, str]:
_build_boards()
return _board_names
def _board_of_id(sys_id: str) -> str | None:
"""The board an id names, by its display name: naomi2 and sega-naomi2
are one board."""
try:
name = system_name(sys_id)
except KeyError:
return None
return _board_ids_by_name().get(name.casefold())
def arcade_board(sha1: str) -> str | None:
"""The system id an arcade archive is the BIOS of, or None.
Read from the profiles' ``system``/``systems`` and ``contents:``,
never from the folder. An archive several boards share as often (a
device ROM), or one a machine with its own section names (neogeo.zip
for the Neo Geo, cd32.zip for the CD32), has no board. Every id of a
board's name returns the same id, the first in sort order."""
_build_boards()
return _archive_boards.get(str(sha1))
def board_slug(sys_id: str) -> str:
"""The slug of a board's section: its page is systems/arcade-<slug>/
and its heading's id is <slug>. Read from the board's display name,
so every id of one board gives one slug."""
from core.anchors import toc_slug
return toc_slug(system_name(str(sys_id)))
# Boards whose section the system pages wrote. A link waits for its
# section: before the Arcade pages were grouped by board, 8,606 links on
# 141 pages led to pages nobody wrote and the build stopped.
_board_sections: set[str] = set()
def record_board_section(board: str) -> None:
"""Mark a board's section as written, at systems/arcade-<board_slug>/
under the heading <board_slug>. From then on system_section() leads
every id of the board there, and card_page() sends its Arcade cards
there. The system pages call it for each board they give a section,
before any other page links one."""
canonical = _board_of_id(str(board))
if canonical is None:
raise KeyError(f"{board!r} is not an arcade board")
_board_sections.add(canonical)
def arcade_boards() -> dict[str, str]:
"""Every board, by board id -> display name."""
_build_boards()
return {board: system_name(board) for board in sorted(set(_board_names.values()))}
def _field_text(key: object, value: object) -> str:
"""A scalar of a structured block. A source reference reads as code."""
if isinstance(value, bool):
text = "yes" if value else "no"
elif value is None:
text = "none"
else:
# One line: a folded note's second line started at column 0 and
# left the admonition it was written in. Never cut: 34 notes lost
# their end, and a cut citation links to another line.
text = " ".join(str(value).split())
return f"`{text}`" if key == "source_ref" else text
def _field_label(key: object) -> str:
"""A YAML key as the page shows it: words, not an identifier."""
return str(key).replace("_", " ")
FieldText = Callable[[object, object], str]
def _render_yaml_value(
lines: list[str], val: object, indent: int = 4,
field_text: FieldText = _field_text,
) -> None:
"""Render any YAML value as a nested markdown list.
Every level is a list item and its children a sublist four spaces in.
A key written as a paragraph with its children indented below it read as
an indented code block: the clownmdemu page showed the raw asterisks.
``field_text`` renders each scalar, so a page can link a source_ref.
"""
pad = " " * indent
if isinstance(val, dict):
for k, v in val.items():
if isinstance(v, (dict, list)) and v:
lines.append(f"{pad}- **{_field_label(k)}:**")
lines.append("")
_render_yaml_value(lines, v, indent + 4, field_text)
else:
lines.append(f"{pad}- **{_field_label(k)}:** {field_text(k, v)}")
lines.append("")
elif isinstance(val, list):
for item in val:
if isinstance(item, dict):
# Scalars on the item's line, lists and maps as its children:
# cemu's firmware titles lost the files each title carries.
scalars = {ik: iv for ik, iv in item.items()
if not (isinstance(iv, (dict, list)) and iv)}
nested = {ik: iv for ik, iv in item.items() if ik not in scalars}
parts = [f"{_field_label(ik)}: {field_text(ik, iv)}"
for ik, iv in scalars.items()]
lines.append(f"{pad}- {', '.join(parts)}".rstrip())
if nested:
lines.append("")
_render_yaml_value(lines, nested, indent + 4, field_text)
else:
lines.append(f"{pad}- {field_text(None, item)}")
lines.append("")
elif isinstance(val, str) and "\n" in val:
lines.extend(f"{pad}{line}" for line in val.split("\n"))
else:
lines.append(f"{pad}{field_text(None, val)}")
def _platform_link(name: str, display: str, prefix: str = "") -> str:
"""Generate a markdown link to a platform page."""
return f"[{display}]({prefix}platforms/{name}.md)"
def _emulator_link(name: str, prefix: str = "") -> str:
"""Generate a markdown link to an emulator page."""
return f"[{name}]({prefix}emulators/{name}.md)"
def _fmt_size(size: int) -> str:
if size >= 1024 * 1024 * 1024:
return f"{size / (1024**3):.1f} GB"
if size >= 1024 * 1024:
return f"{size / (1024**2):.1f} MB"
if size >= 1024:
return f"{size / 1024:.1f} KB"
return f"{size} B"
def _pct(n: int, total: int) -> str:
if total == 0:
return "0%"
return f"{n / total * 100:.1f}%"
def _by_mode(value: str | dict, mode: str) -> str:
"""Read a profile field that may be keyed by build mode."""
if isinstance(value, dict):
return str(value.get(mode) or "") if mode else ""
return str(value or "")
# Of those, the top whose headings never name a system, even read whole.
# An Arcade heading can (Namco System 246), an Other one cannot.
_NAMELESS_TOPS = frozenset({"Other"})
_REPO_ROOT = REPO_ROOT
# A system id that names a family of arcade boards -> the board its link
# leads to. RetroArch's sega-dreamcast-arcade lists the NAOMI, NAOMI 2 and
# Atomiswave BIOS: the NAOMI page comes first, the Dreamcast section links
# the others.
BOARD_PARENTS: dict[str, str] = {
"sega-dreamcast-arcade": "sega-naomi",
}
def system_ids(profiles: dict[str, dict], platforms: list[dict]) -> set[str]:
"""Every system id a page can name: the platforms' and the profiles'."""
ids = {str(sys_id) for config in platforms for sys_id in config.get("systems", {})}
for profile in profiles.values():
ids.update(str(sys_id) for sys_id in profile.get("systems") or [])
for entry in profile.get("files") or []:
if not isinstance(entry, dict):
continue
if entry.get("system"):
ids.add(str(entry["system"]))
ids.update(str(sys_id) for sys_id in entry.get("systems") or [])
return ids
def link_coverage(ids: set[str]) -> tuple[int, int]:
"""How many of ``ids`` lead to a section, and how many there are."""
return sum(1 for sys_id in ids if system_section(sys_id)), len(ids)
# A system id -> the names the platforms' own files give it, built once.
_search_aliases: dict[str, list[str]] = {}
_search_aliases_built = [False]
# A native name as a person types it: no space, no comma. RetroArch's
# native names are No-Intro titles ("Sony - PlayStation") and stay out.
_ALIAS_SHAPE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.+-]*")
def system_search_aliases(sys_id: str) -> list[str]:
"""The native system ids the platform YAMLs file ``sys_id`` under
(psx, dreamcast, gba), sorted, for search. Read from each platform's
own entries by common.platform_system_names, never typed by hand."""
if not _search_aliases_built[0]:
from model.registry import list_registered_platforms
from model.platforms import load_platform_config
from model.systems import platform_system_names
platforms_dir = str(siteinputs.current().platforms)
index: dict[str, set[str]] = {}
for platform in list_registered_platforms(platforms_dir):
config = load_platform_config(platform, platforms_dir)
names = platform_system_names(config, list(config.get("systems", {})))
for owner, spelled in names.items():
index.setdefault(owner, set()).update(
name for name in spelled if _ALIAS_SHAPE.fullmatch(name)
)
# Search ignores case: one spelling per word, the lower-case one
# when a platform writes it (psx, not PSX).
_search_aliases.clear()
for owner, names in index.items():
spellings: dict[str, str] = {}
for name in sorted(names, key=lambda n: (n != n.lower(), n)):
spellings.setdefault(name.casefold(), name)
if spellings:
_search_aliases[owner] = sorted(spellings.values(), key=str.casefold)
_search_aliases_built[0] = True
return list(_search_aliases.get(str(sys_id), []))
+966
View File
@@ -0,0 +1,966 @@
"""The site as an Astro Starlight project: pages, sidebar and data files.
generate_site.py writes each page body, and this module gives it the form
Starlight reads. A page's links are written as the docs tree holds them
(``../systems/sony.md``, MkDocs' convention, the one a Markdown editor
follows), and the site serves them as addresses under /retrobios/, so
each target is resolved against the page's own place here. Every heading
keeps the id the MkDocs site gave it, so the anchors cited since stay
valid.
"""
from __future__ import annotations
import html
import json
import re
import urllib.parse
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass, field
from html import unescape
from pathlib import Path, PurePosixPath
from core.paths import REPO_ROOT
from core.anchors import _unique, toc_slug
BASE = "/retrobios/"
SITE_URL = "https://abdess.github.io/retrobios/"
# Components a page body may use, and where each comes from.
COMPONENTS = {
"Tabs": "@astrojs/starlight/components",
"TabItem": "@astrojs/starlight/components",
"FilePicker": "components/FilePicker.astro",
"WantedFiles": "components/WantedFiles.astro",
"WantedList": "components/WantedList.astro",
"MeasurementsExplorer": "components/MeasurementsExplorer.astro",
"InstallDemo": "components/InstallDemo.astro",
}
# Pages of file cards: level 3 headings by the hundred, so the table of
# contents stops at level 2.
CARD_PAGES = ("systems/", "emulators/", "platforms/")
FENCE = re.compile(r"(^[ \t]*(`{3,}|~{3,}).*?^[ \t]*\2[ \t]*$)", re.M | re.S)
CODE_SPAN = re.compile(r"(`+)(?!`)(.+?)(?<!`)\1(?!`)", re.S)
MD_LINK = re.compile(r"(?P<bang>!?)\[(?P<text>(?:[^\[\]\n]|\[[^\]\n]*\])*)\]\((?P<url>[^)\s]+)(?P<title> \"[^\"]*\")?\)")
HTML_URL = re.compile(r"(?P<attr>\b(?:href|src))=\"(?P<url>[^\"]*)\"")
ATTR_BLOCK = re.compile(r"[ \t]*\{(?P<attrs>[^{}]*)\}[ \t]*$")
ID_ATTR = re.compile(r"\bid=\"(?P<id>[^\"]+)\"")
# Addresses
def page_url(rel: str) -> str:
"""The address of a page, by its path under the docs tree."""
stem = rel.rsplit(".", 1)[0] if rel.endswith((".md", ".mdx")) else rel
if stem == "index":
return BASE
if stem.endswith("/index"):
stem = stem[: -len("/index")]
return f"{BASE}{stem}/"
def resolve(rel_page: str, target: str) -> str:
"""A link target written relative to the page's file, as a site address."""
if not target or re.match(r"^(?:[a-z][a-z0-9+.-]*:|#|/)", target):
return target
path, hash_mark, fragment = target.partition("#")
path, question, query = path.partition("?")
parts: list[str] = []
for piece in (PurePosixPath(rel_page).parent / path).as_posix().split("/"):
if piece in ("", "."):
continue
if piece == "..":
if parts:
parts.pop()
else:
parts.append(piece)
joined = "/".join(parts)
if joined.endswith((".md", ".mdx")):
url = page_url(joined)
elif path.endswith("/") or not path:
url = f"{BASE}{joined}/" if joined else BASE
else:
url = f"{BASE}{joined}"
if question:
url += f"?{query}"
return url + (f"#{fragment}" if hash_mark else "")
# Text outside code
def outside_fences(text: str, fn: Callable[[str], str]) -> str:
parts = FENCE.split(text)
# FENCE has two groups: text, fence, marker, text, ...
out = []
for index in range(0, len(parts), 3):
out.append(fn(parts[index]))
if index + 1 < len(parts):
out.append(parts[index + 1])
return "".join(out)
def outside_code(text: str, fn: Callable[[str], str]) -> str:
def chunk(part: str) -> str:
out, position = [], 0
for match in CODE_SPAN.finditer(part):
out.append(fn(part[position:match.start()]))
out.append(match.group(0))
position = match.end()
out.append(fn(part[position:]))
return "".join(out)
return outside_fences(text, chunk)
def rewrite_links(text: str, rel: str) -> str:
def markdown(match: re.Match) -> str:
return (f"{match['bang']}[{match['text']}]({resolve(rel, match['url'])}"
f"{match['title'] or ''})")
def attribute(match: re.Match) -> str:
return f'{match["attr"]}="{resolve(rel, match["url"])}"'
text = outside_fences(text, lambda chunk: MD_LINK.sub(markdown, chunk))
return outside_fences(text, lambda chunk: HTML_URL.sub(attribute, chunk))
def pin_heading_ids(text: str, title_id: str = "") -> str:
"""Every heading with the id the MkDocs build gave it. *title_id* is
the page title's, taken first."""
used: set[str] = {title_id} if title_id else set()
explicit = set()
for match in re.finditer(r"\{[^{}\n]*#([^\s}]+)[^{}\n]*\}[ \t]*$", text, re.M):
explicit.add(match[1])
for match in ID_ATTR.finditer(text):
explicit.add(match["id"])
used |= explicit
def markdown(match: re.Match) -> str:
heading = match["mdtext"]
attrs = ATTR_BLOCK.search(heading)
body = heading[: attrs.start()] if attrs else heading
tokens = attrs["attrs"].split() if attrs else []
if any(token.startswith("#") for token in tokens):
return match.group(0)
ident = _unique(toc_slug(body), used)
return f"{match['hashes']} {body.rstrip()} {{ {' '.join(['#' + ident, *tokens])} }}"
def raw(match: re.Match) -> str:
if ID_ATTR.search(match["attrs"]):
return match.group(0)
level, text = match["level"], match["htmltext"]
ident = _unique(toc_slug(text), used)
return f'<h{level} id="{ident}"{match["attrs"]}>{text}</h{level}>'
def pick(match: re.Match) -> str:
return markdown(match) if match["hashes"] else raw(match)
# In document order: one pass over either kind of heading.
return outside_fences(text, lambda chunk: _ANY_HEADING.sub(pick, chunk))
_ANY_HEADING = re.compile(
r"^(?P<hashes>#{2,6})[ \t]+(?P<mdtext>.+?)[ \t]*$"
r"|<h(?P<level>[2-6])(?P<attrs>(?:\s[^>]*)?)>(?P<htmltext>.*?)</h(?P=level)>",
re.M | re.S,
)
# Glossary tooltips
def glossary_terms(path: Path) -> dict[str, str]:
"""Each term the glossary defines, with its definition as plain text."""
terms: dict[str, str] = {}
if not path.is_file():
return terms
text = path.read_text(encoding="utf-8")
for match in re.finditer(r"^(?P<term>\*\*.+)\n: (?P<body>.+(?:\n .+)*)", text, re.M):
definition = re.sub(r"\s+", " ", match["body"]).strip()
definition = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", definition).replace("`", "")
for term in re.findall(r"\*\*([^*]+)\*\*", match["term"]):
terms.setdefault(term, definition)
return terms
_SKIP_TAGS = re.compile(r"<(a|code|pre|abbr|h[1-6]|script|style|summary|svg|figure)\b.*?</\1>", re.S | re.I)
def add_tooltips(text: str, terms: dict[str, str]) -> str:
"""The first use of each glossary term on a page, with its definition
a hover or a tap away. Headings, links, code and HTML are left as they are."""
if not terms:
return text
pending = dict(terms)
pattern = re.compile(
r"(?<![\w/.-])(" + "|".join(re.escape(t) for t in sorted(terms, key=len, reverse=True))
+ r")(?![\w/-])"
)
def prose(chunk: str) -> str:
if not pending:
return chunk
out = []
for line in chunk.split("\n"):
stripped = line.lstrip()
if (not pending or stripped.startswith(("#", "|", "<", ":::", "[", "!"))
or not stripped):
out.append(line)
continue
out.append(_tooltip_line(line, pattern, pending))
return "\n".join(out)
return outside_code(text, prose)
def _tooltip_line(line: str, pattern: re.Pattern, pending: dict[str, str]) -> str:
# Inline HTML, links and emphasis markers stay whole.
protected = re.compile(r"<[^>]+>|\[[^\]]*\]\([^)]*\)|\*\*[^*]+\*\*|\{[^}]*\}")
out, position = [], 0
for match in protected.finditer(line):
out.append(_tooltip_text(line[position:match.start()], pattern, pending))
out.append(match.group(0))
position = match.end()
out.append(_tooltip_text(line[position:], pattern, pending))
return "".join(out)
_NAME_BEFORE = re.compile(r"(?:/|\b[A-Z][\w'-]*[ \t]+)$")
def _in_proper_name(term: str, before: str) -> bool:
"""A capitalised term after a capitalised word or a slash is part of a
name: Free Unix Spectrum Emulator, Windows Terminal, Documents/Dolphin
Emulator. An acronym (BIOS, ZIP) is the term wherever it stands."""
first = term.split()[0]
return first[:1].isupper() and not first.isupper() and bool(_NAME_BEFORE.search(before))
def _tooltip_text(text: str, pattern: re.Pattern, pending: dict[str, str]) -> str:
def swap(match: re.Match) -> str:
term = match.group(1)
if term not in pending or _in_proper_name(term, text[:match.start()]):
return term
definition = pending.pop(term)
return f'<abbr class="rb-term" title="{html.escape(definition)}">{term}</abbr>'
return pattern.sub(swap, text)
# MDX
_VOID = re.compile(r"<(br|img|input|hr|source|meta|link|wbr)\b([^>]*?)(?<!/)>")
_HEADING_ATTRS = re.compile(r"(?m)(?<=\S)[ \t]+\{[ \t]*#[^{}\n]*\}[ \t]*$")
_COMMENT = re.compile(r"<!--.*?-->", re.S)
_TAG_GAP = re.compile(r"(</[A-Za-z][\w-]*>)[ \t]+(?=<[A-Za-z])")
def mdx_safe(text: str) -> str:
"""What MDX would read as code in prose: braces, a stray ``<``,
comments, unclosed void tags and ``<https://...>`` links. A space
between two tags is written as an expression MDX keeps."""
def fix(chunk: str) -> str:
chunk = _COMMENT.sub("", chunk)
chunk = re.sub(r"<(https?://[^>\s]+)>", r"[\1](\1)", chunk)
held: list[str] = []
def hold(match: re.Match) -> str:
held.append(match.group(0))
return f"\x00{len(held) - 1}\x00"
chunk = _HEADING_ATTRS.sub(hold, chunk)
chunk = chunk.replace("{", "&#123;").replace("}", "&#125;")
chunk = re.sub(r"\x00(\d+)\x00", lambda m: held[int(m[1])], chunk)
chunk = re.sub(r"<(?![A-Za-z/])", "&lt;", chunk)
chunk = _VOID.sub(lambda m: f"<{m[1]}{m[2].rstrip()} />", chunk)
# A line of tags alone is JSX to MDX, which drops the space between
# them: a setup page with tabs read "2007/2008Coverage".
return _TAG_GAP.sub(r'\1{" "}', chunk)
return outside_code(text, fix)
def used_components(body: str) -> list[str]:
return [name for name in COMPONENTS if re.search(rf"<{name}[\s/>]", body)]
# Pages
def _front_matter(data: dict) -> str:
import yaml
return "---\n" + yaml.safe_dump(data, sort_keys=False, allow_unicode=True, width=1000) + "---\n\n"
def og_section(rel: str, level: str) -> str:
"""The sharing card a page takes: its level, or what its address says."""
url = page_url(rel)[len(BASE):]
if not url:
return "home"
if level in ("start", "setup", "explore", "reference", "contribute"):
return level
if url.startswith(("which-pack", "wiki/first-install", "wiki/faq", "wiki/getting-started")):
return "start"
if url.startswith("platforms"):
return "setup"
if url.startswith(("systems", "emulators", "files")):
return "explore"
if url.startswith(("contributing", "wiki/adding", "wiki/profiling", "wiki/testing", "wiki/release")):
return "contribute"
return "reference"
# Sharing cards of their own, made by scripts/make_og_cards.py: one per
# platform page, titled with the platform's name.
OG_DIR = REPO_ROOT / "docs_assets" / "og"
# An emulator page's card is that of the maker of the first system it runs,
# by page path: "emulators/mgba.mdx" -> "nintendo". One card per emulator
# would be some 900 images in the repository, and the maker's names the
# consoles. Filled by generate_site.record_emulator_page.
EMULATOR_CARDS: dict[str, str] = {}
def og_image(rel: str, level: str) -> str:
"""The sharing card's address: the page's own when it has one, its
maker's for an emulator, else its section's."""
own = re.fullmatch(r"(platforms|systems)/([a-z0-9_-]+)\.mdx?", rel)
if own and own[2] != "index" and (OG_DIR / own[1] / f"{own[2]}.png").is_file():
return f"{SITE_URL}assets/og/{own[1]}/{own[2]}.png"
maker = EMULATOR_CARDS.get(re.sub(r"\.mdx?$", "", rel))
if maker and (OG_DIR / "systems" / f"{maker}.png").is_file():
return f"{SITE_URL}assets/og/systems/{maker}.png"
return f"{SITE_URL}assets/og/{og_section(rel, level)}.png"
NOT_FOUND = "404.md"
def page_head(rel: str, level: str, title: str, browser_title: str, structured: dict) -> list[dict]:
"""What a page adds to its head: its own window title, its sharing
card (og_image), and its structured data. The page a stale link
lands on asks not to be indexed and describes nothing."""
head: list[dict] = []
if browser_title != title:
head.append({"tag": "title", "content": f"{browser_title} - RetroBIOS"})
if rel == NOT_FOUND:
return head + [{"tag": "meta", "attrs": {"name": "robots", "content": "noindex"}}]
image = og_image(rel, level)
if browser_title != title:
# Starlight writes og:title from the H1 ("mGBA"): a shared link
# reads as the search result does ("mGBA BIOS files").
head += [{"tag": "meta", "attrs": {"property": "og:title", "content": browser_title}},
{"tag": "meta", "attrs": {"name": "twitter:title", "content": browser_title}}]
head += [
{"tag": "meta", "attrs": {"property": "og:image", "content": image}},
{"tag": "meta", "attrs": {"property": "og:image:width", "content": "1200"}},
{"tag": "meta", "attrs": {"property": "og:image:height", "content": "630"}},
{"tag": "meta", "attrs": {"property": "og:image:alt", "content": f"RetroBIOS: {browser_title}"}},
{"tag": "meta", "attrs": {"name": "twitter:image", "content": image}},
{"tag": "script", "attrs": {"type": "application/ld+json"},
"content": json.dumps(structured, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")},
]
return head
def split_title(markdown: str) -> tuple[str, str, str]:
"""The page's H1 as plain text, the id MkDocs gave it, and the body
without it."""
match = re.search(r"^# (.+?)[ \t]*$\n?", markdown, re.M)
if not match:
return "", "", markdown
explicit = re.search(r"\{[^}]*#([^\s}]+)[^}]*\}\s*$", match[1])
title = re.sub(r"\s*\{[^}]*\}\s*$", "", match[1])
ident = explicit[1] if explicit else toc_slug(title)
title = re.sub(r"<[^>]+>", "", title)
title = re.sub(r"!\[[^\]]*\]\([^)]*\)", "", title)
title = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", title).replace("`", "")
return unescape(title).strip(), ident, markdown[: match.start()] + markdown[match.end():]
_CARD_NAME = re.compile(r'<h3[^>]*class="rb-file-title"(?![^>]*data-pagefind-ignore)[^>]*><code>([^<]+)</code>')
# What separates the parts of a file name: anything but a letter or a digit.
_NAME_PART = re.compile(r"[\W_]+")
def search_field(key: str, words: list[str]) -> str:
"""A search field of the page, held in an attribute of an empty
element: the text of an element is indexed and shown as the result's
excerpt (a run of 250 file names). Pagefind splits several fields at a
comma, so a value carries none."""
value = " ".join(word.replace(",", " ") for word in words).strip()
if not value:
return ""
return f'\n<span data-pagefind-meta="{html.escape(f"{key}:{value}", quote=True)}" hidden></span>\n'
def file_names_meta(body: str) -> str:
"""The names of the files a system page holds cards for, as a search
field of the page. A page of 250 cards is long, and the search weighs a
long page down: the Sony page, where scph5501.bin is downloaded, came
after every short page citing the name. The field is weighted in the
site's ranking (astro.config.mjs, metaWeights.files).
A name is written as its parts (scph5501 bin), each once. The search
matches a word as the start of a longer one and scores every distinct
word it reaches: whole names gave "ds" twelve rare words on the DSi page
(dsi_bios7.bin, DSi_Nand_USA.bin...), which then ranked first for
"nintendo ds bios"."""
names = sorted({unescape(name) for name in _CARD_NAME.findall(body)})
parts: dict[str, str] = {}
for name in names:
for part in _NAME_PART.split(name):
if part:
parts.setdefault(part.casefold(), part)
return search_field("files", list(parts.values()))
# systems/ page -> the platforms' own ids for the consoles it holds, built
# on the first system page, once the generator has installed the sections.
_page_aliases: dict[str, list[str]] = {}
_page_aliases_built = [False]
def page_aliases(rel: str) -> list[str]:
"""The names the platforms file the consoles of a system page under
(psx, dreamcast, gba), from siterender.system_search_aliases(): "psx
bios" finds the PlayStation page though the page never says psx."""
if not _page_aliases_built[0]:
from sitegen import render as siterender
by_page: dict[str, set[str]] = {}
for sys_id in list(siterender._system_page_map):
section = siterender.system_section(sys_id)
names = siterender.system_search_aliases(sys_id)
if not section or not names:
continue
target = siterender.console_href(*section).partition("#")[0]
by_page.setdefault(urllib.parse.unquote(target), set()).update(names)
_page_aliases.clear()
_page_aliases.update({page: sorted(names, key=str.casefold)
for page, names in by_page.items()})
_page_aliases_built[0] = bool(siterender._system_page_map)
return list(_page_aliases.get(rel, []))
def field_words(value: object) -> list[str]:
"""The words of a front matter search field: a list, or one string
with its words or phrases split at commas."""
if isinstance(value, str):
return [part.strip() for part in value.split(",") if part.strip()]
if isinstance(value, (list, tuple)):
return [str(part).strip() for part in value if str(part).strip()]
return []
def console_words(names: list[str]) -> list[str]:
"""What a visitor types for a console: its name with "BIOS". A page that
answers "No file needed" says BIOS only where the search does not read,
so "nes bios" found NES.emu and never the NES page. As a task word it
weighs like one: in the consoles field, NES.emu's title still won."""
return [f"{name} BIOS" for name in names]
_CONSOLES_META = re.compile(r'data-pagefind-meta="consoles:([^"]*)"')
def page_console_words(authored: dict, text: str) -> set[str]:
"""The words of the consoles a page answers for: its `consoles` front
matter (*authored*) before decoration, its `consoles` field after."""
names = field_words(authored.get("consoles"))
if names:
return {word.casefold() for name in names for word in name.split()}
match = _CONSOLES_META.search(text)
return set(unescape(match[1]).casefold().split()) if match else set()
def covered_names(names: list[str], page: str, words_by_page: Mapping[str, set[str]]) -> list[str]:
"""The names of *names* whose every word another page's consoles also
hold, as a word or the start of one (PlayStation on the PlayStation 2
page, Nintendo DS on the DSi page, Nintendo Super System on the
Nintendo page). The search matches a word as the start of a longer one
and ignores the words a page has that the query lacks: it cannot tell
these pages apart by words, only by a weight the other page lacks."""
held = [words for other, words in words_by_page.items() if other != page]
return [name for name in names
if any(all(any(word.startswith(part) for word in words)
for part in name.casefold().split())
for words in held)]
def _neighbour(rel: str, value: object) -> object:
"""A `prev:` or `next:` the page states, its link resolved like any
other link of the page."""
if isinstance(value, dict) and value.get("link"):
# Starlight writes the link as given: a site path gets the base.
link = resolve(rel, str(value["link"]))
if link.startswith("/") and not link.startswith(BASE):
link = BASE + link.lstrip("/")
return {**value, "link": link}
return value
_NEXT_STEPS = re.compile(r"^## Next steps\b[^\n]*\n+(?P<list>(?:[ \t]*[-*] .*\n?)+)", re.M)
def next_step(body: str) -> dict | None:
"""The first link of the page's "Next steps" list, as the theme's
`next:` front matter."""
match = _NEXT_STEPS.search(body)
if not match:
return None
link = MD_LINK.search(match["list"])
if not link or link["bang"]:
return None
return {"link": link["url"], "label": re.sub(r"[*_`]", "", link["text"]).strip()}
@dataclass(frozen=True)
class PageMeta:
"""What render_page writes around a page body."""
level: str
weight: float | None
browser_title: str
description: str
structured: dict
terms: dict[str, str]
search: bool = True
logo: str = ""
parent: dict | None = None
authored: dict | None = None
words_by_page: Mapping[str, set[str]] | None = None
def render_page(rel: str, markdown: str, meta: PageMeta) -> tuple[str, str]:
"""The Starlight file for a page body: its path under the content
collection and its text. *parent* ({label, link}, the link written
relative to the page) is the page a part page belongs to: the route
middleware makes it the last crumb and marks it in the sidebar.
*authored* is the front matter the page was written with. Its
`searchWeight`, `prev` and `next` win over the computed ones (a part
page states its neighbours and its weight), and its `consoles` and
`terms` become search fields (astro.config.mjs, metaWeights): the
consoles a manufacturer page holds sections for, and the words a page
answers that its text does not say, as an error message words them.
*words_by_page* holds the console words of every system page, by path
without extension: a console another page's words cover is written
once more, in `exact`."""
authored = meta.authored or {}
title, body = _page_body(rel, markdown, meta.terms, authored, meta.words_by_page or {})
components = used_components(body)
stem = rel.rsplit(".", 1)[0]
if components:
body = _with_imports(mdx_safe(body), components, rel)
front = _page_front(rel, stem, body, title, authored, meta)
return stem + (".mdx" if components else ".md"), _front_matter(front) + body
def _page_body(rel: str, markdown: str, terms: dict[str, str], authored: dict,
words_by_page: Mapping[str, set[str]]) -> tuple[str, str]:
"""The page's title and its body, links rewritten and search fields added."""
title, title_id, body = split_title(markdown)
body = body.lstrip("\n")
body = rewrite_links(body, rel)
body = pin_heading_ids(body, title_id)
if title_id:
# The title is the theme's, with an id of its own: the one MkDocs
# gave it stays an anchor at the top of the text.
body = f'<div id="{html.escape(title_id)}" class="rb-anchor"></div>\n\n' + body
if rel not in ("wiki/glossary.md", "wiki/reference-terms.md"):
body = add_tooltips(body, terms)
# A badge is a status (required, missing, MD5), not a word a reader
# searches for: 141 "missing" badges put an emulator page above the
# troubleshooting page for "missing bios". The archive a file sits in
# is a name, and stays: it is how "neogeo.zip" finds the cores reading it.
body = re.sub(r'<span class="(rb-badge(?![^"]*rb-badge-archive)[^"]*)"',
r'<span data-pagefind-ignore class="\1"', body)
# "Next steps" closes most pages with the same links ("for the setup in
# use"): the "u" of "wii u bios" matched the start of "use" there, and
# the Nintendo page came before the Wii U page.
body = _NEXT_STEPS.sub(
lambda match: f"<div data-pagefind-ignore>\n\n{match[0].rstrip()}\n\n</div>\n\n", body, count=1)
if rel.startswith("systems/"):
body += file_names_meta(body) + search_field("aliases", page_aliases(rel))
consoles = field_words(authored.get("consoles"))
body += search_field("consoles", consoles)
body += search_field("exact", covered_names(consoles, rel.rsplit(".", 1)[0], words_by_page))
body += search_field("terms", field_words(authored.get("terms")) + console_words(consoles))
return title, body
def _with_imports(body: str, components: list[str], rel: str) -> str:
imports: dict[str, list[str]] = {}
for name in components:
imports.setdefault(COMPONENTS[name], []).append(name)
# Our own components are imported from src/, two levels above the
# content collection plus the page's own folders.
up = "../" * (rel.count("/") + 2)
return "".join(f"import {{ {', '.join(names)} }} from '{source}';\n"
if source.startswith("@") else f"import {names[0]} from '{up}{source}';\n"
for source, names in imports.items()) + "\n" + body
def _page_front(rel: str, stem: str, body: str, title: str, authored: dict,
meta: PageMeta) -> dict:
level = meta.level
browser_title = meta.browser_title
structured = meta.structured
front: dict = {"title": title or browser_title, "description": meta.description}
# Starlight's slugger drops dots and plus signs: the address stays MkDocs'.
if re.search(r"[^a-z0-9_/-]", stem):
front["slug"] = stem
if level:
front["level"] = level
if meta.logo:
front["logo"] = meta.logo
parent = meta.parent
if parent:
front["parent"] = {"label": str(parent["label"]),
"link": resolve(rel, str(parent["link"]))}
weight = authored.get("searchWeight", meta.weight)
if weight:
front["searchWeight"] = weight
toc = _table_of_contents(rel, body)
if toc is not None:
front["tableOfContents"] = toc
if not meta.search:
front["pagefind"] = False
_neighbours(front, rel, body, authored)
front["head"] = page_head(rel, level, front["title"], browser_title, structured)
if structured.get("dateModified"):
front["lastmod"] = str(structured["dateModified"])
return front
def _table_of_contents(rel: str, body: str) -> dict | bool | None:
if rel == NOT_FOUND:
return False
if rel.startswith(CARD_PAGES):
sections = len(re.findall(r"^## ", body, re.M))
# A page of cards under one or two headings has nothing to list, and
# the table of contents watches every block of the page to follow
# the reader: 2 x 430 ms of a phone's main thread on 400 cards.
return {"minHeadingLevel": 2, "maxHeadingLevel": 2} if sections > 2 else False
return None
def _neighbours(front: dict, rel: str, body: str, authored: dict) -> None:
step = next_step(body)
if rel == NOT_FOUND or not reads_in_order(rel):
front["prev"] = False
front["next"] = False
elif step:
# The page's own "Next steps" list and the next link agree.
front["next"] = step
for side in ("prev", "next"):
if rel != NOT_FOUND and side in authored:
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)}
return ids | {match["id"] for match in ID_ATTR.finditer(text)}
def reads_in_order(rel: str) -> bool:
"""A page the previous and next links pass through. A system, emulator
or platform page is reached by its name, not read after its neighbour
in the alphabet: "SNK, Sony, Sord" is no reading order."""
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"}
_CORE_NAME = re.compile(r"[a-z0-9_-]+")
def redirects(profiles: dict, present: set[str],
moved: dict[str, str] | None = None) -> dict[str, str]:
"""Old and alternative addresses, for src/generated/redirects.json.
A page that moved, once its source is gone, and each name a profile's
`cores:` gives the emulator (the buildbot's `mednafen_psx` for
beetle_psx), to the profile's page, and an alias profile's own name to
the page of the profile it is an alias of. A name two profiles claim, or one
that is already a page's address, is left out. Addresses are written
under the site root, without its base. ``moved`` adds pages that moved
by generation, old page to new page, the new one with an optional
#fragment. A page MOVED_PAGES names keeps that target over the part
record: cross-reference-minui is answered on MinUI's own page."""
def address(rel: str) -> str:
page, _, fragment = rel.partition("#")
return "/" + page_url(page)[len(BASE):] + (f"#{fragment}" if fragment else "")
out = {address(old): address(new) for old, new in {**(moved or {}), **MOVED_PAGES}.items()
if old not in present and new.partition("#")[0] in present}
pages = {rel.casefold() for rel in present}
claims: dict[str, set[str]] = {}
for key, profile in profiles.items():
if f"emulators/{key}.md" not in present:
continue
for name in profile.get("cores") or []:
name = str(name)
if _CORE_NAME.fullmatch(name) and name != key:
claims.setdefault(name, set()).add(key)
# An alias profile has no page of its own: its name is the address of
# the profile it designates (emulators/vba_m/ is VBA-M's, under vbam).
for key, profile in profiles.items():
target = str(profile.get("alias_of") or "")
if (profile.get("type") == "alias" and _CORE_NAME.fullmatch(key)
and f"emulators/{target}.md" in present):
claims.setdefault(key, set()).add(target)
for name, keys in sorted(claims.items()):
if len(keys) == 1 and f"emulators/{name}.md".casefold() not in pages:
out[address(f"emulators/{name}.md")] = address(f"emulators/{next(iter(keys))}.md")
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
def picker_data(install: Path, out: Path, titles: dict[str, str]) -> int:
"""Each manifest, compacted to what the file picker reads: per file its
destination, size and systems, the systems install.py --system accepts.
`titles` names a system id the way its system page does.
"""
out.mkdir(parents=True, exist_ok=True)
index = []
for manifest in sorted(install.glob("*.json")):
data = json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(data, dict) or "files" not in data or "platform" not in data:
continue
systems = sorted({s for f in data["files"] for s in f.get("systems") or []})
position = {s: k for k, s in enumerate(systems)}
names = data.get("system_names") or {}
payload = {
"platform": data["platform"],
"name": data.get("display_name", data["platform"]),
"folder": (data.get("detect") or [{}])[0].get("bios_path", ""),
"generated": data.get("generated", ""),
"systems": [{"id": s, "title": titles.get(s, ""), "native": names.get(s, [])}
for s in systems],
"other": any(not f.get("systems") for f in data["files"]),
"files": [[f["dest"], f.get("size", 0), [position[s] for s in f.get("systems") or []]]
for f in sorted(data["files"], key=lambda f: f["dest"])],
}
(out / f"{data['platform']}.json").write_text(
json.dumps(payload, separators=(",", ":")), encoding="utf-8")
index.append({"platform": data["platform"], "name": payload["name"],
"files": len(payload["files"])})
index.sort(key=lambda entry: entry["name"].casefold())
(out / "index.json").write_text(json.dumps(index, separators=(",", ":")), encoding="utf-8")
return len(index)
def quote_url(url: str) -> str:
return urllib.parse.quote(url, safe="/:#?=&%")
+277
View File
@@ -0,0 +1,277 @@
"""What the install box of Get the files shows under each tab.
Two things per tab, both drawn from data:
- The steps that differ by system, opening a terminal and pasting the line,
as a drawing: one card per step, a pictogram and a short caption, drawn
with sitediagrams' primitives and shown as its SVG files, one per layout
and theme (sitediagrams.pictures). The text steps above it
(platforms/_guides.yml, terminals) are the one text source: the images
are alt="", so the page reads the steps once. The files say the same in
their title and desc, for one opened on its own. The pictograms are
generic shapes (a menu, a search field, a window, keys, a mouse, the
power symbol), no vendor's interface or logo.
- The installer demo recorded for that place (scripts/make_demo.py): the
full-screen interface on a handheld under "On the device", the terminal
recording under the others but Windows. No Windows recording is
published (make_demo.py says why), and a curl line recorded in a Linux
terminal under the PowerShell command would contradict it.
"""
from __future__ import annotations
from dataclasses import dataclass
from xml.sax.saxutils import escape
from sitegen import markup
from sitediagrams import (
MONO_STYLE,
NARROW,
STROKE,
TEXT_SIZE,
WIDE,
_badge,
_badge_side,
_line,
_n,
_rect,
_text,
diagram_files,
pictures,
svg_document,
wrap,
)
KEY_SIZE = 11.5
ICON_H = 44.0
@dataclass(frozen=True)
class Step:
"""One card: a pictogram (*icon* and its *word*, the text it shows:
keys joined by "+", the word typed in a search field) and a caption."""
icon: str
caption: str
word: str = ""
STEPS: dict[str, tuple[str, tuple[Step, ...]]] = {
"windows": ("Windows: open PowerShell and paste the line", (
Step("menu", "Open the Start menu"),
Step("search", "Type PowerShell and press Enter", "PowerShell"),
Step("copy", "Click Copy, the button by the line"),
Step("mouse", "Right-click in the window to paste"),
Step("keys", "Press Enter", "Enter"),
)),
"macos": ("macOS: open Terminal and paste the line", (
Step("keys", "Press Cmd+Space", "Cmd+Space"),
Step("search", "Type Terminal and press Return", "Terminal"),
Step("copy", "Click Copy, the button by the line"),
Step("keys", "Press Cmd+V to paste", "Cmd+V"),
Step("keys", "Press Return", "Return"),
)),
"linux": ("Linux: open a terminal and paste the line", (
Step("keys", "Open a terminal, often Ctrl+Alt+T", "Ctrl+Alt+T"),
Step("copy", "Click Copy, the button by the line"),
Step("keys", "Press Ctrl+Shift+V to paste", "Ctrl+Shift+V"),
Step("keys", "Press Enter", "Enter"),
)),
"steamdeck": ("Steam Deck: open Konsole and paste the line", (
Step("power", "Hold power, pick Switch to Desktop"),
Step("window", "Open Konsole"),
Step("copy", "Click Copy, the button by the line"),
Step("keys", "Press Ctrl+Shift+V to paste", "Ctrl+Shift+V"),
Step("keys", "Press Enter", "Enter"),
)),
}
# The recording each tab shows (docs_assets/demo/demo.json keys), "" for none.
TAB_DEMOS = {"device": "handheld", "windows": ""}
DEFAULT_DEMO = "default"
def demo_variant(tab: str) -> str:
return TAB_DEMOS.get(tab, DEFAULT_DEMO)
def description(tab: str) -> str:
"""The steps in words: the desc of the SVG files."""
return " ".join(f"{index}. {step.caption}." for index, step in
enumerate(STEPS[tab][1], start=1))
# Pictograms, drawn in a box *w* wide and ICON_H high from (x, y).
def _stroke(d: str, cls: str = "rb-d-line", width: float = 1.5) -> str:
return f'<path d="{d}" fill="none" stroke="{STROKE}" stroke-width="{_n(width)}" class="{cls}"/>'
def _key_width(label: str) -> float:
return max(20.0, len(label) * KEY_SIZE * 0.62 + 10)
def _keys(x: float, y: float, w: float, word: str) -> list[str]:
labels = word.split("+")
total = sum(_key_width(label) for label in labels) + 4 * (len(labels) - 1)
left = x + (w - total) / 2
out = []
top = y + ICON_H / 2 - 12
for label in labels:
width = _key_width(label)
out.append(_rect(left, top, width, 24, accent=True))
out.append(
f'<text x="{_n(left + width / 2)}" y="{_n(top + 16.5)}" font-size="{_n(KEY_SIZE)}" '
f'text-anchor="middle" fill="currentColor" style="{MONO_STYLE}">{escape(label)}</text>')
left += width + 4
return out
def _menu(x: float, y: float, w: float) -> list[str]:
cx, top = x + w / 2, y + 4
out = [_rect(cx - 22, top, 44, 36)]
out += [_stroke(f"M{_n(cx - 14)} {_n(top + 10 + 8 * i)} H{_n(cx + 14)}") for i in range(3)]
return out
def _search(x: float, y: float, w: float, word: str) -> list[str]:
width = min(w - 4, len(word) * KEY_SIZE * 0.62 + 34)
left, top = x + (w - width) / 2, y + ICON_H / 2 - 12
return [
_rect(left, top, width, 24, accent=True),
f'<circle cx="{_n(left + 11)}" cy="{_n(top + 11)}" r="5" fill="none" stroke="{STROKE}" '
'stroke-width="1.5" class="rb-d-line"/>',
_stroke(f"M{_n(left + 15)} {_n(top + 15)} L{_n(left + 19)} {_n(top + 19)}"),
f'<text x="{_n(left + 25)}" y="{_n(top + 16.5)}" font-size="{_n(KEY_SIZE)}" '
f'fill="currentColor" style="{MONO_STYLE}">{escape(word)}</text>',
]
def _window(x: float, y: float, w: float) -> list[str]:
cx, top = x + w / 2, y + 2
return [
_rect(cx - 32, top, 64, 40),
_stroke(f"M{_n(cx - 32)} {_n(top + 9)} H{_n(cx + 32)}"),
f'<text x="{_n(cx - 24)}" y="{_n(top + 28)}" font-size="{_n(KEY_SIZE)}" '
f'fill="currentColor" style="{MONO_STYLE}">&gt;_</text>',
]
def _copy(x: float, y: float, w: float) -> list[str]:
cx, top = x + w / 2, y + 6
return [_rect(cx - 12, top, 18, 24), _rect(cx - 6, top + 7, 18, 24, accent=True)]
def _mouse(x: float, y: float, w: float) -> list[str]:
cx, top = x + w / 2, y + 2
return [
f'<rect x="{_n(cx - 13)}" y="{_n(top)}" width="26" height="40" rx="12" fill="none" '
f'stroke="{STROKE}" stroke-width="1.5" class="rb-d-line"/>',
# The right button, the one to press.
f'<path d="M{_n(cx + 1)} {_n(top + 1)} A12 12 0 0 1 {_n(cx + 12)} {_n(top + 13)} '
f'L{_n(cx + 1)} {_n(top + 13)} Z" fill="currentColor" class="rb-d-num"/>',
_stroke(f"M{_n(cx)} {_n(top)} V{_n(top + 14)} M{_n(cx - 13)} {_n(top + 14)} "
f"H{_n(cx + 13)}"),
]
def _power(x: float, y: float, w: float) -> list[str]:
cx, cy = x + w / 2, y + ICON_H / 2 + 2
return [
_stroke(f"M{_n(cx - 9)} {_n(cy - 11)} A14 14 0 1 0 {_n(cx + 9)} {_n(cy - 11)}", width=2.5),
_stroke(f"M{_n(cx)} {_n(cy - 18)} V{_n(cy - 2)}", width=2.5),
]
def _icon(step: Step, x: float, y: float, w: float) -> list[str]:
if step.icon == "keys":
return _keys(x, y, w, step.word)
if step.icon == "search":
return _search(x, y, w, step.word)
return {"menu": _menu, "window": _window, "copy": _copy, "mouse": _mouse,
"power": _power}[step.icon](x, y, w)
def _wide(steps: tuple[Step, ...]) -> tuple[float, float, list[str]]:
"""The cards in a row, joined by arrows."""
gap = 14.0
width = (WIDE - gap * (len(steps) - 1) - 2) / len(steps)
captions = [wrap(step.caption, width - 12, TEXT_SIZE) for step in steps]
height = 34 + ICON_H + 10 + max(len(lines) for lines in captions) * 18 + 8
out: list[str] = []
for index, (step, lines) in enumerate(zip(steps, captions)):
x = 1 + index * (width + gap)
out.append(_rect(x, 1, width, height))
out += _badge(x + 8, 8, str(index + 1))
out += _icon(step, x + 4, 30, width - 8)
y = 30 + ICON_H + 24
for line in lines:
out.append(_text(x + width / 2, y, line, anchor="middle"))
y += 18
if index < len(steps) - 1:
mid = 1 + height / 2
out += _line([(x + width + 1, mid), (x + width + gap - 1, mid)])
return WIDE, height + 2, out
def _narrow(steps: tuple[Step, ...]) -> tuple[float, float, list[str]]:
"""One card a row: number, pictogram, caption."""
icon_w, row_gap = 112.0, 8.0
text_x = 8 + _badge_side("9") + 6 + icon_w + 8
out: list[str] = []
y = 1.0
for index, step in enumerate(steps):
lines = wrap(step.caption, NARROW - text_x - 8, TEXT_SIZE)
height = max(ICON_H + 12, len(lines) * 18 + 16)
out.append(_rect(1, y, NARROW - 2, height))
out += _badge(8, y + height / 2 - 10, str(index + 1))
out += _icon(step, 8 + _badge_side("9") + 6, y + (height - ICON_H) / 2, icon_w)
ty = y + height / 2 - (len(lines) - 1) * 9 + 5
for line in lines:
out.append(_text(text_x, ty, line))
ty += 18
y += height + row_gap
return NARROW, y - row_gap + 1, out
def _svg(tab: str, layout: str) -> str:
title, steps = STEPS[tab]
width, height, body = (_wide if layout == "wide" else _narrow)(steps)
return svg_document(width, height, title, description(tab), body, f"rb-steps-{tab}-{layout}")
def _layouts(tab: str) -> dict[str, str]:
return {layout: _svg(tab, layout) for layout in ("wide", "narrow")}
def stem(tab: str) -> str:
return f"steps-{tab}"
def steps_files() -> dict[str, str]:
"""Every tab's drawing files, by name under sitediagrams.DIAGRAM_DIR."""
return {name: text for tab in STEPS for name, text in diagram_files(stem(tab), _layouts(tab)).items()}
def steps_figure(tab: str) -> list[str]:
"""The figure of a tab's steps, both layouts in both themes, or nothing
for a tab with no drawing. The steps above it say its words."""
if tab not in STEPS:
return []
return [f'<figure class="rb-figure rb-steps" {markup.search_exclude()}>',
pictures(stem(tab), _layouts(tab)), "</figure>", ""]
def tab_demo(tab: str) -> list[str]:
"""The recording a tab shows, as generate_site writes the component."""
from generate_site import install_demo
variant = demo_variant(tab)
return install_demo(variant, tab) if variant else []
def install_box(tabs: tuple[str, ...]) -> tuple[dict[str, list[str]], dict[str, list[str]]]:
"""What terminal_tabs puts under each tab's steps and under its command."""
return ({tab: steps_figure(tab) for tab in tabs},
{tab: tab_demo(tab) for tab in tabs})
+583
View File
@@ -0,0 +1,583 @@
"""The files the collection lacks, as the wanted page reads them.
A visitor drops files on wanted/, each is hashed in the browser and
compared with this list, and the page lists every entry under the drop
box. The list is the gaps page's: a file a platform lists that its own
check finds missing or under another hash, a file an emulator loads that
no platform lists and the collection does not hold, and a file not
collected yet. A declaration that names no hash is kept and marked: it
is recognised by its name only, and the review of the upload decides.
Each entry keeps the hashes its declaration writes, read as the resolver
reads them (comma lists split, a crc32 counted only where no stronger hash
is declared), and the folder validate_pr.placement() gives those hashes:
the review of the pull request asks for that same folder.
"""
from __future__ import annotations
import re
import urllib.parse
from collections.abc import Callable, Iterable
from pathlib import Path
import archive_build
from resolve.layout import runs_standalone
from model.profiles import unique_emulator_profiles
from packs.crossref import _first_hash
from core.hashing import cut_md5_owner, parse_hash_list
from resolve.review import LARGE_FILE_ISSUE_URL, Placement, placement
from resolve.validation import deliverable, filter_files_by_mode, installed_with_emulator
ALGORITHMS = ("sha1", "sha256", "md5", "crc32")
# GitHub's upload page takes 25 MB per file. A larger file goes in by a
# push or, past 100 MB, through the issue form (CONTRIBUTING.md).
BROWSER_UPLOAD_LIMIT = 25 * 1024 * 1024
# The upload page of a folder is this followed by the folder.
UPLOAD_ROOT = "https://github.com/Abdess/retrobios/upload/main/"
# Under the site's public folder, read by WantedFiles.astro.
DATA_FILE = "data/wanted.json"
def _sizes(entry: dict) -> list[int]:
size = entry.get("size")
values = size if isinstance(size, list) else [size]
return sorted({int(v) for v in values if isinstance(v, int) and not isinstance(v, bool) and v > 0})
def declared_hashes(entry: dict) -> dict[str, list[str]]:
"""The hashes that identify an entry's own bytes, by algorithm.
A zipped_file md5 is the md5 of a ROM inside the archive, not of the
archive, so it says nothing about the file a visitor drops. A crc32
counts only where no stronger hash is declared, as in
resolve_local_file.
"""
hashes = {algo: parse_hash_list(entry.get(algo)) for algo in ALGORITHMS}
if entry.get("zipped_file"):
hashes["md5"] = []
hashes["md5"] = [v for v in hashes["md5"] if 0 < len(v) <= 32]
hashes["sha1"] = [v for v in hashes["sha1"] if len(v) == 40]
hashes["sha256"] = [v for v in hashes["sha256"] if len(v) == 64]
hashes["crc32"] = [v.zfill(8) for v in hashes["crc32"] if len(v) <= 8]
if hashes["sha1"] or hashes["sha256"] or hashes["md5"]:
hashes["crc32"] = []
return {algo: values for algo, values in hashes.items() if values}
def _alternatives(hashes: dict[str, list[str]]) -> list[dict[str, list[str]]]:
"""One declaration per file it accepts.
A Recalbox entry lists every revision its check takes in one md5 field:
each is a file of its own, with a folder of its own. Values of two
algorithms cannot be paired, so such an entry stays whole.
"""
listed = [algo for algo, values in hashes.items() if len(values) > 1]
if len(hashes) == 1 and listed:
algo = listed[0]
return [{algo: [value]} for value in hashes[algo]]
return [hashes]
class Held:
"""What the collection holds, by every hash a file or an archive
member is known under."""
def __init__(self, db: dict, ledger: Iterable[dict] = ()) -> None:
files = db.get("files", {})
indexes = db.get("indexes", {})
self.sha1 = set(files)
self.md5 = set(indexes.get("by_md5", {}))
self.sha256 = set(indexes.get("by_sha256", {}))
self.crc32: dict[str, set[int]] = {}
for record in files.values():
crc = str(record.get("crc32") or "").lower()
if crc:
self.crc32.setdefault(crc, set()).add(int(record.get("size") or 0))
# A ROM held only inside one of the collection's archives.
for archive in ledger:
for member in archive.get("members") or []:
if member.get("sha1"):
self.sha1.add(str(member["sha1"]).lower())
crc = str(member.get("crc32") or "").lower()
if crc:
self.crc32.setdefault(crc, set()).add(int(member.get("size") or 0))
def holds(self, hashes: dict[str, list[str]], sizes: list[int]) -> bool:
if any(v in self.sha1 for v in hashes.get("sha1", [])):
return True
if any(v in self.sha256 for v in hashes.get("sha256", [])):
return True
for value in hashes.get("md5", []):
if value in self.md5 or (len(value) < 32 and cut_md5_owner(value, self.md5)):
return True
for value in hashes.get("crc32", []):
held = self.crc32.get(value, set())
if held and (not sizes or held & set(sizes)):
return True
return False
def gap_entries(profile: dict, name: str, identity: str, unsourceable: bool) -> list[dict]:
"""The profile entries behind one row of the gap report."""
named = [f for f in profile.get("files") or []
if isinstance(f, dict) and f.get("name") == name]
if unsourceable:
return [f for f in named if f.get("unsourceable")] or named
if identity:
return [f for f in named if _first_hash(f) == identity] or named
return named
def _directory(entry: dict) -> str:
"""The directory a declaration names for its file: a platform's
destination, a profile's path. Empty for a bare name."""
where = str(entry.get("destination") or entry.get("path") or "")
return where.rsplit("/", 1)[0] + "/" if "/" in where else ""
def _paired(files: list, details: list[dict]) -> Iterable[tuple[dict, dict]]:
"""Each verify detail of a system with the declaration it scores.
verify scores the declarations of a system in order, one detail each,
so the k-th detail of a name is the k-th declaration of that name:
AmberELEC declares config.ini once per blueMSX machine, and a match by
name alone gave each missing one every machine's folder.
"""
by_name: dict[str, list[dict]] = {}
for entry in files:
if isinstance(entry, dict):
by_name.setdefault(str(entry.get("name")), []).append(entry)
seen: dict[str, int] = {}
for detail in details:
name = str(detail.get("name"))
position = seen.get(name, 0)
seen[name] = position + 1
same = by_name.get(name, [])
if position < len(same):
yield detail, same[position]
def _brought_by_readers(detail: dict, config: dict, platform: str, profiles: dict) -> bool:
"""Whether every core that reads a platform entry installs it itself.
The readers are those verify names for the entry's category, the cores
of its system first. A reader brings the file when the entries of its
build that read it are all installed with it (validation.deliverable,
the rule the pack builder applies).
"""
readers = (detail.get("category_evidence") or {}).get("read_by") or []
own = [r for r in readers if r.get("runs_system")] or readers
standalone_cores = set(config.get("standalone_cores") or [])
verdicts = []
for reader in own:
profile = profiles.get(reader.get("emulator", ""))
if not profile:
continue
names = {str(e.get("name")) for e in reader.get("entries") or []}
read = [f for f in profile.get("files") or []
if isinstance(f, dict) and str(f.get("name")) in names]
standalone = runs_standalone(reader["emulator"], profile, standalone_cores)
if filter_files_by_mode(read, standalone):
verdicts.append(not deliverable(read, standalone, platform))
return bool(verdicts) and all(verdicts)
def wanted_declarations(profiles: dict, coverages: dict, gap_report: dict) -> list[dict]:
"""Every declaration of a file the gaps page reports as lacking.
Each is {name, system, required, reader: (kind, key, label), entry,
reason, category, directory}: the reason a file not collected yet
carries, empty otherwise, and bios or unread as verify (a platform's
entry) or the profile (an emulator's) gives it. Game data is no
contributor's to send, and a file the emulator installs itself
(`bundled`, scoped by the build that reads it) is no gap: neither is
a declaration here.
"""
found: list[dict] = []
for key, coverage in sorted(coverages.items()):
systems = coverage.get("config", {}).get("systems") or {}
by_system: dict[str, list[dict]] = {}
for detail in coverage.get("details", []):
by_system.setdefault(detail.get("system", ""), []).append(detail)
for system, details in sorted(by_system.items()):
files = (systems.get(system) or {}).get("files") or []
for detail, entry in _paired(files, details):
if detail.get("settled_by") or detail.get("status") not in ("missing", "untested"):
continue
if detail.get("category") == GAME_DATA or _brought_by_readers(
detail, coverage.get("config", {}), key, profiles):
continue
found.append({
"name": str(entry["name"]), "system": system,
"required": bool(detail.get("required", True)),
"reader": ("platform", key, coverage["platform"]), "entry": entry,
"reason": "",
"category": detail.get("category") if detail.get("category") in RANK else BIOS,
"directory": _directory(entry),
})
unique = unique_emulator_profiles(profiles)
for key, data in sorted(gap_report.items()):
profile = unique.get(key)
if profile is None:
continue
systems = [str(s) for s in data.get("systems") or profile.get("systems") or []]
rows = [(gap, False) for gap in data.get("gap_details") or []
if gap.get("source") == "missing" and not gap.get("bundled")]
rows += [(row, True) for row in data.get("unsourceable") or []]
for row, unsourceable in rows:
for entry in gap_entries(profile, str(row.get("name", "")),
str(row.get("identity") or ""), unsourceable):
if entry.get("category") == GAME_DATA or installed_with_emulator(entry):
continue
system = entry.get("system") or (systems[0] if len(systems) == 1 else "")
found.append({
"name": str(entry["name"]), "system": str(system),
"required": bool(row.get("required", False)),
"reader": ("emulator", key, str(data.get("emulator", key))), "entry": entry,
"reason": str(row.get("reason") or "") if unsourceable else "",
"category": BIOS,
"directory": _directory(entry),
})
return found
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
BIOS = "bios"
GAME_DATA = "game_data"
# verify's category for a platform entry no core the platform runs reads.
UNREAD = "unread"
# Firmware first, then what a platform lists and no core reads.
RANK = {BIOS: 0, UNREAD: 1}
# A name the code builds from the content (<serial>.txt, *.ini) is a
# pattern, not a file anyone can upload.
PATTERN = re.compile(r"[<>*?]")
# A file not collected yet stays wanted, however hard it is to find ("no
# public dump located", "retail data the collection does not hold"). It
# leaves the list only when its reason (the profile's `unsourceable:`)
# says no copy can be shared, read by the rules below.
NOT_SHAREABLE = re.compile("|".join([
# Any file of the name serves: there is no one file to collect.
r"\bno canonical\b",
# The user writes, picks, records or places it (WHDLoad's key aside,
# emucorev's config.txt: "plugin list the user writes").
r"\bthe user\b|\buser[- ](?:supplied|authored|created|settings|overlay|placeholder)\b"
r"|\bother users\b",
# The emulator or the guest writes it: a save, a state, a generated key.
r"\bwritten by (?:the (?:emulator|guest|firmware editor)|bam)\b|\bgenerated by the emulator\b"
r"|\bwith the debug key\b|\bmachine state\b|\bcreat\w* (?:this directory )?empty\b",
# It belongs to one person, one account or one copy (puae's WHDLoad.key).
r"\bper[- ]user\b|\btied to the (?:account|tag)\b|\bnever distributed generically\b"
r"|\bissued for one copy\b",
# Nothing was ever released under the name.
r"\bno (?:distributed form|released artefact|hardware dump equivalent)\b"
r"|\bno file of this name is distributed\b",
]), re.I)
def shareable(reason: str) -> bool:
"""False when a reason says no copy of the file can be shared."""
return not NOT_SHAREABLE.search(reason)
def _settle_cut(records: list[dict]) -> None:
"""A cut md5 names a dump only if exactly one md5 starts with it.
Matched against the wanted md5s: with one match the cut is that md5.
With several it names none, and an entry left with no hash is known by
its name. With none the page compares by prefix.
"""
full = {v for r in records for v in r["hashes"].get("md5", []) if len(v) == 32}
for record in records:
kept = []
for value in record["hashes"].get("md5", []):
if len(value) == 32:
kept.append(value)
continue
starting = {md5 for md5 in full if md5.startswith(value)}
if len(starting) == 1:
kept.append(starting.pop())
elif not starting:
kept.append(value)
if kept:
record["hashes"]["md5"] = sorted(set(kept))
else:
record["hashes"].pop("md5", None)
class Placer:
"""validate_pr's placement for a declaration: its declared hashes,
strongest first, and its name.
The database stands in for the disk validate_pr reads: the site is
built from a checkout whose release assets are not on disk.
"""
def __init__(self, db: dict, platform_hashes: dict, profile_hashes: dict) -> None:
self.db = db
self.platform_hashes = platform_hashes
self.profile_hashes = profile_hashes
self.paths = {
path for record in db.get("files", {}).values()
for path in [record.get("path"), *(record.get("paths") or [])] if path
}
def place(self, hashes: dict[str, list[str]], name: str, systems: Iterable[str] = (),
directory: str = "") -> Placement:
"""A declaration that writes no hash is known by its name alone,
as the review knows a file whose hashes nothing declares, and its
folder comes from its systems and its declared directory."""
values = [value for algo in ("sha1", "md5", "sha256") for value in hashes.get(algo, [])
if len(value) == FULL_LENGTH[algo]]
return placement(values, name, self.db, self.platform_hashes, self.profile_hashes,
declared=bool(hashes), exists=self.paths.__contains__,
systems=sorted(systems), directory=directory)
def folder(self, entry: dict, system: str = "") -> str:
"""The folder an upload of a profile or platform entry goes to."""
system = str(entry.get("system") or system)
return self.place(declared_hashes(entry), str(entry.get("name", "")),
[system] if system else [], _directory(entry)).folder
FULL_LENGTH = {"sha1": 40, "md5": 32, "sha256": 64}
def upload_href(root: str, folder: str) -> str:
"""GitHub's upload page for a folder of the repository, bios/ when the
placement names none."""
return root + urllib.parse.quote((folder or "bios/").rstrip("/"))
def _order(record: dict) -> tuple:
"""Most useful first: firmware, then the files no core reads, required
first in each, then by how many setups and emulators read the file."""
return (RANK[record["category"]], not record["required"], -len(record["readers"]),
record["name"].casefold(), sorted(record["readers"]))
def reader_page(kind: str, key: str, entry: dict) -> str:
"""Where a reader's page is, below the site root: the page a row of
the list links when no card anchor is given."""
return f"{'emulators' if kind == 'emulator' else 'platforms'}/{key}/"
def build_wanted(
profiles: dict,
coverages: dict,
gap_report: dict,
db: dict,
placer: Placer,
system_name: Callable[[str], str],
ledger: Iterable[dict] = (),
link: Callable[[str, str, dict], str] = reader_page,
) -> dict:
"""The wanted list, compact, as public/data/wanted.json carries it.
Readers, systems and folders are written once and named by position.
An entry: n name, h hashes (absent when the declarations write none:
the file is known by its name only), c a crc32 a declaration writes
beside a stronger hash (shown, never matched), w readers, s systems,
r required, z sizes, a the page holding its details (*link*: the card
of the first emulator that reads it, else the page of the first setup
that lists it), f folder, t the name it is uploaded under, v that name
goes to the folder's .variants/ with the first 8 characters of its
sha1. Entries come most useful first (_order). A file no one can share
(the reason says so, NOT_SHAREABLE) is left out.
"""
records = _collect_records(wanted_declarations(profiles, coverages, gap_report),
Held(db, ledger), link)
_merge_named(records)
ordered = sorted(records.values(), key=_order)
_settle_cut(ordered)
readers = sorted({reader for r in ordered for reader in r["readers"]},
key=lambda reader: (reader[0], reader[2].casefold(), reader[1]))
reader_at = {reader: i for i, reader in enumerate(readers)}
titles = sorted({system_name(s) for r in ordered for s in r["systems"]}, key=str.casefold)
title_at = {title: i for i, title in enumerate(titles)}
folders: list[str] = []
folder_at: dict[str, int] = {}
entries = []
for record in ordered:
spot = placer.place(record["hashes"], record["name"], record["systems"],
record["directory"])
if spot.folder and spot.folder not in folder_at:
folder_at[spot.folder] = len(folders)
folders.append(spot.folder)
entries.append(_compact(record, spot, reader_at,
{s: title_at[system_name(s)] for s in record["systems"]},
folder_at))
return {
"upload": UPLOAD_ROOT,
"issue": LARGE_FILE_ISSUE_URL,
"limit": BROWSER_UPLOAD_LIMIT,
"readers": [[kind[0], key, label] for kind, key, label in readers],
"systems": titles,
"folders": folders,
"entries": entries,
}
def _collect_records(declarations: Iterable[dict], held: Held,
link: Callable[[str, str, dict], str]) -> dict[tuple, dict]:
"""One record per wanted file, keyed by name and hashes (or name,
system and folder when no hash is written), merging every declaration
of it. A file the collection holds, a pattern and a file no one can
share are left out."""
records: dict[tuple, dict] = {}
for declaration in declarations:
if PATTERN.search(declaration["name"]) or not shareable(declaration["reason"]):
continue
entry = declaration["entry"]
sizes = _sizes(entry)
for hashes in _alternatives(declared_hashes(entry)):
if hashes and held.holds(hashes, sizes):
continue
key = ((declaration["name"], tuple(sorted((a, tuple(v)) for a, v in hashes.items())),
tuple(sizes)) if hashes
else (declaration["name"].casefold(), declaration["system"],
declaration["directory"]))
record = records.setdefault(key, {
"name": declaration["name"], "hashes": {a: list(v) for a, v in hashes.items()},
"sizes": sizes, "systems": set(), "required": False, "readers": set(),
"category": UNREAD, "directory": declaration["directory"],
"crc": set(), "links": {},
})
if RANK[declaration["category"]] < RANK[record["category"]]:
record["category"] = declaration["category"]
if declaration["system"]:
record["systems"].add(declaration["system"])
record["required"] = record["required"] or declaration["required"]
record["readers"].add(declaration["reader"])
record["crc"] |= {v.zfill(8) for v in parse_hash_list(entry.get("crc32")) if len(v) <= 8}
kind, reader_key, _label = declaration["reader"]
record["links"].setdefault((kind != "emulator", reader_key), link(kind, reader_key, entry))
return records
def _compact(record: dict, spot: Placement, reader_at: dict, system_at: dict[str, int],
folder_at: dict[str, int]) -> dict:
"""The compact entry of one record, as build_wanted describes it."""
item: dict = {"n": record["name"]}
if record["hashes"]:
item["h"] = {algo: record["hashes"][algo] for algo in ALGORITHMS if algo in record["hashes"]}
if record["crc"] and "crc32" not in record["hashes"]:
item["c"] = sorted(record["crc"])
item["w"] = sorted(reader_at[reader] for reader in record["readers"])
systems = sorted(set(system_at.values()))
if systems:
item["s"] = systems
if record["required"]:
item["r"] = 1
if record["sizes"]:
item["z"] = record["sizes"]
item["a"] = record["links"][min(record["links"])]
if spot.folder:
item["f"] = folder_at[spot.folder]
if spot.name:
item["t"] = spot.name
if spot.variant:
item["v"] = 1
return item
def _merge_named(records: dict[tuple, dict]) -> None:
"""A declaration that writes no hash takes any file of its name: when
a declaration of the same name and system writes one, the file that
meets it meets both, so its readers join that entry."""
hashed: dict[tuple[str, str], list[dict]] = {}
for record in records.values():
if record["hashes"]:
for system in record["systems"] or {""}:
hashed.setdefault((record["name"].casefold(), system), []).append(record)
for key in [k for k, record in records.items() if not record["hashes"]]:
targets = hashed.get(key[:2], [])
if len(targets) != 1:
continue
record = records.pop(key)
target = targets[0]
target["readers"] |= record["readers"]
target["required"] = target["required"] or record["required"]
target["crc"] |= record["crc"]
for where, href in record["links"].items():
target["links"].setdefault(where, href)
if RANK[record["category"]] < RANK[target["category"]]:
target["category"] = record["category"]
def load_ledger(path: Path) -> list[dict]:
"""The archive records of recipes/archives.json, empty when absent."""
return list(archive_build.load_ledger(path).values())
def page(total: int, known: int) -> str:
"""The wanted page: the drop box, the steps from a file in hand to a
file in the collection, then the table of every wanted file
(WantedList.astro).
Held to the Start here budgets (tests/test_site_copy.py): anyone with a
file in hand reads it.
"""
return "\n".join([
"---",
"terms: wanted list, donate, give a file, upload to github, help the collection, missing bios",
"---",
"",
"# Wanted",
"",
"Have a file the collection lacks? Drop it below to see if it is wanted.",
"Files are read on this device. Nothing leaves it before an upload to GitHub.",
"",
"<WantedFiles />",
"",
"Several files at once? Drop them all. Each gets its own answer and upload button.",
"",
"## Where a file comes from",
"",
"- A console or handheld at home: its BIOS, copied with a homebrew tool.",
"- An old SD card, or the BIOS folder of an emulator used before.",
"- A firmware update package from the maker.",
"",
"To check any other file, use [Find or check a file](files/index.md).",
"",
"## Send it",
"",
"1. Make a free GitHub account once: [sign up](https://github.com/signup).",
"2. Drop the file at the top. If it is wanted, its button opens the right folder on GitHub.",
"3. Rename the file if the page asks, then drop it there.",
"4. GitHub makes a copy of the project and opens a pull request, a request to add the file.",
"5. A check reads the file and comments on the request.",
"",
"The maintainer then merges it, and the file joins the downloads and the installer.",
"",
(f"A file over {BROWSER_UPLOAD_LIMIT // (1024 * 1024)} MB is too large for the upload page. "
"Its button opens an issue form with the details filled in."),
"",
"## The wanted list",
"",
(f"{total:,} files, required firmware first. A name opens its details. "
f"{known:,} have a fingerprint (a hash), so a dropped copy is recognised."),
"",
"The others are known by name only: a dropped file of that name gets a button too.",
"",
"<WantedList />",
"",
"More ways to help are on [Contributing](contributing.md).",
"",
])
+102
View File
@@ -0,0 +1,102 @@
"""Writing the site, and knowing what was written.
The generated tree is swept rather than deleted: a page is removed
only once nothing produces it, so a page whose content did not move
keeps its bytes and a deploy stops republishing the whole site for
the clock alone."""
from __future__ import annotations
from pathlib import Path
from core.artifacts import write_if_changed as _write_artifact
import os
# Every path this run produced. The generated directories used to be deleted
# before the build, which made every page new: write_if_changed had no earlier
# version to compare against, so the whole site was rewritten for the clock
# alone and a deploy republished 600 unchanged pages. They are swept instead,
# and a page is only removed once nothing produced it.
_produced: set[str] = set()
def _record(path: str | Path) -> None:
_produced.add(os.path.realpath(str(path)))
# The reader level label the decoration pass puts above a page's title.
LEVEL_LABEL_START = '<span class="rb-level '
def _undecorated(markdown: str) -> str:
"""Return a page body without the front matter the decoration pass adds."""
if markdown.startswith("---\n") and "generated_by: retrobios-site" in markdown[:300]:
end = markdown.find("\n---\n", 4)
if end != -1:
markdown = markdown[end + 5:].lstrip("\n")
script_end = markdown.find("</script>\n\n")
if markdown.startswith('<script type="application/ld+json">') and script_end != -1:
markdown = markdown[script_end + len("</script>\n\n"):]
if markdown.startswith(LEVEL_LABEL_START):
markdown = markdown[markdown.find("\n\n") + 2:]
return markdown
def write_if_changed(path: str, content: str) -> bool:
"""Write a page body only when it moved, and remember it either way.
A page is written twice: the body here, then the same body wrapped in
front matter by the decoration pass. This comparison therefore reduces
the file on disk to its body. The decoration pass compares in full -
normalizing there too would make its own write look like a no-op and
every page would lose its front matter.
"""
_record(path)
return _write_artifact(path, content, normalize=_undecorated)
def write_decorated(path: str | Path, content: str) -> bool:
"""Write the wrapped page, comparing front matter and body together."""
_record(path)
return _write_artifact(str(path), content)
# A page body is written as .md and the decoration pass, which runs after
# the sweep, gives it its final extension: .mdx when it holds components,
# the other file removed. The .mdx a previous run left is that same page.
_PAGE_SUFFIXES = (".md", ".mdx")
def _was_produced(path: Path) -> bool:
"""Whether this run produced *path*, a page under either extension."""
if os.path.realpath(str(path)) in _produced:
return True
return path.suffix in _PAGE_SUFFIXES and any(
os.path.realpath(str(path.with_suffix(suffix))) in _produced
for suffix in _PAGE_SUFFIXES if suffix != path.suffix)
def _sweep_generated(docs: Path, directories: list[str]) -> int:
"""Delete files in the generated tree that this run did not produce."""
removed = 0
for name in directories:
root = docs / name
if not root.is_dir():
continue
for path in sorted(root.rglob("*")):
if path.is_file() and not _was_produced(path):
path.unlink()
removed += 1
for path in sorted(root.rglob("*"), reverse=True):
if path.is_dir() and not any(path.iterdir()):
path.rmdir()
return removed
def _sweep_top_pages(docs: Path) -> int:
"""Delete the pages at the root of the docs tree this run did not produce.
The root holds only generated pages, one per stem (`cross-reference-*`,
`gaps-*`), and a stem that stops being produced, such as a platform
whose core table moved to its own page, otherwise kept its old page
and claimed the address its redirect needs.
"""
removed = 0
for path in sorted(docs.glob("*.md*")):
if path.is_file() and path.suffix in _PAGE_SUFFIXES and not _was_produced(path):
path.unlink()
removed += 1
return removed