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)