"""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