From 6559d96ac48180c047f9fef9013bd1a50668f15f Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:47:05 +0100 Subject: [PATCH] refactor: split page preparation and cards --- scripts/fetch_site_images.py | 2 +- scripts/installer_build/installerdoc.py | 14 +- scripts/make_og_cards.py | 2 +- scripts/sitegen/brand.py | 2 +- scripts/sitegen/decorate.py | 2 +- scripts/sitegen/diagrams.py | 358 ------------------------ scripts/sitegen/ogcards.py | 40 ++- scripts/sitegen/pageprep.py | 247 ++++++++++++++++ scripts/sitegen/platformpage.py | 2 +- scripts/sitegen/render.py | 2 +- tests/sources.py | 5 +- tests/test_site_images.py | 24 +- tests/test_site_integration.py | 16 +- tests/test_site_wiki.py | 30 +- 14 files changed, 340 insertions(+), 406 deletions(-) create mode 100644 scripts/sitegen/pageprep.py diff --git a/scripts/fetch_site_images.py b/scripts/fetch_site_images.py index 73e481b9c..bbc6943b5 100644 --- a/scripts/fetch_site_images.py +++ b/scripts/fetch_site_images.py @@ -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 diff --git a/scripts/installer_build/installerdoc.py b/scripts/installer_build/installerdoc.py index c41de3f4f..b61910dd6 100644 --- a/scripts/installer_build/installerdoc.py +++ b/scripts/installer_build/installerdoc.py @@ -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'{shown}')) return _with_prose("options", facts, body, r"`(--[a-z-]+)", 1) diff --git a/scripts/make_og_cards.py b/scripts/make_og_cards.py index 854dd68dc..f3140f23f 100644 --- a/scripts/make_og_cards.py +++ b/scripts/make_og_cards.py @@ -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. diff --git a/scripts/sitegen/brand.py b/scripts/sitegen/brand.py index 42aadf579..8120b9703 100644 --- a/scripts/sitegen/brand.py +++ b/scripts/sitegen/brand.py @@ -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" diff --git a/scripts/sitegen/decorate.py b/scripts/sitegen/decorate.py index c1551feda..bcd09a2e0 100644 --- a/scripts/sitegen/decorate.py +++ b/scripts/sitegen/decorate.py @@ -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 diff --git a/scripts/sitegen/diagrams.py b/scripts/sitegen/diagrams.py index 188fbc9ba..d7b89ee38 100644 --- a/scripts/sitegen/diagrams.py +++ b/scripts/sitegen/diagrams.py @@ -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]*)[ \t]*$") -PLACEHOLDER_ANYWHERE = re.compile(r"") - FONT = "system-ui, -apple-system, 'Segoe UI', Helvetica, Arial, sans-serif" # The stylesheet sets the page font on every , 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 "[ \t]*\n" - r"(?P=indent)```(?:sh|bash)[^\n]*\n(?P.*?)\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 `` as Windows, macOS, - Linux and Steam Deck tabs. `` - 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)^[ \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"(? 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[ \t]*)(?P```|~~~)[^\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"{m.group(0)}", - markdown[position:match.start()])) - block = match.group(0) - if HASH_TEXT.search(block): - indent = match.group("indent") - block = f"{indent}
\n\n{block}\n\n{indent}
" - pieces.append(block) - position = match.end() - pieces.append(HASH_SPAN.sub(lambda m: f"{m.group(0)}", - 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)^\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("', - '', - mark, - 'RetroBIOS', - f'{escape(title)}', - ] - for index, line in enumerate(wrap(tagline, 1000, 34)): - body.append( - f'{escape(line)}' - ) - body.append('abdess.github.io/retrobios') - return ( - '' + "".join(body) + "" - ) - - 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) diff --git a/scripts/sitegen/ogcards.py b/scripts/sitegen/ogcards.py index 08a30593c..49e016b0d 100644 --- a/scripts/sitegen/ogcards.py +++ b/scripts/sitegen/ogcards.py @@ -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("', + '', + mark, + 'RetroBIOS', + f'{escape(title)}', + ] + for index, line in enumerate(wrap(tagline, TAGLINE_WIDTH, TAGLINE_SIZE)): + body.append( + f'{escape(line)}' + ) + body.append('abdess.github.io/retrobios') + return ( + '' + "".join(body) + "" + ) + + 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 diff --git a/scripts/sitegen/pageprep.py b/scripts/sitegen/pageprep.py new file mode 100644 index 000000000..accfede59 --- /dev/null +++ b/scripts/sitegen/pageprep.py @@ -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]*)[ \t]*$") +PLACEHOLDER_ANYWHERE = re.compile(r"") + + +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 "[ \t]*\n" + r"(?P=indent)```(?:sh|bash)[^\n]*\n(?P.*?)\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 `` as Windows, macOS, + Linux and Steam Deck tabs. `` + 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[ \t]*)(?P```|~~~)[^\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"{m.group(0)}", + markdown[position:match.start()])) + block = match.group(0) + if HASH_TEXT.search(block): + indent = match.group("indent") + block = f"{indent}
\n\n{block}\n\n{indent}
" + pieces.append(block) + position = match.end() + pieces.append(HASH_SPAN.sub(lambda m: f"{m.group(0)}", + 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)^\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 + + diff --git a/scripts/sitegen/platformpage.py b/scripts/sitegen/platformpage.py index c58facaba..973f397d6 100644 --- a/scripts/sitegen/platformpage.py +++ b/scripts/sitegen/platformpage.py @@ -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 diff --git a/scripts/sitegen/render.py b/scripts/sitegen/render.py index 59af77622..ff560ebce 100644 --- a/scripts/sitegen/render.py +++ b/scripts/sitegen/render.py @@ -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) diff --git a/tests/sources.py b/tests/sources.py index c39d2f390..322c8cd0c 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -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", diff --git a/tests/test_site_images.py b/tests/test_site_images.py index dfb3b8d41..a05d66073 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -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( "\n\ntext\n\n\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\n\nMore\n") + page = pageprep.resolve_images("Intro\n\n\n\nMore\n") self.assertIn('
\n") + page = pageprep.resolve_images("1. Step\n\n \n") line = page.splitlines()[2] self.assertTrue(line.startswith(" |" - 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()) diff --git a/tests/test_site_integration.py b/tests/test_site_integration.py index 867661048..c97e515fe 100644 --- a/tests/test_site_integration.py +++ b/tests/test_site_integration.py @@ -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): diff --git a/tests/test_site_wiki.py b/tests/test_site_wiki.py index 450099379..bb6710410 100644 --- a/tests/test_site_wiki.py +++ b/tests/test_site_wiki.py @@ -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): "\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('', 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("\n```sh\nls -l\n```\n") + pageprep.expand_commands("\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", ""))) + r"and (\d+) more", ogcards.og_card_svg("home", ""))) 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("
\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("