refactor: split page preparation and cards

This commit is contained in:
Abdessamad Derraz committed 2026-11-22 00:58:05 +01:00
1 parent 5e7593b3bf
commit 6559d96ac4
14 files changed
+340 -406

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ The site served these from other hosts: GitHub avatars and files on the
in silence, and every page view hit third-party hosts. This tool copies them
into ``docs_assets/logos/`` and ``docs_assets/system-icons/``, which are
committed, and records where each came from in a ``sources.json`` beside
them. The site build only reads those copies (``sitegen.diagrams.localize_images``).
them. The site build only reads those copies (``sitegen.pageprep.localize_images``).
Raster logos are normalised to an 80 px square WebP, twice the 40 px they
are shown at, and system icons to a 48 px PNG, so every tile has the same
+11 -3
View File
@@ -96,13 +96,21 @@ def _with_prose(name: str, facts: list[tuple[str, str]], body: str, key: str,
return [[cell, *prose[fact]] for fact, cell in facts]
def option_rows(body: str) -> list[list[str]]:
facts = []
# argparse's own --help last, after the options of the run.
def parser_options() -> list[tuple[list[str], str]]:
"""(flags with the long form first, metavar or "" for a switch) for each
option of install.py, in the order --help lists them, argparse's --help last."""
options = []
for action in sorted(_install.build_parser()._actions,
key=lambda action: isinstance(action, argparse._HelpAction)):
flags = sorted(action.option_strings, key=lambda flag: not flag.startswith("--"))
metavar = "" if action.nargs == 0 else (action.metavar or action.dest.upper())
options.append((flags, metavar))
return options
def option_rows(body: str) -> list[list[str]]:
facts = []
for flags, metavar in parser_options():
shown = ", ".join(f"`{flag} {metavar}`" if metavar else f"`{flag}`" for flag in flags)
facts.append((flags[0], f'<span id="option-{flags[0][2:]}"></span>{shown}'))
return _with_prose("options", facts, body, r"`(--[a-z-]+)", 1)
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Render the sharing cards (Open Graph images) to PNG, once.
Each card is an SVG written by ``sitegen.diagrams.og_card_svg`` from the
Each card is an SVG written by ``sitegen.ogcards.og_card_svg`` from the
registry, rasterised by a headless Chromium through Playwright, then
committed under ``docs_assets/og/``. The site build copies the PNG files and
never runs this script, so it adds nothing to the build's dependencies.
+1 -1
View File
@@ -18,7 +18,7 @@ GLYPH_DIM = "#4fa3c4"
TITLE = {"light": "#273c8f", "dark": "#aebcff"}
# The mark beside it: the header logo in each scheme (website/src/assets).
MARK = {"light": HEADER, "dark": "#fff"}
# The sharing cards' background (sitegen.diagrams.og_card_svg).
# The sharing cards' background (sitegen.ogcards.og_card_svg).
CARD = "#2b2e5c"
FONT = "system-ui, -apple-system, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif"
+1 -1
View File
@@ -15,7 +15,7 @@ from sitegen import markup, measurements as sitemeasurements, starlight as sites
from sitegen.config import SITE_NAME, SITE_URL, yaml
from core.paths import REPO_ROOT
from sitegen.descriptions import PAGE_DATA, page_browser_title, page_description, page_title
from sitegen.diagrams import prepare_page, unresolved_images
from sitegen.pageprep import prepare_page, unresolved_images
from sitegen.render import CARD_ANCHOR, WIKI_SRC_DIR, card_anchor
from sitegen.write import undecorated, write_decorated
-358
View File
@@ -2,11 +2,8 @@
from __future__ import annotations
import ast
import json
import re
import urllib.parse
from collections import Counter
from collections.abc import Callable
from dataclasses import dataclass, field
from functools import cache
@@ -22,9 +19,6 @@ from sitegen import markup
from orchestrate.labels import STEP_LABELS
PLACEHOLDER = re.compile(r"(?m)^([ \t]*)<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->[ \t]*$")
PLACEHOLDER_ANYWHERE = re.compile(r"<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->")
FONT = "system-ui, -apple-system, 'Segoe UI', Helvetica, Arial, sans-serif"
# The stylesheet sets the page font on every <text>, so a path takes the
# mono font from an inline style, which outranks it.
@@ -748,358 +742,6 @@ def figure_html(image_id: str, occurrence: int = 1, inline: bool = False) -> str
)
def resolve_images(markdown: str) -> str:
"""Replace each image placeholder line with its figure.
An unknown id is left in place: validate_site reports the comment in the
built page, and the test of placeholders names it.
"""
if "<!--" not in markdown:
return markdown
seen: Counter[str] = Counter()
def replace(match: re.Match[str]) -> str:
indent, image_id = match.group(1), match.group(2)
if image_id not in IMAGE_IDS:
return match.group(0)
seen[image_id] += 1
html = figure_html(image_id, seen[image_id], inline=bool(indent))
return "\n".join(indent + line for line in html.split("\n"))
resolved = PLACEHOLDER.sub(replace, markdown)
return markdown if resolved == markdown else resolved
def unresolved_images(markdown: str) -> list[str]:
return [m for m in PLACEHOLDER_ANYWHERE.findall(markdown) if m not in IMAGE_IDS]
# Local copies of images the site used to load from other hosts.
LOGO_DIR = REPO_ROOT / "docs_assets" / "logos"
ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons"
SITE_LOGO_DIR = "assets/logos"
SITE_ICON_DIR = "assets/system-icons"
IMAGE_LINK = re.compile(r"(!\[[^\]\n]*\]\()(https?://[^)\s]+)(\))")
IMG_SRC = re.compile(r'(<img\b[^>]*?\bsrc=")(https?://[^"]+)(")')
@cache
def local_images() -> dict[str, str]:
"""Remote URL -> path under the site root, from the two source manifests."""
mapping: dict[str, str] = {}
for directory, site_dir in ((LOGO_DIR, SITE_LOGO_DIR), (ICON_DIR, SITE_ICON_DIR)):
manifest = directory / "sources.json"
if not manifest.is_file():
continue
for entry in json.loads(manifest.read_text(encoding="utf-8"))["images"]:
mapping[entry["source"]] = f"{site_dir}/{entry['file']}"
return mapping
def localize_images(markdown: str, page: Path) -> str:
"""Point image links with a local copy at that copy, relative to *page*.
*page* is the page's path under the docs root. A remote image with no
local copy is left as written, and validate_site refuses it.
"""
if "http" not in markdown:
return markdown
mapping = local_images()
depth = len(page.parts) - 1
prefix = "../" * depth
def swap(match: re.Match[str]) -> str:
local = mapping.get(match.group(2))
if local is None:
return match.group(0)
return match.group(1) + prefix + urllib.parse.quote(local) + match.group(3)
return IMG_SRC.sub(swap, IMAGE_LINK.sub(swap, markdown))
# Installer commands on wiki pages. The page keeps the Linux line, readable
# where the Markdown is read as is, and the site shows it in one tab per
# system, the Windows form written by the same function as the setup pages'.
OS_TABS = re.compile(
r"(?m)^(?P<indent>[ \t]*)<!--\s*os-tabs(?P<own>(?:\s+[^\n]*?)?)\s*-->[ \t]*\n"
r"(?P=indent)```(?:sh|bash)[^\n]*\n(?P<body>.*?)\n(?P=indent)```[ \t]*$",
re.S,
)
OS_TAB_KEYS = ("windows", "macos", "linux", "steamdeck")
_OWN_ARGS = re.compile(r"(?:^|\s)(" + "|".join(OS_TAB_KEYS) + r"):\s*")
FENCE_TITLES = {"sh": "Terminal", "powershell": "PowerShell"}
def _installer_args(body: str) -> str:
"""The options of a one-line install command, continuation lines joined."""
from model.guides import INSTALL_SH
line = " ".join(part.strip().rstrip("\\").strip() for part in body.splitlines())
match = re.fullmatch(rf"curl -fsSL {re.escape(INSTALL_SH)} \| sh(?: -s -- (.+))?", line)
if not match:
raise ValueError(f"an os-tabs block holds no install command: {line!r}")
return match.group(1) or ""
def _own_args(text: str) -> dict[str, str]:
"""`windows: ARGS macos: ARGS` -> the options each named tab uses."""
parts = _OWN_ARGS.split(text.strip())
if parts[0].strip():
raise ValueError(f"an os-tabs marker names no system: {text.strip()!r}")
return {key: value.strip() for key, value in zip(parts[1::2], parts[2::2])}
def expand_commands(markdown: str) -> str:
"""Each install command marked `<!-- os-tabs -->` as Windows, macOS,
Linux and Steam Deck tabs. `<!-- os-tabs windows: ARGS macos: ARGS -->`
gives a tab its own options, for a folder that differs there."""
if "os-tabs" not in markdown:
return markdown
from model.guides import TERMINALS, install_command
def replace(match: re.Match[str]) -> str:
indent = match.group("indent")
args = _installer_args(match.group("body"))
own_args = _own_args(match.group("own"))
items = []
for key in OS_TAB_KEYS:
label, _how, shell = TERMINALS[key]
own = own_args.get(key) or args
items.append((label, [f'```{shell} title="{FENCE_TITLES[shell]}"',
install_command(shell, own), "```"]))
return "\n".join(markup.tabs(items, indent)).rstrip("\n")
return OS_TABS.sub(replace, markdown)
# The installer's options at a glance, read from its argument parser.
OPTIONS_MARKER = re.compile(r"(?m)^<!--\s*installer-options\s*-->[ \t]*$")
_SEE_LINK = re.compile(r"\(#([a-z0-9-]+)\)")
def _string(node: ast.expr, constants: dict[str, str]) -> str:
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
if isinstance(node, ast.JoinedStr):
parts = []
for value in node.values:
if isinstance(value, ast.FormattedValue) and isinstance(value.value, ast.Name):
parts.append(constants[value.value.id])
else:
parts.append(_string(value, constants))
return "".join(parts)
raise ValueError(f"install.py: an option help that is not a string: {ast.unparse(node)}")
@cache
def installer_options() -> tuple[tuple[str, str], ...]:
"""(usage, help) for each option of install.py, in the order --help lists them."""
tree = ast.parse((REPO_ROOT / "install.py").read_text(encoding="utf-8"))
constants = {
node.targets[0].id: node.value.value
for node in tree.body
if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name)
and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str)
}
builder = next(node for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name == "build_parser")
options = []
for node in ast.walk(builder):
if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and node.func.attr == "add_argument"):
continue
flags = [arg.value for arg in node.args
if isinstance(arg, ast.Constant) and isinstance(arg.value, str)]
keywords = {kw.arg: kw.value for kw in node.keywords}
action = keywords.get("action")
takes_value = not (isinstance(action, ast.Constant)
and action.value in ("store_true", "store_false", "version"))
metavar = ""
if takes_value:
given = keywords.get("metavar")
metavar = (given.value if isinstance(given, ast.Constant) and isinstance(given.value, str)
else flags[0].lstrip("-").upper())
usage = ", ".join(f"{flag} {metavar}".strip() for flag in flags)
options.append((usage, _string(keywords["help"], constants) if "help" in keywords else ""))
# argparse's own, added to every parser.
options.append(("--help, -h", "show this help message and exit"))
return tuple(options)
def _sentences(text: str) -> str:
"""A help string as sentences: capitalised, clauses split, a full stop."""
parts = [part.strip() for part in text.split("; ")]
text = ". ".join(part[0].upper() + part[1:] for part in parts if part)
text = re.sub(r"(?<![\w`])(--[a-z][a-z-]*)", r"`\1`", text)
return text.replace("|", "\\|") + ("" if text.endswith(".") else ".")
def options_table(markdown: str) -> list[str]:
"""One row per option: what it does, and the section that says more,
the one the option's row in the page's own Options table sends to."""
sections: dict[str, str] = {}
for line in markdown.splitlines():
flag = re.match(r"\| `(--[a-z-]+)", line)
see = _SEE_LINK.search(line)
if flag and see:
sections[flag.group(1)] = see.group(1)
headings = {
re.sub(r"[^a-z0-9 -]", "", title.lower()).strip().replace(" ", "-"): title
for title in re.findall(r"(?m)^##+ (.+?)(?:\s*\{[^}]*\})?\s*$", markdown)
}
rows = ["| Option | What it does | More |", "|---|---|---|"]
for usage, help_text in installer_options():
anchor = sections.get(usage.split()[0].rstrip(","))
more = f"[{headings.get(anchor, anchor)}](#{anchor})" if anchor else ""
rows.append(f"| `{usage}` | {_sentences(help_text)} | {more} |")
return rows
# The installer page's glance groups its options by task. The list is
# written from the parser when the page is built: an option the parser
# gains and no group names lands under "Other", never off the page.
GLANCE_HEADING = "## Options at a glance"
GLANCE_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
("Where and for what", ("--platform", "--dest", "--target", "--every-board", "--save-dir",
"--romm-firmware", "--standalone-copies", "--add-app")),
("Fewer files", ("--for-games", "--required-only", "--all-files", "--system", "--core", "--emulator",
"--standalone", "--region", "--one-per-slot", "--no-game-data",
"--declared-only", "--source", "--find", "--installed-cores",
"--cores-dir")),
("Look first", ("--check", "--dry-run", "--list-platforms", "--list-targets",
"--list-systems", "--list-cores", "--list-emulators")),
("From files on hand", ("--from", "--from-pack", "--manifest", "--offline")),
("Make a pack", ("--pack", "--split")),
("Remove and put back", ("--remove", "--file", "--misplaced", "--backup", "--backups",
"--restore", "--delete-backup")),
("How the run talks", ("--tui", "--plain", "--no-input", "--yes", "--quiet", "--verbose",
"--events", "--json", "--jobs", "--version", "--help")),
)
GLANCE_OTHER = "Other"
def installer_flags() -> list[str]:
"""Each option's first flag, in the order --help lists them."""
return [usage.split()[0].rstrip(",") for usage, _help in installer_options()]
def options_glance() -> list[str]:
"""One line per group of the glance, each option a link to its row."""
flags = installer_flags()
groups = [(label, [flag for flag in members if flag in flags]) for label, members in GLANCE_GROUPS]
named = {flag for _label, members in GLANCE_GROUPS for flag in members}
groups.append((GLANCE_OTHER, [flag for flag in flags if flag not in named]))
return [
f"- **{label}**: " + ", ".join(f"[`{flag}`](#option-{flag.lstrip('-')})" for flag in members)
for label, members in groups if members
]
def expand_glance(markdown: str) -> str:
"""The glance's list, after the sentence that opens the section."""
start = markdown.find(f"\n{GLANCE_HEADING}\n")
if start == -1:
return markdown
body_start = start + len(GLANCE_HEADING) + 2
end = markdown.find("\n## ", body_start)
end = len(markdown) if end == -1 else end
body = markdown[body_start:end].strip("\n")
if any(line.startswith("- ") for line in body.splitlines()):
raise ValueError(f"{GLANCE_HEADING}: the list is written from install.py's parser, "
"not by hand")
return (markdown[:body_start] + "\n" + body + "\n\n" + "\n".join(options_glance())
+ "\n" + markdown[end:])
def expand_options(markdown: str) -> str:
if "installer-options" not in markdown:
return markdown
return OPTIONS_MARKER.sub(lambda _m: "\n".join(options_table(markdown)), markdown)
# Example hashes in the documentation stay out of search, so a hash typed in
# the search box finds the file card that holds it, not a page quoting it.
HASH_SPAN = re.compile(r"`[^`\n]*\b(?:[0-9a-f]{64}|[0-9a-f]{40}|[0-9a-f]{32})\b[^`\n]*`")
HASH_TEXT = re.compile(r"\b(?:[0-9a-f]{64}|[0-9a-f]{40}|[0-9a-f]{32})\b")
FENCE = re.compile(r"(?m)^(?P<indent>[ \t]*)(?P<mark>```|~~~)[^\n]*\n.*?\n(?P=indent)(?P=mark)[ \t]*$", re.S)
def hide_hashes(markdown: str) -> str:
"""Wrap each code block and code span quoting a hash in a search exclusion."""
if not HASH_TEXT.search(markdown):
return markdown
attribute = markup.search_exclude()
pieces: list[str] = []
position = 0
for match in FENCE.finditer(markdown):
pieces.append(HASH_SPAN.sub(lambda m: f"<span {attribute}>{m.group(0)}</span>",
markdown[position:match.start()]))
block = match.group(0)
if HASH_TEXT.search(block):
indent = match.group("indent")
block = f"{indent}<div {attribute}>\n\n{block}\n\n{indent}</div>"
pieces.append(block)
position = match.end()
pieces.append(HASH_SPAN.sub(lambda m: f"<span {attribute}>{m.group(0)}</span>",
markdown[position:]))
return "".join(pieces)
# The markers scripts/generate_installer_doc.py writes its tables between:
# for the source only, the page shows the table alone.
GENERATED_MARKER = re.compile(r"(?m)^<!-- /?generated: [a-z-]+ -->\n\n?")
def prepare_page(markdown: str, page: Path) -> str:
"""Everything this module does to a page before it is decorated."""
markdown = expand_glance(expand_options(expand_commands(resolve_images(localize_images(markdown, page)))))
markdown = GENERATED_MARKER.sub("", markdown)
if page.parts[:1] == ("wiki",):
markdown = hide_hashes(markdown)
return markdown
# Sharing cards: one 1200x630 card per section of the site, rendered to PNG
# once by scripts/make_og_cards.py and committed under docs_assets/og/.
OG_SECTIONS: dict[str, tuple[str, str]] = {
"home": ("BIOS and firmware packs", "Checked file by file, for {frontends}"),
"start": ("Start here", "What BIOS files are, and how to install them with one command"),
"setup": ("Setups", "Where the files go on each device and frontend"),
"explore": ("Systems and emulators", "Which files each console and emulator reads"),
"reference": ("Reference", "Verification modes, gaps, provenance and the data API"),
"contribute": ("Contribute", "Adding files, emulator profiles and platforms"),
}
def og_card_svg(section: str, mark_svg: str) -> str:
"""A sharing card. ``mark_svg`` is the site's white mark
(docs_assets/brand/logo.svg), drawn as the header draws it."""
title, tagline = OG_SECTIONS[section]
tagline = tagline.format(frontends=setups_named(["RetroArch", "Batocera", "EmuDeck"]))
mark = mark_svg.strip().replace("<svg ", '<svg x="96" y="88" width="112" height="112" ', 1)
body = [
'<rect width="1200" height="630" fill="#2b2e5c"/>',
'<rect x="0" y="606" width="1200" height="24" fill="#3b3f7a"/>',
mark,
'<text x="236" y="164" font-size="48" font-weight="700" fill="#ffffff">RetroBIOS</text>',
f'<text x="96" y="330" font-size="72" font-weight="700" fill="#ffffff">{escape(title)}</text>',
]
for index, line in enumerate(wrap(tagline, 1000, 34)):
body.append(
f'<text x="96" y="{400 + index * 46}" font-size="34" fill="#d4d6ee">{escape(line)}</text>'
)
body.append('<text x="96" y="556" font-size="28" fill="#aebcff">abdess.github.io/retrobios</text>')
return (
'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" '
f'font-family="{FONT}">' + "".join(body) + "</svg>"
)
def write_svgs(directory: Path) -> list[Path]:
"""Each diagram's wide layout as a file, for reading outside the site."""
directory.mkdir(parents=True, exist_ok=True)
+39 -1
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from xml.sax.saxutils import escape
from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT
from core.text import series
@@ -13,7 +14,7 @@ from model.composition import GAME_DATA_TOPS
from model.database import load_database
from model.platforms import load_platform_config
from model.registry import list_registered_platforms
from sitegen.diagrams import OG_SECTIONS, og_card_svg, wrap
from sitegen.diagrams import FONT, setups_named, wrap
OUT = REPO_ROOT / "docs_assets" / "og"
LOGO = REPO_ROOT / "docs_assets" / "brand" / "logo.svg"
@@ -23,6 +24,43 @@ PLATFORM_TAGLINE = "Which BIOS files it needs, and where each one goes"
TAGLINE_WIDTH, TAGLINE_SIZE, TAGLINE_LINES = 1000, 34, 3
# Sharing cards: one 1200x630 card per section of the site, rendered to PNG
# once by scripts/make_og_cards.py and committed under docs_assets/og/.
OG_SECTIONS: dict[str, tuple[str, str]] = {
"home": ("BIOS and firmware packs", "Checked file by file, for {frontends}"),
"start": ("Start here", "What BIOS files are, and how to install them with one command"),
"setup": ("Setups", "Where the files go on each device and frontend"),
"explore": ("Systems and emulators", "Which files each console and emulator reads"),
"reference": ("Reference", "Verification modes, gaps, provenance and the data API"),
"contribute": ("Contribute", "Adding files, emulator profiles and platforms"),
}
def og_card_svg(section: str, mark_svg: str) -> str:
"""A sharing card. ``mark_svg`` is the site's white mark
(docs_assets/brand/logo.svg), drawn as the header draws it."""
title, tagline = OG_SECTIONS[section]
tagline = tagline.format(frontends=setups_named(["RetroArch", "Batocera", "EmuDeck"]))
mark = mark_svg.strip().replace("<svg ", '<svg x="96" y="88" width="112" height="112" ', 1)
body = [
'<rect width="1200" height="630" fill="#2b2e5c"/>',
'<rect x="0" y="606" width="1200" height="24" fill="#3b3f7a"/>',
mark,
'<text x="236" y="164" font-size="48" font-weight="700" fill="#ffffff">RetroBIOS</text>',
f'<text x="96" y="330" font-size="72" font-weight="700" fill="#ffffff">{escape(title)}</text>',
]
for index, line in enumerate(wrap(tagline, TAGLINE_WIDTH, TAGLINE_SIZE)):
body.append(
f'<text x="96" y="{400 + index * 46}" font-size="34" fill="#d4d6ee">{escape(line)}</text>'
)
body.append('<text x="96" y="556" font-size="28" fill="#aebcff">abdess.github.io/retrobios</text>')
return (
'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" '
f'font-family="{FONT}">' + "".join(body) + "</svg>"
)
def platform_cards() -> dict[str, tuple[str, str]]:
"""Each platform page's card, by its path under og/, with its title."""
platforms = REPO_ROOT / PLATFORMS_DIR
+247
View File
@@ -0,0 +1,247 @@
"""Wiki pages made ready for the site: figures, local images, install tabs, options glance, hidden hashes."""
from __future__ import annotations
import json
import re
import urllib.parse
from collections import Counter
from functools import cache
from pathlib import Path
from core.paths import REPO_ROOT
from sitegen import markup
from sitegen.diagrams import IMAGE_IDS, figure_html
PLACEHOLDER = re.compile(r"(?m)^([ \t]*)<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->[ \t]*$")
PLACEHOLDER_ANYWHERE = re.compile(r"<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->")
def resolve_images(markdown: str) -> str:
"""Replace each image placeholder line with its figure.
An unknown id is left in place: validate_site reports the comment in the
built page, and the test of placeholders names it.
"""
if "<!--" not in markdown:
return markdown
seen: Counter[str] = Counter()
def replace(match: re.Match[str]) -> str:
indent, image_id = match.group(1), match.group(2)
if image_id not in IMAGE_IDS:
return match.group(0)
seen[image_id] += 1
html = figure_html(image_id, seen[image_id], inline=bool(indent))
return "\n".join(indent + line for line in html.split("\n"))
resolved = PLACEHOLDER.sub(replace, markdown)
return markdown if resolved == markdown else resolved
def unresolved_images(markdown: str) -> list[str]:
return [m for m in PLACEHOLDER_ANYWHERE.findall(markdown) if m not in IMAGE_IDS]
# Local copies of images the site used to load from other hosts.
LOGO_DIR = REPO_ROOT / "docs_assets" / "logos"
ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons"
SITE_LOGO_DIR = "assets/logos"
SITE_ICON_DIR = "assets/system-icons"
IMAGE_LINK = re.compile(r"(!\[[^\]\n]*\]\()(https?://[^)\s]+)(\))")
IMG_SRC = re.compile(r'(<img\b[^>]*?\bsrc=")(https?://[^"]+)(")')
@cache
def local_images() -> dict[str, str]:
"""Remote URL -> path under the site root, from the two source manifests."""
mapping: dict[str, str] = {}
for directory, site_dir in ((LOGO_DIR, SITE_LOGO_DIR), (ICON_DIR, SITE_ICON_DIR)):
manifest = directory / "sources.json"
if not manifest.is_file():
continue
for entry in json.loads(manifest.read_text(encoding="utf-8"))["images"]:
mapping[entry["source"]] = f"{site_dir}/{entry['file']}"
return mapping
def localize_images(markdown: str, page: Path) -> str:
"""Point image links with a local copy at that copy, relative to *page*.
*page* is the page's path under the docs root. A remote image with no
local copy is left as written, and validate_site refuses it.
"""
if "http" not in markdown:
return markdown
mapping = local_images()
depth = len(page.parts) - 1
prefix = "../" * depth
def swap(match: re.Match[str]) -> str:
local = mapping.get(match.group(2))
if local is None:
return match.group(0)
return match.group(1) + prefix + urllib.parse.quote(local) + match.group(3)
return IMG_SRC.sub(swap, IMAGE_LINK.sub(swap, markdown))
# Installer commands on wiki pages. The page keeps the Linux line, readable
# where the Markdown is read as is, and the site shows it in one tab per
# system, the Windows form written by the same function as the setup pages'.
OS_TABS = re.compile(
r"(?m)^(?P<indent>[ \t]*)<!--\s*os-tabs(?P<own>(?:\s+[^\n]*?)?)\s*-->[ \t]*\n"
r"(?P=indent)```(?:sh|bash)[^\n]*\n(?P<body>.*?)\n(?P=indent)```[ \t]*$",
re.S,
)
OS_TAB_KEYS = ("windows", "macos", "linux", "steamdeck")
_OWN_ARGS = re.compile(r"(?:^|\s)(" + "|".join(OS_TAB_KEYS) + r"):\s*")
FENCE_TITLES = {"sh": "Terminal", "powershell": "PowerShell"}
def _installer_args(body: str) -> str:
"""The options of a one-line install command, continuation lines joined."""
from model.guides import INSTALL_SH
line = " ".join(part.strip().rstrip("\\").strip() for part in body.splitlines())
match = re.fullmatch(rf"curl -fsSL {re.escape(INSTALL_SH)} \| sh(?: -s -- (.+))?", line)
if not match:
raise ValueError(f"an os-tabs block holds no install command: {line!r}")
return match.group(1) or ""
def _own_args(text: str) -> dict[str, str]:
"""`windows: ARGS macos: ARGS` -> the options each named tab uses."""
parts = _OWN_ARGS.split(text.strip())
if parts[0].strip():
raise ValueError(f"an os-tabs marker names no system: {text.strip()!r}")
return {key: value.strip() for key, value in zip(parts[1::2], parts[2::2])}
def expand_commands(markdown: str) -> str:
"""Each install command marked `<!-- os-tabs -->` as Windows, macOS,
Linux and Steam Deck tabs. `<!-- os-tabs windows: ARGS macos: ARGS -->`
gives a tab its own options, for a folder that differs there."""
if "os-tabs" not in markdown:
return markdown
from model.guides import TERMINALS, install_command
def replace(match: re.Match[str]) -> str:
indent = match.group("indent")
args = _installer_args(match.group("body"))
own_args = _own_args(match.group("own"))
items = []
for key in OS_TAB_KEYS:
label, _how, shell = TERMINALS[key]
own = own_args.get(key) or args
items.append((label, [f'```{shell} title="{FENCE_TITLES[shell]}"',
install_command(shell, own), "```"]))
return "\n".join(markup.tabs(items, indent)).rstrip("\n")
return OS_TABS.sub(replace, markdown)
# The installer page's glance groups its options by task. The list is
# written from the parser when the page is built: an option the parser
# gains and no group names lands under "Other", never off the page.
GLANCE_HEADING = "## Options at a glance"
GLANCE_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = (
("Where and for what", ("--platform", "--dest", "--target", "--every-board", "--save-dir",
"--romm-firmware", "--standalone-copies", "--add-app")),
("Fewer files", ("--for-games", "--required-only", "--all-files", "--system", "--core", "--emulator",
"--standalone", "--region", "--one-per-slot", "--no-game-data",
"--declared-only", "--source", "--find", "--installed-cores",
"--cores-dir")),
("Look first", ("--check", "--dry-run", "--list-platforms", "--list-targets",
"--list-systems", "--list-cores", "--list-emulators")),
("From files on hand", ("--from", "--from-pack", "--manifest", "--offline")),
("Make a pack", ("--pack", "--split")),
("Remove and put back", ("--remove", "--file", "--misplaced", "--backup", "--backups",
"--restore", "--delete-backup")),
("How the run talks", ("--tui", "--plain", "--no-input", "--yes", "--quiet", "--verbose",
"--events", "--json", "--jobs", "--version", "--help")),
)
GLANCE_OTHER = "Other"
def installer_flags() -> list[str]:
"""Each option's first flag, in the order --help lists them."""
from installer_build.installerdoc import parser_options
return [flags[0] for flags, _metavar in parser_options()]
def options_glance() -> list[str]:
"""One line per group of the glance, each option a link to its row."""
flags = installer_flags()
groups = [(label, [flag for flag in members if flag in flags]) for label, members in GLANCE_GROUPS]
named = {flag for _label, members in GLANCE_GROUPS for flag in members}
groups.append((GLANCE_OTHER, [flag for flag in flags if flag not in named]))
return [
f"- **{label}**: " + ", ".join(f"[`{flag}`](#option-{flag.lstrip('-')})" for flag in members)
for label, members in groups if members
]
def expand_glance(markdown: str) -> str:
"""The glance's list, after the sentence that opens the section."""
start = markdown.find(f"\n{GLANCE_HEADING}\n")
if start == -1:
return markdown
body_start = start + len(GLANCE_HEADING) + 2
end = markdown.find("\n## ", body_start)
end = len(markdown) if end == -1 else end
body = markdown[body_start:end].strip("\n")
if any(line.startswith("- ") for line in body.splitlines()):
raise ValueError(f"{GLANCE_HEADING}: the list is written from install.py's parser, "
"not by hand")
return (markdown[:body_start] + "\n" + body + "\n\n" + "\n".join(options_glance())
+ "\n" + markdown[end:])
# Example hashes in the documentation stay out of search, so a hash typed in
# the search box finds the file card that holds it, not a page quoting it.
HASH_SPAN = re.compile(r"`[^`\n]*\b(?:[0-9a-f]{64}|[0-9a-f]{40}|[0-9a-f]{32})\b[^`\n]*`")
HASH_TEXT = re.compile(r"\b(?:[0-9a-f]{64}|[0-9a-f]{40}|[0-9a-f]{32})\b")
FENCE = re.compile(r"(?m)^(?P<indent>[ \t]*)(?P<mark>```|~~~)[^\n]*\n.*?\n(?P=indent)(?P=mark)[ \t]*$", re.S)
def hide_hashes(markdown: str) -> str:
"""Wrap each code block and code span quoting a hash in a search exclusion."""
if not HASH_TEXT.search(markdown):
return markdown
attribute = markup.search_exclude()
pieces: list[str] = []
position = 0
for match in FENCE.finditer(markdown):
pieces.append(HASH_SPAN.sub(lambda m: f"<span {attribute}>{m.group(0)}</span>",
markdown[position:match.start()]))
block = match.group(0)
if HASH_TEXT.search(block):
indent = match.group("indent")
block = f"{indent}<div {attribute}>\n\n{block}\n\n{indent}</div>"
pieces.append(block)
position = match.end()
pieces.append(HASH_SPAN.sub(lambda m: f"<span {attribute}>{m.group(0)}</span>",
markdown[position:]))
return "".join(pieces)
# The markers scripts/generate_installer_doc.py writes its tables between:
# for the source only, the page shows the table alone.
GENERATED_MARKER = re.compile(r"(?m)^<!-- /?generated: [a-z-]+ -->\n\n?")
def prepare_page(markdown: str, page: Path) -> str:
"""Everything this module does to a page before it is decorated."""
markdown = expand_glance(expand_commands(resolve_images(localize_images(markdown, page))))
markdown = GENERATED_MARKER.sub("", markdown)
if page.parts[:1] == ("wiki",):
markdown = hide_hashes(markdown)
return markdown
+1 -1
View File
@@ -11,7 +11,7 @@ from resolve.nativemode import check_label, reads_file_contents
from sitegen import markup
from sitegen.config import REPO_URL, date_line
from sitegen.decorate import level_label
from sitegen.diagrams import local_images
from sitegen.pageprep import local_images
from sitegen.guidepage import pack_buttons, platform_guide
from sitegen.home import stat_block
from sitegen.install import platform_install_block
+1 -1
View File
@@ -109,7 +109,7 @@ def prime_system_icons(names: set[str]) -> None:
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: ``sitegen.diagrams.localize_images``
The link names the upstream file: ``sitegen.pageprep.localize_images``
points it at the local copy, whose source is recorded beside it.
"""
name = console_icon_name(manufacturer, console_name)
+3 -2
View File
@@ -70,8 +70,9 @@ COMMANDS = {
"sitegen/versions.py", "sitegen/guidepage.py", "sitegen/install.py", "sitegen/getpages.py",
"sitegen/dataexports.py", "sitegen/lookup.py", "sitegen/apiitems.py", "sitegen/publish.py",
"sitegen/datapage.py", "sitegen/descriptions.py", "sitegen/structured.py",
"sitegen/cards.py", "sitegen/decorate.py", "sitegen/platformindex.py", "sitegen/parts.py",
"sitegen/platformfiles.py", "sitegen/platformpage.py", "sitegen/systemsindex.py",
"sitegen/cards.py", "sitegen/decorate.py", "sitegen/pageprep.py", "sitegen/platformindex.py",
"sitegen/parts.py", "sitegen/platformfiles.py", "sitegen/platformpage.py",
"sitegen/systemsindex.py",
"sitegen/provenance.py", "sitegen/fields.py", "sitegen/consolecards.py",
"sitegen/startwith.py", "sitegen/systempages.py", "sitegen/emulatorcards.py",
"sitegen/emulatorpage.py", "sitegen/gaps.py", "sitegen/crossref.py", "sitegen/reference.py",
+12 -12
View File
@@ -17,7 +17,7 @@ import unittest
import xml.etree.ElementTree as ET
from pathlib import Path
from sitegen import diagrams
from sitegen import diagrams, ogcards, pageprep
ROOT = Path(__file__).resolve().parent.parent
@@ -54,7 +54,7 @@ class EveryDiagramIsAccessibleSvg(unittest.TestCase):
self.assertNotIn("; ", re.sub(r"<[^>]+>", " ", html))
def test_a_second_copy_on_one_page_gets_its_own_ids(self):
page = diagrams.resolve_images(
page = pageprep.resolve_images(
"<!-- image: install-flow -->\n\ntext\n\n<!-- image: install-flow -->\n"
)
ids = re.findall(r'\bid="([^"]+)"', page)
@@ -70,19 +70,19 @@ class PlaceholdersResolve(unittest.TestCase):
found = 0
for path in sources:
text = path.read_text(encoding="utf-8")
for image_id in diagrams.PLACEHOLDER_ANYWHERE.findall(text):
for image_id in pageprep.PLACEHOLDER_ANYWHERE.findall(text):
found += 1
with self.subTest(page=path.name, image=image_id):
self.assertIn(image_id, diagrams.IMAGE_IDS)
self.assertGreater(found, 0)
def test_a_block_placeholder_becomes_a_figure(self):
page = diagrams.resolve_images("Intro\n\n<!-- image: bios-chain -->\n\nMore\n")
page = pageprep.resolve_images("Intro\n\n<!-- image: bios-chain -->\n\nMore\n")
self.assertIn('<figure class="rb-figure"', page)
self.assertNotIn("<!-- image:", page)
def test_an_indented_placeholder_keeps_its_indent_and_escapes_markdown(self):
page = diagrams.resolve_images("1. Step\n\n <!-- image: data-layers -->\n")
page = pageprep.resolve_images("1. Step\n\n <!-- image: data-layers -->\n")
line = page.splitlines()[2]
self.assertTrue(line.startswith(" <span class=\"rb-figure"))
self.assertNotIn("_shared", line)
@@ -90,8 +90,8 @@ class PlaceholdersResolve(unittest.TestCase):
def test_an_unknown_name_is_left_for_the_validator(self):
page = "<!-- image: no-such-diagram -->\n"
self.assertEqual(diagrams.resolve_images(page), page)
self.assertEqual(diagrams.unresolved_images(page), ["no-such-diagram"])
self.assertEqual(pageprep.resolve_images(page), page)
self.assertEqual(pageprep.unresolved_images(page), ["no-such-diagram"])
class DiagramsMatchTheData(unittest.TestCase):
@@ -166,13 +166,13 @@ class ImagesAreServedFromTheSite(unittest.TestCase):
def test_remote_links_with_a_copy_are_rewritten(self):
logo = self._manifest("logos")[0]
page = f"| ![X]({logo['source']}){{ width=20 }} | <img src=\"{logo['source']}\"> |"
local = diagrams.localize_images(page, Path("platforms/x.md"))
local = pageprep.localize_images(page, Path("platforms/x.md"))
self.assertNotIn(logo["source"], local)
self.assertEqual(local.count(f"../assets/logos/{logo['file']}"), 2)
def test_icon_paths_are_link_safe(self):
icon = self._manifest("system-icons")[0]
local = diagrams.localize_images(f"![a]({icon['source']})", Path("systems/x.md"))
local = pageprep.localize_images(f"![a]({icon['source']})", Path("systems/x.md"))
self.assertNotIn(" ", local)
def test_the_validator_refuses_a_remote_image(self):
@@ -193,13 +193,13 @@ class SharingCards(unittest.TestCase):
def test_one_card_per_section_at_the_open_graph_size(self):
import struct
for section in diagrams.OG_SECTIONS:
for section in ogcards.OG_SECTIONS:
with self.subTest(section=section):
data = (ROOT / "docs_assets" / "og" / f"{section}.png").read_bytes()
self.assertEqual(data[:8], b"\x89PNG\r\n\x1a\n")
self.assertEqual(struct.unpack(">II", data[16:24]), (1200, 630))
mark = (ROOT / "docs_assets" / "brand" / "logo.svg").read_text(encoding="utf-8")
ET.fromstring(diagrams.og_card_svg(section, mark))
ET.fromstring(ogcards.og_card_svg(section, mark))
def test_the_template_names_every_section(self):
from sitegen import starlight as sitestarlight
@@ -207,7 +207,7 @@ class SharingCards(unittest.TestCase):
named = {sitestarlight.og_section("index.md", "")} | {
sitestarlight.og_section("wiki/page.md", level)
for level in ("start", "setup", "explore", "reference", "contribute")}
self.assertEqual(named, set(diagrams.OG_SECTIONS))
self.assertEqual(named, set(ogcards.OG_SECTIONS))
for section in named:
with self.subTest(section=section):
self.assertTrue((ROOT / "docs_assets" / "og" / f"{section}.png").is_file())
+8 -8
View File
@@ -27,7 +27,7 @@ from freshness.profiles import check_source_paths
from sitegen import emulatorcards
from sitegen import emulatorpage
from sitegen import startwith
from sitegen import diagrams
from sitegen import pageprep
from model import collection
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -187,14 +187,14 @@ class OptionsGlanceFromTheParser(unittest.TestCase):
table, and not the hand-written glance above it."""
def test_every_parser_option_has_a_group(self):
named = {flag for _label, flags in diagrams.GLANCE_GROUPS for flag in flags}
self.assertEqual(set(diagrams.installer_flags()) - named, set())
self.assertEqual(named - set(diagrams.installer_flags()), set())
named = {flag for _label, flags in pageprep.GLANCE_GROUPS for flag in flags}
self.assertEqual(set(pageprep.installer_flags()) - named, set())
self.assertEqual(named - set(pageprep.installer_flags()), set())
def test_an_option_no_group_names_still_lands(self):
with mock.patch.object(diagrams, "installer_flags",
with mock.patch.object(pageprep, "installer_flags",
return_value=["--platform", "--brand-new"]):
lines = diagrams.options_glance()
lines = pageprep.options_glance()
self.assertEqual(lines, [
"- **Where and for what**: [`--platform`](#option-platform)",
"- **Other**: [`--brand-new`](#option-brand-new)",
@@ -202,10 +202,10 @@ class OptionsGlanceFromTheParser(unittest.TestCase):
def test_the_source_holds_no_list(self):
text = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8")
section = text[text.index(diagrams.GLANCE_HEADING):text.index("\n## One line")]
section = text[text.index(pageprep.GLANCE_HEADING):text.index("\n## One line")]
self.assertNotIn("\n- ", section)
with self.assertRaises(ValueError):
diagrams.expand_glance(f"# x\n\n{diagrams.GLANCE_HEADING}\n\n- a\n\n## y\n")
pageprep.expand_glance(f"# x\n\n{pageprep.GLANCE_HEADING}\n\n- a\n\n## y\n")
class FaqInstallsFromWhatYouHold(unittest.TestCase):
+14 -16
View File
@@ -45,7 +45,7 @@ import unittest
from pathlib import Path
import yaml
from sitegen import diagrams
from sitegen import diagrams, ogcards, pageprep
from model.guides import INSTALL_SH
from tests import sitepages
from installer_build import port
@@ -135,7 +135,7 @@ class InstallCommandsHaveEveryForm(unittest.TestCase):
"<!-- os-tabs windows: --platform retroarch --dest E:\\x -->\n```sh\n"
f"curl -fsSL {INSTALL_SH} \\\n | sh -s -- --platform retroarch --dest /a/b\n```\n"
)
text = diagrams.expand_commands(page)
text = pageprep.expand_commands(page)
windows, rest = text.split('<TabItem label="macOS">', 1)
self.assertIn("--dest E:\\x", windows)
self.assertNotIn("/a/b", windows)
@@ -143,7 +143,7 @@ class InstallCommandsHaveEveryForm(unittest.TestCase):
def test_a_marked_block_without_an_install_command_fails_the_build(self):
with self.assertRaises(ValueError):
diagrams.expand_commands("<!-- os-tabs -->\n```sh\nls -l\n```\n")
pageprep.expand_commands("<!-- os-tabs -->\n```sh\nls -l\n```\n")
class FirstInstallEnds(unittest.TestCase):
@@ -259,7 +259,7 @@ class SetupCount(unittest.TestCase):
text = path.read_text(encoding="utf-8")
found.update(int(n) for n in re.findall(r"(?:RetroArch|EmuDeck|Batocera) and (\d+) more", text))
found.update(int(n) for n in re.findall(
r"and (\d+) more", diagrams.og_card_svg("home", "<svg></svg>")))
r"and (\d+) more", ogcards.og_card_svg("home", "<svg></svg>")))
self.assertTrue(found)
self.assertEqual(found, {len(diagrams.setups()) - 3})
@@ -382,13 +382,13 @@ class ExampleHashesStayOutOfSearch(unittest.TestCase):
self.assertIn("data-pagefind-ignore", context)
def test_a_fenced_hash_is_wrapped(self):
out = diagrams.hide_hashes("```sh\nx 490f666e1afb15b7362b406ed1cea246\n```\n")
out = pageprep.hide_hashes("```sh\nx 490f666e1afb15b7362b406ed1cea246\n```\n")
self.assertTrue(out.startswith("<div data-pagefind-ignore>\n\n```sh"))
def test_only_wiki_pages_are_touched(self):
page = "Hash `490f666e1afb15b7362b406ed1cea246`.\n"
self.assertEqual(diagrams.prepare_page(page, Path("systems/sony.md")), page)
self.assertIn("data-pagefind-ignore", diagrams.prepare_page(page, Path("wiki/x.md")))
self.assertEqual(pageprep.prepare_page(page, Path("systems/sony.md")), page)
self.assertIn("data-pagefind-ignore", pageprep.prepare_page(page, Path("wiki/x.md")))
class InstallerOptionsAtAGlance(unittest.TestCase):
@@ -398,7 +398,7 @@ class InstallerOptionsAtAGlance(unittest.TestCase):
def test_every_option_of_the_parser_has_a_row(self):
source = (REPO_ROOT / "install.py").read_text(encoding="utf-8")
declared = set(re.findall(r'parser\.add_argument\(\s*"(--[a-z-]+)"', source))
listed = {usage.split()[0].rstrip(",") for usage, _ in diagrams.installer_options()}
listed = set(pageprep.installer_flags())
self.assertEqual(declared | {"--help"}, listed)
def test_the_built_page_opens_on_a_link_per_option(self):
@@ -406,8 +406,7 @@ class InstallerOptionsAtAGlance(unittest.TestCase):
glance = text.index("## Options at a glance")
self.assertLess(glance, text.index("## One line"))
listed = text[glance:text.index("## One line")]
for usage, _ in diagrams.installer_options():
flag = usage.split()[0].rstrip(",")
for flag in pageprep.installer_flags():
with self.subTest(option=flag):
self.assertIn(f"[`{flag}`](#option-{flag.lstrip('-')})", listed)
self.assertNotIn("<!-- installer-options", text)
@@ -967,12 +966,11 @@ class OneOptionsTable(unittest.TestCase):
def test_each_option_links_to_its_row(self):
# The glance is written from the parser when the page is built.
glance = _section(diagrams.expand_glance(self.text), "Options at a glance")
glance = _section(pageprep.expand_glance(self.text), "Options at a glance")
table = _section(self.text, "Options")
self.assertNotIn("installer-options", glance)
self.assertNotIn("|", glance)
for usage, _ in diagrams.installer_options():
flag = usage.split()[0].rstrip(",")
for flag in pageprep.installer_flags():
anchor = f"option-{flag.lstrip('-')}"
with self.subTest(option=flag):
self.assertIn(f"[`{flag}`](#{anchor})", glance)
@@ -1030,7 +1028,7 @@ class NoSetupFoundGivesEachSystemItsFolder(unittest.TestCase):
self.assertEqual(folders["Linux"], f"`{expected['Linux']}/`")
self.assertEqual(folders["Steam Deck and Linux Flatpak"], f"`{expected['Steam Deck']}/`")
tabs = diagrams.expand_commands(self.section)
tabs = pageprep.expand_commands(self.section)
parts = re.split(r'<TabItem label="([^"]+)">', tabs)
bodies = dict(zip(parts[1::2], parts[2::2]))
self.assertEqual(set(bodies), set(expected))
@@ -1059,7 +1057,7 @@ class OsTabsTakeOptionsPerSystem(unittest.TestCase):
f"```sh\ncurl -fsSL {INSTALL_SH} | sh -s -- --dest /l\n```\n")
def test_each_named_tab_uses_its_own(self):
parts = re.split(r'<TabItem label="([^"]+)">', diagrams.expand_commands(self.PAGE))
parts = re.split(r'<TabItem label="([^"]+)">', pageprep.expand_commands(self.PAGE))
bodies = dict(zip(parts[1::2], parts[2::2]))
self.assertIn("--dest E:\\x\n", bodies["Windows"])
self.assertIn("--dest /m\n", bodies["macOS"])
@@ -1069,7 +1067,7 @@ class OsTabsTakeOptionsPerSystem(unittest.TestCase):
def test_text_before_a_system_name_fails_the_build(self):
page = self.PAGE.replace("os-tabs windows:", "os-tabs typo windows:")
with self.assertRaises(ValueError):
diagrams.expand_commands(page)
pageprep.expand_commands(page)
class MostEmulatorsNotEvery(unittest.TestCase):