chore: merge the site generator quality work

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 09:33:57 +01:00
commit c7d89627fb
17 files changed
+3078 -2173

No files matched your search

+1 -1
View File
@@ -91,7 +91,7 @@ def square_image(data: bytes, size: int, kind: str = "PNG", flip: bool = False,
def is_svg(data: bytes) -> bool:
head = data[:512].lstrip().lower()
return head.startswith(b"<?xml") or head.startswith(b"<svg")
return head.startswith((b"<?xml", b"<svg"))
def safe_svg(data: bytes, url: str) -> bytes:
+2
View File
@@ -19,6 +19,8 @@ ROOT = Path(__file__).resolve().parent.parent
OUTPUT = ROOT / "schemas" / "install-events.schema.json"
_spec = importlib.util.spec_from_file_location("install", ROOT / "install.py")
if _spec is None or _spec.loader is None:
raise ImportError(f"cannot load {ROOT / 'install.py'}")
_install = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_install)
+41 -23
View File
@@ -37,6 +37,7 @@ import json
import os
import re
import shutil
import socket
import socketserver
import subprocess
import sys
@@ -44,16 +45,21 @@ import tempfile
import threading
import zipfile
from pathlib import Path, PurePosixPath
from typing import Callable
from typing import TYPE_CHECKING, Any, Callable
import sitehandheld
from artifacts import write_text_atomic
if TYPE_CHECKING:
from install import LocalCopy, Progress, _OsRule
ROOT = Path(__file__).resolve().parent.parent
PAGE = ROOT / "wiki" / "installer.md"
INSTALLER = ROOT / "install.py"
_spec = importlib.util.spec_from_file_location("install", INSTALLER)
if _spec is None or _spec.loader is None:
raise ImportError(f"cannot load {INSTALLER}")
_install = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_install)
@@ -183,7 +189,7 @@ def route_keys() -> str:
_BARE_FILES = frozenset({"MiSTer"})
def _marker(rule: _install._OsRule) -> str:
def _marker(rule: _OsRule) -> str:
"""A card rule's evidence in words: the file or folder, and the line it
holds for a rule that reads one."""
if rule.method == "file_matches":
@@ -281,8 +287,9 @@ class _ListHandler(http.server.SimpleHTTPRequestHandler):
"""Serves the committed file lists, install/<platform>.json, and nothing
else: a sample that asks for a file is a sample that downloads."""
def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__(*args, directory=str(ROOT), **kwargs)
def __init__(self, request: socket.socket | tuple[bytes, socket.socket],
client_address: tuple[str, int], server: socketserver.BaseServer) -> None:
super().__init__(request, client_address, server, directory=str(ROOT))
def do_GET(self) -> None:
if not re.fullmatch(r"/install/[a-z0-9_-]+\.json", self.path):
@@ -302,6 +309,8 @@ class _LoopbackServer(http.server.ThreadingHTTPServer):
def server_bind(self) -> None:
socketserver.TCPServer.server_bind(self)
host, port = self.server_address[:2]
if not isinstance(host, str):
raise TypeError(f"the list server needs a host name, not {host!r}")
self.server_name, self.server_port = host, port
@@ -340,20 +349,20 @@ def _child(spec: dict) -> int:
them, and a held run finds every file and tree in place. The counts,
sizes and words are the installer's own."""
import concurrent.futures
import socket
from unittest import mock
real_connect = socket.create_connection
def loopback_only(address: tuple, *args: object, **kwargs: object) -> socket.socket:
# The rest of the arguments are create_connection's own, passed through.
def loopback_only(address: tuple[str, int], *args: Any, **kwargs: Any) -> socket.socket:
if address[0] not in ("127.0.0.1", "localhost"):
raise OSError(f"the sample makes no request to {address[0]}")
return real_connect(address, *args, **kwargs)
real_download = _install._download_one
def landed(f: dict, bios: Path, verbose: bool = False, progress: object = None,
copy: object = None) -> tuple[str, bool, str]:
def landed(f: dict, bios: Path, verbose: bool = False, progress: Progress | None = None,
copy: LocalCopy | None = None) -> tuple[str, bool, str]:
if copy is not None:
# A copy from this machine is made for real: it is local.
return real_download(f, bios, verbose, progress, copy)
@@ -372,7 +381,7 @@ def _child(spec: dict) -> int:
def tree_held(entry: dict, bios: Path, remember: bool = False) -> tuple:
return bios / entry.get("dest", ""), {}, len(entry["files"])
patches = [
patches: list[contextlib.AbstractContextManager[object]] = [
mock.patch.object(socket, "create_connection", loopback_only),
# One worker and the submission order: the progress lines of a log.
mock.patch.object(concurrent.futures, "as_completed", list),
@@ -463,7 +472,8 @@ class Sandbox:
card = self.card / "userdata" / "bios" if platform != "retroarch" else None
if card is not None:
card.mkdir(parents=True, exist_ok=True)
spec = {"platform": platform, "argv": ["--plain", "--platform", platform, *argv],
args = ["--plain", "--platform", platform, *argv]
spec = {"platform": platform, "argv": args,
"card": str(card) if card else None, "landed": landed, "held": held}
env = {"PATH": os.environ.get("PATH", ""), "HOME": str(home),
"RETROBIOS_OS": "linux", "LANG": "C.UTF-8",
@@ -473,7 +483,7 @@ class Sandbox:
cwd=ROOT, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True,
check=False)
if done.returncode not in codes:
raise SampleFailed(f"install.py {' '.join(spec['argv'])} exited "
raise SampleFailed(f"install.py {' '.join(args)} exited "
f"{done.returncode}: {done.stderr.strip()[-2000:]}")
return done.stdout.replace(str(home), SHOWN_HOME).replace(str(self.card), SHOWN_CARD)
@@ -484,8 +494,8 @@ _RUNS: dict[tuple, str] = {}
def _stamp(platform: str) -> tuple[int, int]:
return tuple(hash(path.read_bytes()) for path in
(INSTALLER, ROOT / "install" / f"{platform}.json"))
return (hash(INSTALLER.read_bytes()),
hash((ROOT / "install" / f"{platform}.json").read_bytes()))
class _LazySandbox:
@@ -495,14 +505,13 @@ class _LazySandbox:
self.stack = stack
self.box: Sandbox | None = None
def run(self, platform: str, *argv: str, **kinds: bool) -> str:
key = (platform, argv, kinds.get("landed", False), kinds.get("held", False),
_stamp(platform))
def run(self, platform: str, *argv: str, landed: bool = False, held: bool = False) -> str:
key = (platform, argv, landed, held, _stamp(platform))
if key in _RUNS:
return _RUNS[key]
if self.box is None:
self.box = self.stack.enter_context(Sandbox())
_RUNS[key] = self.box.run(platform, *argv, **kinds)
_RUNS[key] = self.box.run(platform, *argv, landed=landed, held=held)
return _RUNS[key]
def small(self, kind: str) -> str:
@@ -528,6 +537,8 @@ def _lines_from(text: str, first: str, last: str | None = None, count: int | Non
raise SampleFailed(f"the run printed no line starting {first!r}")
if count is not None:
return lines[start:start + count]
if last is None:
raise ValueError("_lines_from needs last or count")
end = next((i for i in range(start, len(lines)) if lines[i].startswith(last)), None)
if end is None:
raise SampleFailed(f"the run printed no line starting {last!r} after {first!r}")
@@ -561,15 +572,22 @@ def _bulk_line(box: Sandbox | _LazySandbox) -> str:
return found[0]
def sample_writers(box: Sandbox) -> dict[str, Callable[[str], str]]:
def sample_writers(box: Sandbox | _LazySandbox) -> dict[str, Callable[[str], str]]:
"""The run samples, each from the run that prints it: the walk through a
run reads its --verbose lines, the default sample the lines it hides them
from."""
default_run = lambda: box.run(WALKTHROUGH, "--yes", "--jobs", "1", landed=True) # noqa: E731
install_run = lambda: box.run(WALKTHROUGH, "--yes", "--jobs", "1", "--verbose", # noqa: E731
landed=True)
check_run = lambda: box.run(WALKTHROUGH, "--check", "--verbose", held=True) # noqa: E731
dry_run = lambda: box.run("retroarch", "--dry-run", "--verbose") # noqa: E731
def default_run() -> str:
return box.run(WALKTHROUGH, "--yes", "--jobs", "1", landed=True)
def install_run() -> str:
return box.run(WALKTHROUGH, "--yes", "--jobs", "1", "--verbose", landed=True)
def check_run() -> str:
return box.run(WALKTHROUGH, "--check", "--verbose", held=True)
def dry_run() -> str:
return box.run("retroarch", "--dry-run", "--verbose")
return {
"run-default": lambda _body: _fenced(
_lines_from(default_run(), "Installing ", "Next: ")),
+2
View File
@@ -36,6 +36,8 @@ from build_port import (
OUTPUT = REPO_ROOT / "install" / "launchers" / "index.json"
_spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py")
if _spec is None or _spec.loader is None:
raise ImportError(f"cannot load {REPO_ROOT / 'install.py'}")
_install = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_install)
+6 -3
View File
@@ -18,6 +18,7 @@ import sys
from collections.abc import Callable
from datetime import datetime, timezone
from pathlib import Path
from types import ModuleType
sys.path.insert(0, os.path.dirname(__file__))
from common import (
@@ -46,13 +47,15 @@ import pr_checks
from verify import verify_platform
def _installer_words() -> object:
def _installer_words() -> ModuleType:
"""install.py read as a module, for the words its screen shows: the
README named a line menu the one-liner never opens."""
import importlib.util
spec = importlib.util.spec_from_file_location(
"install", Path(__file__).resolve().parent.parent / "install.py")
path = Path(__file__).resolve().parent.parent / "install.py"
spec = importlib.util.spec_from_file_location("install", path)
if spec is None or spec.loader is None:
raise ImportError(f"cannot load {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
+2358 -1747
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -64,6 +64,7 @@ import shutil
import subprocess
import sys
import threading
import types
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
@@ -363,7 +364,7 @@ def session_env(base_url: str, work: Path, card: Path,
}
def _installer() -> object:
def _installer() -> types.ModuleType:
spec = importlib.util.spec_from_file_location("retrobios_install", ROOT / "install.py")
if spec is None or spec.loader is None:
raise RuntimeError("install.py cannot be loaded")
@@ -374,7 +375,7 @@ def _installer() -> object:
def format_size(size: int) -> str:
"""The size as the installer writes it."""
return str(_installer().format_size(size)) # type: ignore[attr-defined]
return str(_installer().format_size(size))
def describe(variant: str, facts: dict) -> str:
+5 -4
View File
@@ -23,11 +23,12 @@ import argparse
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts"))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from common import list_registered_platforms, load_platform_config # noqa: E402
from sitediagrams import OG_SECTIONS, og_card_svg, wrap # noqa: E402
from common import list_registered_platforms, load_platform_config
from sitediagrams import OG_SECTIONS, og_card_svg, wrap
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "docs_assets" / "og"
LOGO = ROOT / "docs_assets" / "brand" / "logo.svg"
+4
View File
@@ -116,6 +116,8 @@ def fetch_queries(start: dt.date, end: dt.date) -> list[Query]:
answer = _get_json(url, {"Authorization": f"Bearer {token}"}, {
"startDate": start.isoformat(), "endDate": end.isoformat(),
"dimensions": ["query", "page"], "rowLimit": 25000, "startRow": len(rows)})
if not isinstance(answer, dict):
raise SystemExit("Search Console answered with something other than an object")
batch = answer.get("rows", [])
rows += [Query(r["keys"][0], r["keys"][1], int(r["clicks"]), int(r["impressions"]),
float(r["position"])) for r in batch]
@@ -133,6 +135,8 @@ def fetch_goatcounter(start: dt.date, end: dt.date) -> dict:
while True:
params = urllib.parse.urlencode({**span, "limit": 100, "exclude_paths": ",".join(exclude)})
answer = _get_json(f"{GOATCOUNTER}/stats/hits?{params}", auth)
if not isinstance(answer, dict):
raise SystemExit("GoatCounter answered with something other than an object")
for hit in answer.get("hits", []):
hits.append((hit["path"] + (" [404]" if hit.get("title") == "404" else ""), int(hit["count"])))
exclude.append(str(hit["path_id"]))
+200 -106
View File
@@ -33,8 +33,10 @@ import os
import re
import subprocess
import sys
from collections.abc import Callable
from html.parser import HTMLParser
from pathlib import Path
from typing import ClassVar
sys.path.insert(0, os.path.dirname(__file__))
from common import run_cli
@@ -106,23 +108,37 @@ class _Converter(HTMLParser):
return
if tag not in ("br", "img", "hr", "input", "meta", "link", "source", "wbr"):
self.depth_stack.append(tag)
if self._open_tabs(tag, attr) or self._open_skipped(tag, attr, classes):
return
if self.pre:
# Inside a code block a line is a div, never a paragraph.
if tag == "div" and "ec-line" in classes and not "".join(self.out[-1:]).endswith("```\n"):
self._emit("\n")
return
opener = self._OPENERS.get(tag)
if opener is not None:
opener(self, tag, attr, classes)
def _open_tabs(self, tag: str, attr: dict[str, str]) -> bool:
"""A tab list, a tab's name or a tab panel: True when handled."""
if attr.get("role") == "tablist":
self.skip += 1
if tag == "a" or attr.get("role") == "tab":
pass
return
return True
if self.skip and attr.get("role") == "tab" and attr.get("id"):
self._tab = attr["id"]
self.tab_names[self._tab] = ""
self.skip += 1
return
return True
if attr.get("role") == "tabpanel" and not self.skip:
self._block()
name = self.tab_names.get(attr.get("aria-labelledby", ""), "").strip()
if name:
self._emit(f"**{' '.join(name.split())}:**")
self._block()
return
return True
return False
def _open_skipped(self, tag: str, attr: dict[str, str], classes: set[str]) -> bool:
# A `hidden` element is chrome the page's script shows (a filter
# box, the file picker, a setup's install chooser): a tab panel,
# hidden too, was read above.
@@ -130,80 +146,117 @@ class _Converter(HTMLParser):
or classes & {"sr-only", "sl-anchor-link", "copy", "rb-anchor"}:
if tag not in ("br", "img", "hr", "input", "wbr"):
self.skip += 1
return
if self.pre:
# Inside a code block a line is a div, never a paragraph.
if tag == "div" and "ec-line" in classes and not "".join(self.out[-1:]).endswith("```\n"):
self._emit("\n")
return
if tag in HEADINGS:
self._block()
self._emit("#" * HEADINGS[tag] + " ")
elif tag in ("p", "div", "section", "figure", "details", "blockquote", "dl"):
self._block()
elif tag == "summary":
self._block()
self._emit("**")
elif tag in ("ul", "ol"):
self._block()
self.lists.append([0 if tag == "ol" else -1])
elif tag == "li":
if self.out and not "".join(self.out[-1:]).endswith("\n"):
self._emit("\n")
level = len(self.lists) - 1
marker = "-"
if self.lists and self.lists[-1][0] >= 0:
self.lists[-1][0] += 1
marker = f"{self.lists[-1][0]}."
self._emit(" " * max(level, 0) + marker + " ")
elif tag == "pre":
self._block()
self.pre += 1
self._emit("```\n")
elif tag == "code" and not self.pre:
return True
return False
def _open_heading(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self._emit("#" * HEADINGS[tag] + " ")
def _open_block(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
def _open_bold_block(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self._emit("**")
def _open_list(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.lists.append([0 if tag == "ol" else -1])
def _open_item(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.out and not "".join(self.out[-1:]).endswith("\n"):
self._emit("\n")
level = len(self.lists) - 1
marker = "-"
if self.lists and self.lists[-1][0] >= 0:
self.lists[-1][0] += 1
marker = f"{self.lists[-1][0]}."
self._emit(" " * max(level, 0) + marker + " ")
def _open_pre(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.pre += 1
self._emit("```\n")
def _open_code(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if not self.pre:
self._emit("`")
elif tag in ("strong", "b"):
self._emit("**")
elif tag in ("em", "i"):
self._emit("*")
elif tag == "a" and "rb-card" in classes:
def _open_strong(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit("**")
def _open_em(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit("*")
def _open_link(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
href = attr.get("href", "")
if "rb-card" in classes:
# A card of a grid: one list line each, its name then what it
# says, instead of one run-on line of links.
href = attr.get("href", "")
href = SITE + href if href.startswith("/") else href
self._block()
self._emit("- [")
self.links.append(href or None)
self._card = True
elif tag == "span" and self._card and self.links:
return
if href.startswith("#"):
href = self.page_url + href
elif href.startswith("/"):
href = SITE + href
self.links.append(href or None)
if href:
self._emit("[")
def _open_span(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self._card and self.links:
self._emit(": ")
elif tag == "a":
href = attr.get("href", "")
if href.startswith("#"):
href = self.page_url + href
elif href.startswith("/"):
href = SITE + href
self.links.append(href or None)
if href:
self._emit("[")
elif tag == "img":
alt = attr.get("alt", "").strip()
if alt:
self._emit(alt)
elif tag == "table":
self._block()
self.table, self.header_rows = [], 0
elif tag == "tr" and self.table is not None:
def _open_img(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
alt = attr.get("alt", "").strip()
if alt:
self._emit(alt)
def _open_table(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._block()
self.table, self.header_rows = [], 0
def _open_row(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.table is not None:
self.row = []
elif tag in ("td", "th") and self.row is not None:
def _open_cell(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
if self.row is not None:
self.cell = []
if tag == "th" and not self.row:
self.header_rows = max(self.header_rows, len(self.table or []) + 1)
elif tag == "dt":
self._block()
self._emit("**")
elif tag == "dd":
self._emit(": ")
def _open_definition(self, tag: str, attr: dict[str, str], classes: set[str]) -> None:
self._emit(": ")
_OPENERS: ClassVar[dict[str, Callable[[_Converter, str, dict[str, str], set[str]], None]]] = {
**dict.fromkeys(HEADINGS, _open_heading),
**dict.fromkeys(("p", "div", "section", "figure", "details", "blockquote", "dl"), _open_block),
"summary": _open_bold_block,
"dt": _open_bold_block,
"ul": _open_list,
"ol": _open_list,
"li": _open_item,
"pre": _open_pre,
"code": _open_code,
"strong": _open_strong,
"b": _open_strong,
"em": _open_em,
"i": _open_em,
"a": _open_link,
"span": _open_span,
"img": _open_img,
"table": _open_table,
"tr": _open_row,
"td": _open_cell,
"th": _open_cell,
"dd": _open_definition,
}
def handle_endtag(self, tag: str) -> None:
if tag == "h1" and self._in_title:
@@ -223,51 +276,92 @@ class _Converter(HTMLParser):
return
if self.pre and tag != "pre":
return
if tag in HEADINGS or tag in ("p", "section", "figure", "details", "blockquote", "dl"):
self._block()
elif tag == "summary":
self._emit("**")
self._block()
elif tag in ("ul", "ol"):
if self.lists:
self.lists.pop()
self._block()
elif tag == "pre":
self.pre -= 1
self._emit("\n```")
self._block()
elif tag == "code" and not self.pre:
closer = self._CLOSERS.get(tag)
if closer is not None:
closer(self, tag)
def _close_block(self, tag: str) -> None:
self._block()
def _close_summary(self, tag: str) -> None:
self._emit("**")
self._block()
def _close_list(self, tag: str) -> None:
if self.lists:
self.lists.pop()
self._block()
def _close_pre(self, tag: str) -> None:
self.pre -= 1
self._emit("\n```")
self._block()
def _close_code(self, tag: str) -> None:
if not self.pre:
self._emit("`")
elif tag in ("strong", "b", "dt"):
self._emit("**")
elif tag in ("em", "i"):
self._emit("*")
elif tag == "a":
href = self.links.pop() if self.links else None
if href:
self._emit(f"]({href})")
if self._card:
self._card = False
self._emit("\n")
elif tag in ("td", "th") and self.cell is not None and self.row is not None:
def _close_strong(self, tag: str) -> None:
self._emit("**")
def _close_em(self, tag: str) -> None:
self._emit("*")
def _close_link(self, tag: str) -> None:
href = self.links.pop() if self.links else None
if href:
self._emit(f"]({href})")
if self._card:
self._card = False
self._emit("\n")
def _close_cell(self, tag: str) -> None:
if self.cell is not None and self.row is not None:
self.row.append(" ".join("".join(self.cell).split()).replace("|", "\\|"))
self.cell = None
elif tag == "tr" and self.row is not None and self.table is not None:
def _close_row(self, tag: str) -> None:
if self.row is not None and self.table is not None:
self.table.append(self.row)
self.row = None
elif tag == "table" and self.table is not None:
rows, self.table = self.table, None
if rows:
width = max(len(r) for r in rows)
rows = [r + [""] * (width - len(r)) for r in rows]
head = rows[0] if self.header_rows else [""] * width
body = rows[1:] if self.header_rows else rows
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * width]
lines += ["| " + " | ".join(r) + " |" for r in body]
self.out.append("\n".join(lines))
self._block()
elif tag == "br":
self._emit("\n" if self.pre else " \n")
def _close_table(self, tag: str) -> None:
if self.table is None:
return
rows, self.table = self.table, None
if rows:
width = max(len(r) for r in rows)
rows = [r + [""] * (width - len(r)) for r in rows]
head = rows[0] if self.header_rows else [""] * width
body = rows[1:] if self.header_rows else rows
lines = ["| " + " | ".join(head) + " |", "|" + "---|" * width]
lines += ["| " + " | ".join(r) + " |" for r in body]
self.out.append("\n".join(lines))
self._block()
def _close_break(self, tag: str) -> None:
self._emit("\n" if self.pre else " \n")
_CLOSERS: ClassVar[dict[str, Callable[[_Converter, str], None]]] = {
**dict.fromkeys(HEADINGS, _close_block),
**dict.fromkeys(("p", "section", "figure", "details", "blockquote", "dl"), _close_block),
"summary": _close_summary,
"ul": _close_list,
"ol": _close_list,
"pre": _close_pre,
"code": _close_code,
"strong": _close_strong,
"b": _close_strong,
"dt": _close_strong,
"em": _close_em,
"i": _close_em,
"a": _close_link,
"td": _close_cell,
"th": _close_cell,
"tr": _close_row,
"table": _close_table,
"br": _close_break,
}
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
+62 -38
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import functools
import os
import sys
from dataclasses import dataclass
sys.path.insert(0, os.path.dirname(__file__))
import siteinputs
@@ -94,10 +95,41 @@ def _engine_sections(manufacturers: dict[str, dict[str, list]]) -> dict[str, dic
top joins that top, and a folder named by a profile key is headed with
the engine's name (SECTION_LABELS), its address unchanged.
"""
from siterender import _PROGRAM_TOPS, SECTION_LABELS, record_card_move
from siterender import SECTION_LABELS
profiles = {key: profile for key, profile in _profiles_on_disk().items()
if profile.get("type") != "alias" and profile.get("role") != "test"}
engines = _Engines(profiles, _file_readers(profiles))
out: dict[str, dict[str, list]] = {}
for mfr, consoles in manufacturers.items():
if mfr not in GAME_DATA_TOPS:
out[mfr] = dict(consoles)
continue
out[mfr] = _regroup_top(mfr, consoles, engines)
_join_other_folders(out)
for mfr in GAME_DATA_TOPS:
for console in out.get(mfr, {}):
named = console if console in profiles else None
if named and engines.engine(named) != console:
SECTION_LABELS[(mfr, console)] = engines.engine(named)
return {mfr: consoles for mfr, consoles in out.items() if consoles}
@dataclass(frozen=True)
class _Engines:
"""The game-engine profiles, and the profiles that read each file name."""
profiles: dict[str, dict]
readers: dict[str, set[str]]
def engine(self, key: str) -> str:
return str(self.profiles[key].get("emulator") or key)
def profile_of(self, name: str) -> str | None:
return next((k for k in sorted(self.profiles)
if name.casefold() in (k.casefold(), self.engine(k).casefold())), None)
def _file_readers(profiles: dict[str, dict]) -> dict[str, set[str]]:
readers: dict[str, set[str]] = {}
for key, profile in profiles.items():
for entry in profile.get("files") or []:
@@ -105,40 +137,38 @@ def _engine_sections(manufacturers: dict[str, dict[str, list]]) -> dict[str, dic
for name in [entry.get("name"), *(entry.get("aliases") or [])]:
if name:
readers.setdefault(str(name).rsplit("/", 1)[-1], set()).add(key)
return readers
def engine(key: str) -> str:
return str(profiles[key].get("emulator") or key)
def profile_of(name: str) -> str | None:
return next((k for k in sorted(profiles)
if name.casefold() in (k.casefold(), engine(k).casefold())), None)
def _regroup_top(mfr: str, consoles: dict[str, list], engines: _Engines) -> dict[str, list]:
from siterender import record_card_move
own = engines.profile_of(mfr)
regrouped: dict[str, list] = {}
for console, files in sorted(consoles.items(), key=lambda item: item[0].startswith(".")):
for f in files:
parts = str(f.get("path", "")).split("/")
target = console
if console.startswith(".") or (len(parts) == 3 and console == parts[-1]):
# A variant answers its primary's name: scummvm.zip.a93f1c4b.
base = parts[-1].rsplit(".", 1)[0] if console.startswith(".") else parts[-1]
keys = sorted(engines.readers.get(base, ()))
reader = keys[0] if len(keys) == 1 else own
found = next((c for c, held in regrouped.items()
if any(h.get("name") == base for h in held)), None)
target = found or (next((c for c in consoles if c == reader), None)
or (engines.engine(reader) if reader else base))
if target != console:
record_card_move(mfr, console, str(f.get("sha1", "")), mfr, target)
regrouped.setdefault(target, []).append(f)
return regrouped
def _join_other_folders(out: dict[str, dict[str, list]]) -> None:
"""The folder under Other an engine top is named after: ScummVM's
engine data under Other/ScummVM, its themes under ScummVM/."""
from siterender import _PROGRAM_TOPS, record_card_move
out: dict[str, dict[str, list]] = {}
for mfr, consoles in manufacturers.items():
if mfr not in GAME_DATA_TOPS:
out[mfr] = dict(consoles)
continue
own = profile_of(mfr)
regrouped: dict[str, list] = {}
for console, files in sorted(consoles.items(), key=lambda item: item[0].startswith(".")):
for f in files:
parts = str(f.get("path", "")).split("/")
target = console
if console.startswith(".") or (len(parts) == 3 and console == parts[-1]):
# A variant answers its primary's name: scummvm.zip.a93f1c4b.
base = parts[-1].rsplit(".", 1)[0] if console.startswith(".") else parts[-1]
keys = sorted(readers.get(base, ()))
reader = keys[0] if len(keys) == 1 else own
found = next((c for c, held in regrouped.items()
if any(h.get("name") == base for h in held)), None)
target = found or (next((c for c in consoles if c == reader), None)
or (engine(reader) if reader else base))
if target != console:
record_card_move(mfr, console, str(f.get("sha1", "")), mfr, target)
regrouped.setdefault(target, []).append(f)
out[mfr] = regrouped
# The folder under Other an engine top is named after: ScummVM's
# engine data under Other/ScummVM, its themes under ScummVM/.
others = out.get("Other", {})
for folder in sorted(others):
top = next((t for t in out if t in GAME_DATA_TOPS and t.casefold() == folder.casefold()),
@@ -152,12 +182,6 @@ def _engine_sections(manufacturers: dict[str, dict[str, list]]) -> dict[str, dic
record_card_move("Other", folder, str(f.get("sha1", "")), top, target)
sections[target] = [*sections.get(target, []),
*(f for f in others.pop(folder) if str(f.get("sha1", "")) not in held)]
for mfr in GAME_DATA_TOPS:
for console in out.get(mfr, {}):
named = console if console in profiles else None
if named and engine(named) != console:
SECTION_LABELS[(mfr, console)] = engine(named)
return {mfr: consoles for mfr, consoles in out.items() if consoles}
def _profiles_on_disk() -> dict[str, dict]:
+18 -9
View File
@@ -39,11 +39,12 @@ from functools import cache
from pathlib import Path
from xml.sax.saxutils import escape
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts"))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import siteinputs # noqa: E402
import sitemarkup as markup # noqa: E402
import siteinputs
import sitemarkup as markup
ROOT = Path(__file__).resolve().parent.parent
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*-->")
@@ -626,9 +627,15 @@ def _pipeline_boxes() -> list[Box]:
"""The steps pipeline.py runs, read from its STEP_LABELS literal."""
tree = ast.parse((ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"))
for node in ast.walk(tree):
target = getattr(node, "target", None) or (getattr(node, "targets", [None]) or [None])[0]
if isinstance(target, ast.Name) and target.id == "STEP_LABELS":
labels = ast.literal_eval(node.value)
if isinstance(node, ast.Assign):
target: ast.expr = node.targets[0]
value: ast.expr | None = node.value
elif isinstance(node, ast.AnnAssign):
target, value = node.target, node.value
else:
continue
if isinstance(target, ast.Name) and target.id == "STEP_LABELS" and value is not None:
labels = ast.literal_eval(value)
break
else:
raise RuntimeError("STEP_LABELS not found in scripts/pipeline.py")
@@ -945,7 +952,8 @@ def installer_options() -> tuple[tuple[str, str], ...]:
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)]
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)
@@ -953,7 +961,8 @@ def installer_options() -> tuple[tuple[str, str], ...]:
metavar = ""
if takes_value:
given = keywords.get("metavar")
metavar = given.value if isinstance(given, ast.Constant) else flags[0].lstrip("-").upper()
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.
+49 -33
View File
@@ -296,6 +296,50 @@ def _handheld_guide(data: object, registry: dict, guides: dict, where: str) -> H
)
def _terminals(raw: dict, file_name: str) -> dict[str, tuple[str, str, str]]:
terminals: dict[str, tuple[str, str, str]] = {}
for key, entry in raw.items():
at = f"{file_name}: terminals.{key}"
if not isinstance(entry, dict):
raise GuideError(f"{at}: expected a mapping")
_unknown(entry, _TERMINAL_KEYS, at)
label, how, shell = (_text(entry.get(k), f"{at}.{k}") for k in _TERMINAL_KEYS)
terminals[key] = (label, how, shell)
if entry["shell"] not in ("sh", "powershell"):
raise GuideError(f"{at}.shell: sh or powershell, found {entry['shell']!r}")
return terminals
def _also_runs(raw: list, raw_guides: dict, at: str) -> tuple[tuple[str, str, str, str, str], ...]:
rows = []
for i, row in enumerate(raw):
row_at = f"{at}.also_runs[{i}]"
if not isinstance(row, dict):
raise GuideError(f"{row_at}: expected a mapping")
_unknown(row, _ALSO_KEYS, row_at)
setup, summary, uses, runs_on, folder = (_text(row.get(k), f"{row_at}.{k}")
for k in _ALSO_KEYS)
if uses not in raw_guides:
raise GuideError(f"{row_at}.uses: {uses!r} is not a platform with a guide")
rows.append((setup, summary, uses, runs_on, folder))
return tuple(rows)
def _group_tiles(raw: list, at: str) -> tuple[Tile, ...]:
group_tiles = []
for i, row in enumerate(raw):
row_at = f"{at}.tiles[{i}]"
if not isinstance(row, dict):
raise GuideError(f"{row_at}: expected a mapping")
_unknown(row, _TILE_KEYS + _TILE_LOGO_KEYS, row_at)
if row.get("logo") and not all(row.get(k) for k in _TILE_LOGO_KEYS):
raise GuideError(f"{row_at}: a logo needs logo_owner and logo_licence")
group_tiles.append(Tile(
*(_text(row.get(k), f"{row_at}.{k}") for k in _TILE_KEYS),
*(_text(row[k], f"{row_at}.{k}") if row.get(k) else "" for k in _TILE_LOGO_KEYS)))
return tuple(group_tiles)
def load_guides(path: Path = GUIDES_FILE, registry: dict | None = None) -> dict:
"""The guides file, checked against the registry.
@@ -313,16 +357,7 @@ def load_guides(path: Path = GUIDES_FILE, registry: dict | None = None) -> dict:
raise GuideError(f"{path.name}: expected a mapping")
_unknown(data, _TOP_KEYS, path.name)
terminals: dict[str, tuple[str, str, str]] = {}
for key, entry in (data.get("terminals") or {}).items():
at = f"{path.name}: terminals.{key}"
if not isinstance(entry, dict):
raise GuideError(f"{at}: expected a mapping")
_unknown(entry, _TERMINAL_KEYS, at)
terminals[key] = tuple(_text(entry.get(k), f"{at}.{k}") for k in _TERMINAL_KEYS)
if entry["shell"] not in ("sh", "powershell"):
raise GuideError(f"{at}.shell: sh or powershell, found {entry['shell']!r}")
terminals = _terminals(data.get("terminals") or {}, path.name)
raw_guides = data.get("guides") or {}
groups: dict[str, tuple[str, str]] = {}
anchors: dict[str, str] = {}
@@ -336,31 +371,12 @@ def load_guides(path: Path = GUIDES_FILE, registry: dict | None = None) -> dict:
groups[key] = (_text(entry.get("label"), f"{at}.label"),
_text(entry.get("description"), f"{at}.description"))
anchors[key] = _text(entry.get("anchor"), f"{at}.anchor")
rows = []
for i, row in enumerate(entry.get("also_runs") or []):
row_at = f"{at}.also_runs[{i}]"
if not isinstance(row, dict):
raise GuideError(f"{row_at}: expected a mapping")
_unknown(row, _ALSO_KEYS, row_at)
values = tuple(_text(row.get(k), f"{row_at}.{k}") for k in _ALSO_KEYS)
if values[2] not in raw_guides:
raise GuideError(f"{row_at}.uses: {values[2]!r} is not a platform with a guide")
rows.append(values)
rows = _also_runs(entry.get("also_runs") or [], raw_guides, at)
if rows:
also_runs[key] = tuple(rows)
group_tiles = []
for i, row in enumerate(entry.get("tiles") or []):
row_at = f"{at}.tiles[{i}]"
if not isinstance(row, dict):
raise GuideError(f"{row_at}: expected a mapping")
_unknown(row, _TILE_KEYS + _TILE_LOGO_KEYS, row_at)
if row.get("logo") and not all(row.get(k) for k in _TILE_LOGO_KEYS):
raise GuideError(f"{row_at}: a logo needs logo_owner and logo_licence")
group_tiles.append(Tile(
*(_text(row.get(k), f"{row_at}.{k}") for k in _TILE_KEYS),
*(_text(row[k], f"{row_at}.{k}") if row.get(k) else "" for k in _TILE_LOGO_KEYS)))
also_runs[key] = rows
group_tiles = _group_tiles(entry.get("tiles") or [], at)
if group_tiles:
tiles[key] = tuple(group_tiles)
tiles[key] = group_tiles
unregistered = sorted(set(raw_guides) - set(registry))
if unregistered:
+5 -2
View File
@@ -143,7 +143,10 @@ def load_observations(path: Path) -> dict[str, dict]:
return {}
out = {}
for issue, entries in (yaml.safe_load(path.read_text(encoding="utf-8")) or {}).items():
number = ISSUE_SUBJECT.match(f"{issue}-")["number"]
named = ISSUE_SUBJECT.match(f"{issue}-")
if named is None:
raise ValueError(f"{path}: {issue!r} is not an issue<number> key")
number = named["number"]
for entry in entries:
for key in [*entry.get("records", ()), *entry.get("subjects", ())]:
out[key] = {"issue": number, "said": entry["said"]}
@@ -221,7 +224,7 @@ def build_index(stored: list[mr.Stored], source: dict | None, profiles: dict,
entries = by_subject[key]
latest = max(entries, key=lambda s: (s.record["recorded_at"], s.line))
profile = profiles.get(key[0]) or {}
records = [{"url": permalink((source or {}).get("repo"), (source or {}).get("commit"),
records = [{"url": permalink((source or {})["repo"], (source or {})["commit"],
mr.records_path(s.emulator), s.line),
"proves": proves(ancestors.get(s.record["id"]) or {s.record["id"]}, profile),
"shown": shown_of(s.record),
+85 -61
View File
@@ -324,7 +324,7 @@ _archive_boards: dict[str, str] = {}
_board_names: dict[str, str] = {}
# sha1 -> the (manufacturer, console) sections of the machines whose own
# set the archive is: neogeo.zip for the Neo Geo, mz2000.zip for the MZ.
_archive_machines: dict[str, set[tuple[str, str]]] = {}
_archive_machines: dict[str, set[tuple[str, str] | None]] = {}
_boards_built = [False]
@@ -394,26 +394,17 @@ def _arcade_suffix_sha1s(db: dict) -> frozenset[str]:
def _build_boards() -> None:
if _boards_built[0]:
return
from ziptools import zip_member_crcs
_ensure_console_sections()
if _arcade_source[0] is None:
import json
from common import load_emulator_profiles
inputs = siteinputs.current()
database = inputs.db
if not database.exists():
source = _arcade_source[0]
if source is None:
source = _read_arcade_source()
if source is None:
_archive_boards.clear()
_board_names.clear()
_boards_built[0] = True
return
with open(database, encoding="utf-8") as handle:
db = json.load(handle)
profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False)
_arcade_source[0] = (profiles, db)
profiles, db = _arcade_source[0]
_arcade_source[0] = source
profiles, db = source
files = db.get("files", {})
by_name = db.get("indexes", {}).get("by_name", {})
@@ -432,49 +423,84 @@ def _build_boards() -> None:
owners = _owner_ids(entry, systems)
if not owners:
continue
crcs = {
str(member["crc32"]).lower()
for member in entry.get("contents") or []
if isinstance(member, dict) and member.get("crc32")
}
names = {str(entry.get("name", ""))}
names.update(str(alias) for alias in entry.get("aliases") or [])
archives: set[str] = set()
for name in names:
found = by_name.get(name.rsplit("/", 1)[-1]) or []
for sha1 in [found] if isinstance(found, str) else found:
if sha1 not in files:
continue
if crcs:
held = zip_member_crcs(str(_REPO_ROOT / files[sha1]["path"]))
# An archive the build cannot read keeps its name.
if held and not held & crcs:
continue
archives.add(sha1)
for owner in owners:
role = _board_role(owner)
if role == _MACHINE:
# The profile's only system stands for an entry that names
# none: MAME's printer and expansion sets in a Dragon
# profile. Only an entry naming the machine moves its set,
# and only when every machine it names has that section:
# epson_fx80.zip, which sixteen machines load, has none.
declared = entry.get("system") or entry.get("systems")
places = {_machine_section(o) for o in owners
if _board_role(o) == _MACHINE} if declared else {None}
section = next(iter(places)) if len(places) == 1 else None
for sha1 in archives:
votes[sha1] = None
_archive_machines.setdefault(sha1, set()).add(section)
continue
if role is None:
continue
ids_by_name.setdefault(role.casefold(), set()).add(owner)
for sha1 in archives:
ballot = votes.setdefault(sha1, {})
if ballot is not None:
ballot.setdefault(role.casefold(), set()).add(key)
archives = _entry_archives(entry, files, by_name)
_cast_votes(key, entry, owners, archives, votes, ids_by_name)
_elect_boards(votes, ids_by_name, db)
_boards_built[0] = True
def _read_arcade_source() -> tuple[dict, dict] | None:
"""The profiles and database of the repository, None without a database."""
import json
from common import load_emulator_profiles
inputs = siteinputs.current()
database = inputs.db
if not database.exists():
return None
with open(database, encoding="utf-8") as handle:
db = json.load(handle)
profiles = load_emulator_profiles(str(inputs.emulators), skip_aliases=False)
return profiles, db
def _entry_archives(entry: dict, files: dict, by_name: dict) -> set[str]:
"""The archives of the collection a ``bios_zip`` entry names."""
from ziptools import zip_member_crcs
crcs = {
str(member["crc32"]).lower()
for member in entry.get("contents") or []
if isinstance(member, dict) and member.get("crc32")
}
names = {str(entry.get("name", ""))}
names.update(str(alias) for alias in entry.get("aliases") or [])
archives: set[str] = set()
for name in names:
found = by_name.get(name.rsplit("/", 1)[-1]) or []
for sha1 in [found] if isinstance(found, str) else found:
if sha1 not in files:
continue
if crcs:
held = zip_member_crcs(str(_REPO_ROOT / files[sha1]["path"]))
# An archive the build cannot read keeps its name.
if held and not held & crcs:
continue
archives.add(sha1)
return archives
def _cast_votes(key: str, entry: dict, owners: set[str], archives: set[str],
votes: dict[str, dict[str, set[str]] | None],
ids_by_name: dict[str, set[str]]) -> None:
for owner in owners:
role = _board_role(owner)
if role == _MACHINE:
# The profile's only system stands for an entry that names
# none: MAME's printer and expansion sets in a Dragon
# profile. Only an entry naming the machine moves its set,
# and only when every machine it names has that section:
# epson_fx80.zip, which sixteen machines load, has none.
declared = entry.get("system") or entry.get("systems")
places = {_machine_section(o) for o in owners
if _board_role(o) == _MACHINE} if declared else {None}
section = next(iter(places)) if len(places) == 1 else None
for sha1 in archives:
votes[sha1] = None
_archive_machines.setdefault(sha1, set()).add(section)
continue
if role is None:
continue
ids_by_name.setdefault(role.casefold(), set()).add(owner)
for sha1 in archives:
ballot = votes.setdefault(sha1, {})
if ballot is not None:
ballot.setdefault(role.casefold(), set()).add(key)
def _elect_boards(votes: dict[str, dict[str, set[str]] | None],
ids_by_name: dict[str, set[str]], db: dict) -> None:
_archive_boards.clear()
_board_names.clear()
for sha1, ballot in votes.items():
@@ -493,7 +519,6 @@ def _build_boards() -> None:
for sha1, board in list(_archive_boards.items()):
if system_name(board).casefold() not in _board_names:
del _archive_boards[sha1]
_boards_built[0] = True
def _machine_section(sys_id: str) -> tuple[str, str] | None:
@@ -638,8 +663,7 @@ def _render_yaml_value(
lines.append(f"{pad}- {field_text(None, item)}")
lines.append("")
elif isinstance(val, str) and "\n" in val:
for line in val.split("\n"):
lines.append(f"{pad}{line}")
lines.extend(f"{pad}{line}" for line in val.split("\n"))
else:
lines.append(f"{pad}{field_text(None, val)}")
+146 -77
View File
@@ -17,6 +17,7 @@ import re
import unicodedata
import urllib.parse
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass, field
from html import unescape
from pathlib import Path, PurePosixPath
@@ -539,6 +540,22 @@ def next_step(body: str) -> dict | None:
return {"link": link["url"], "label": re.sub(r"[*_`]", "", link["text"]).strip()}
@dataclass(frozen=True)
class PageMeta:
"""What render_page writes around a page body."""
level: str
weight: float | None
browser_title: str
description: str
structured: dict
terms: dict[str, str]
search: bool = True
logo: str = ""
parent: dict | None = None
authored: dict | None = None
words_by_page: Mapping[str, set[str]] | None = None
def finalize_page(
rel: str,
markdown: str,
@@ -555,6 +572,14 @@ def finalize_page(
authored: dict | None = None,
words_by_page: Mapping[str, set[str]] | None = None,
) -> tuple[str, str]:
"""render_page with the fields of PageMeta as keywords."""
return render_page(rel, markdown, PageMeta(
level=level, weight=weight, browser_title=browser_title, description=description,
structured=structured, terms=terms, search=search, logo=logo, parent=parent,
authored=authored, words_by_page=words_by_page))
def render_page(rel: str, markdown: str, meta: PageMeta) -> tuple[str, str]:
"""The Starlight file for a page body: its path under the content
collection and its text. *parent* ({label, link}, the link written
relative to the page) is the page a part page belongs to: the route
@@ -569,7 +594,19 @@ def finalize_page(
*words_by_page* holds the console words of every system page, by path
without extension: a console another page's words cover is written
once more, in `exact`."""
authored = authored or {}
authored = meta.authored or {}
title, body = _page_body(rel, markdown, meta.terms, authored, meta.words_by_page or {})
components = used_components(body)
stem = rel.rsplit(".", 1)[0]
if components:
body = _with_imports(mdx_safe(body), components, rel)
front = _page_front(rel, stem, body, title, authored, meta)
return stem + (".mdx" if components else ".md"), _front_matter(front) + body
def _page_body(rel: str, markdown: str, terms: dict[str, str], authored: dict,
words_by_page: Mapping[str, set[str]]) -> tuple[str, str]:
"""The page's title and its body, links rewritten and search fields added."""
title, title_id, body = split_title(markdown)
body = body.lstrip("\n")
body = rewrite_links(body, rel)
@@ -595,46 +632,68 @@ def finalize_page(
body += file_names_meta(body) + search_field("aliases", page_aliases(rel))
consoles = field_words(authored.get("consoles"))
body += search_field("consoles", consoles)
body += search_field("exact", covered_names(consoles, rel.rsplit(".", 1)[0], words_by_page or {}))
body += search_field("exact", covered_names(consoles, rel.rsplit(".", 1)[0], words_by_page))
body += search_field("terms", field_words(authored.get("terms")) + console_words(consoles))
components = used_components(body)
stem = rel.rsplit(".", 1)[0]
if components:
body = mdx_safe(body)
imports: dict[str, list[str]] = {}
for name in components:
imports.setdefault(COMPONENTS[name], []).append(name)
# Our own components are imported from src/, two levels above the
# content collection plus the page's own folders.
up = "../" * (rel.count("/") + 2)
body = "".join(f"import {{ {', '.join(names)} }} from '{source}';\n"
if source.startswith("@") else f"import {names[0]} from '{up}{source}';\n"
for source, names in imports.items()) + "\n" + body
front: dict = {"title": title or browser_title, "description": description}
return title, body
def _with_imports(body: str, components: list[str], rel: str) -> str:
imports: dict[str, list[str]] = {}
for name in components:
imports.setdefault(COMPONENTS[name], []).append(name)
# Our own components are imported from src/, two levels above the
# content collection plus the page's own folders.
up = "../" * (rel.count("/") + 2)
return "".join(f"import {{ {', '.join(names)} }} from '{source}';\n"
if source.startswith("@") else f"import {names[0]} from '{up}{source}';\n"
for source, names in imports.items()) + "\n" + body
def _page_front(rel: str, stem: str, body: str, title: str, authored: dict,
meta: PageMeta) -> dict:
level = meta.level
browser_title = meta.browser_title
structured = meta.structured
front: dict = {"title": title or browser_title, "description": meta.description}
# Starlight's slugger drops dots and plus signs: the address stays MkDocs'.
if re.search(r"[^a-z0-9_/-]", stem):
front["slug"] = stem
if level:
front["level"] = level
if logo:
front["logo"] = logo
if meta.logo:
front["logo"] = meta.logo
parent = meta.parent
if parent:
front["parent"] = {"label": str(parent["label"]),
"link": resolve(rel, str(parent["link"]))}
weight = authored.get("searchWeight", weight)
weight = authored.get("searchWeight", meta.weight)
if weight:
front["searchWeight"] = weight
toc = _table_of_contents(rel, body)
if toc is not None:
front["tableOfContents"] = toc
if not meta.search:
front["pagefind"] = False
_neighbours(front, rel, body, authored)
front["head"] = page_head(rel, level, front["title"], browser_title, structured)
if structured.get("dateModified"):
front["lastmod"] = str(structured["dateModified"])
return front
def _table_of_contents(rel: str, body: str) -> dict | bool | None:
if rel == NOT_FOUND:
front["tableOfContents"] = False
elif rel.startswith(CARD_PAGES):
return False
if rel.startswith(CARD_PAGES):
sections = len(re.findall(r"^## ", body, re.M))
# A page of cards under one or two headings has nothing to list, and
# the table of contents watches every block of the page to follow
# the reader: 2 x 430 ms of a phone's main thread on 400 cards.
front["tableOfContents"] = (
{"minHeadingLevel": 2, "maxHeadingLevel": 2} if sections > 2 else False)
if not search:
front["pagefind"] = False
return {"minHeadingLevel": 2, "maxHeadingLevel": 2} if sections > 2 else False
return None
def _neighbours(front: dict, rel: str, body: str, authored: dict) -> None:
step = next_step(body)
if rel == NOT_FOUND or not reads_in_order(rel):
front["prev"] = False
@@ -645,10 +704,6 @@ def finalize_page(
for side in ("prev", "next"):
if rel != NOT_FOUND and side in authored:
front[side] = _neighbour(rel, authored[side])
front["head"] = page_head(rel, level, front["title"], browser_title, structured)
if structured.get("dateModified"):
front["lastmod"] = str(structured["dateModified"])
return stem + (".mdx" if components else ".md"), _front_matter(front) + body
# Navigation
@@ -724,58 +779,73 @@ def sidebar(nav: list, present: set[str], anchors: dict[str, set[str]] | None =
`reading` is the order of the previous and next links, one list per run
of tabs read in sequence.
"""
anchors = anchors or {}
owner: dict[str, str] = {}
groups: dict[str, dict] = {}
def label_of(entry: object) -> str:
return next(iter(entry)) if isinstance(entry, dict) else ""
def overview_of(value: list) -> str | None:
return next((v for v in value if isinstance(v, str)), None)
def item(entry: object, topic: str, trail: tuple[str, ...], parent: str | None) -> dict | None:
if isinstance(entry, str):
owner[entry] = topic
return {"label": "Overview", "link": _sidebar_link(entry)} if entry in present else None
(label, value), = entry.items()
if isinstance(value, str):
if value.startswith("http"):
return {"label": label, "link": value}
owner[value] = topic
return {"label": label, "link": _sidebar_link(value)} if value in present else None
if "/" in label:
raise ValueError(f"a navigation group label holds a slash: {label!r}")
own = overview_of(value)
here = (*trail, label)
href = None
if own and own in present:
href = page_url(own)
elif parent and parent in present:
anchor = toc_slug(label)
if anchor in anchors.get(parent, set()):
href = f"{page_url(parent)}#{anchor}"
elif topic in PRUNED_TABS:
# Drawn as a link, it needs an address: the overview it
# sits under, never one of its own pages.
href = page_url(parent)
children = [child for child in (item(v, topic, here, own or parent) for v in value) if child]
if not children:
return None
groups["/".join(here)] = {"href": href, "prune": topic in PRUNED_TABS and href is not None,
"crumb": not by_initial(label, children)}
return {"label": label, "items": children, "collapsed": True}
walk = _NavWalk(present, anchors or {})
topics = []
for tab in nav:
(label, value), = tab.items()
topic = topic_id(label)
children = [child for child in (item(v, topic, (label,), overview_of(value)) for v in value)
children = [child for child in (walk.item(v, topic, (label,), _overview_of(value)) for v in value)
if child]
if children:
topics.append({"id": topic, "label": label, "link": next(_links(children))["link"],
"items": children})
extra = _unlisted_pages(walk.owner, present, topics)
return {"topics": topics, "options": {"topics": extra, "exclude": []},
"groups": walk.groups, "reading": _reading(nav, present)}
def _overview_of(value: list) -> str | None:
return next((v for v in value if isinstance(v, str)), None)
@dataclass
class _NavWalk:
"""The sidebar items of the navigation, the topic of each page it
lists, and the entry of each group in `groups`."""
present: set[str]
anchors: dict[str, set[str]]
owner: dict[str, str] = field(default_factory=dict)
groups: dict[str, dict] = field(default_factory=dict)
def item(self, entry: str | dict, topic: str, trail: tuple[str, ...],
parent: str | None) -> dict | None:
if isinstance(entry, str):
self.owner[entry] = topic
return {"label": "Overview", "link": _sidebar_link(entry)} if entry in self.present else None
(label, value), = entry.items()
if isinstance(value, str):
if value.startswith("http"):
return {"label": label, "link": value}
self.owner[value] = topic
return {"label": label, "link": _sidebar_link(value)} if value in self.present else None
if "/" in label:
raise ValueError(f"a navigation group label holds a slash: {label!r}")
own = _overview_of(value)
here = (*trail, label)
href = self._group_href(label, own, parent, topic)
children = [child for child in (self.item(v, topic, here, own or parent) for v in value) if child]
if not children:
return None
self.groups["/".join(here)] = {"href": href, "prune": topic in PRUNED_TABS and href is not None,
"crumb": not by_initial(label, children)}
return {"label": label, "items": children, "collapsed": True}
def _group_href(self, label: str, own: str | None, parent: str | None, topic: str) -> str | None:
if own and own in self.present:
return page_url(own)
if parent and parent in self.present:
anchor = toc_slug(label)
if anchor in self.anchors.get(parent, set()):
return f"{page_url(parent)}#{anchor}"
if topic in PRUNED_TABS:
# Drawn as a link, it needs an address: the overview it
# sits under, never one of its own pages.
return page_url(parent)
return None
def _unlisted_pages(owner: dict[str, str], present: set[str], topics: list[dict]) -> dict[str, list[str]]:
"""The pages each topic holds beyond the ones the navigation lists."""
votes: dict[str, dict[str, int]] = {}
for rel, topic in owner.items():
tally = votes.setdefault(rel.rpartition("/")[0], {})
@@ -804,16 +874,15 @@ def sidebar(nav: list, present: set[str], anchors: dict[str, set[str]] | None =
tally[topic] = tally.get(topic, 0) + count
for rel in unlisted:
folder = rel.rpartition("/")[0]
tally = votes.get(folder) or adopted.get(folder)
if tally:
topic = max(tally, key=tally.get)
chosen = votes.get(folder) or adopted.get(folder)
if chosen:
topic = max(chosen, key=chosen.__getitem__)
elif topics:
topic = topics[0]["id"]
else:
continue
extra.setdefault(topic, []).append("/" + (_sidebar_link(rel).strip("/") or "index"))
return {"topics": topics, "options": {"topics": extra, "exclude": []},
"groups": groups, "reading": _reading(nav, present)}
return extra
def _reading(nav: list, present: set[str]) -> list[list[dict]]:
+91 -67
View File
@@ -93,6 +93,11 @@ class _PageParser(HTMLParser):
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
data = {key: value or "" for key, value in attrs}
self._count(tag, data)
self._open(tag, data)
self._references(tag, data)
def _count(self, tag: str, data: dict[str, str]) -> None:
if tag not in ("script", "style"):
self.page.elements += 1
if tag in _LITERAL_TAGS:
@@ -106,6 +111,8 @@ class _PageParser(HTMLParser):
self.page.runtime_diagrams += 1
if tag == "script" and re.match(r"\s*(?:https?:)?//", data.get("src", "")):
self.page.remote_scripts.append(data["src"])
def _open(self, tag: str, data: dict[str, str]) -> None:
if tag == "html":
self.page.lang = data.get("lang", "")
elif tag == "title":
@@ -125,6 +132,7 @@ class _PageParser(HTMLParser):
self._jsonld_depth += 1
self._jsonld_parts = []
def _references(self, tag: str, data: dict[str, str]) -> None:
element_id = data.get("id")
if element_id is not None:
self.page.ids.append(element_id)
@@ -264,78 +272,94 @@ def _check_pages(
filled here for it.
"""
issues: list[str] = []
def report(path: Path, message: str) -> None:
issues.append(f"{path.relative_to(site)}: {message}")
for path, page in pages.items():
is_404 = path.relative_to(site) == Path("404.html")
if not page.title:
report(path, "missing document title")
elif not is_404:
titles[page.title].append(path)
if page.lang != "en":
report(path, f"expected lang='en', got {page.lang!r}")
if len(page.descriptions) != 1 or not page.descriptions[0]:
report(path, f"expected one non-empty description, got {len(page.descriptions)}")
elif not is_404:
descriptions[page.descriptions[0]].append(path)
if not is_404 and page.h1_count != 1:
report(path, f"expected one H1, got {page.h1_count}")
if page.main_count != 1:
report(path, f"expected one main landmark, got {page.main_count}")
if not is_404 and (
len(page.canonical) != 1
or not page.canonical[0].startswith("https://")
):
report(path, f"expected one HTTPS canonical URL, got {page.canonical!r}")
duplicate_ids = [
value
for value, count in Counter(page.ids).items()
if value and count > 1
rel = path.relative_to(site)
is_404 = rel == Path("404.html")
messages = [
*_document_issues(path, page, is_404, titles, descriptions),
*_content_issues(page, rel.as_posix()),
*_jsonld_issues(page, is_404),
]
if duplicate_ids:
report(path, f"duplicate IDs: {duplicate_ids[:5]}")
if page.missing_alt:
report(path, f"images missing alt: {page.missing_alt[:5]}")
if page.remote_images:
report(path, f"images loaded from another host: {page.remote_images[:3]}")
if page.remote_scripts:
report(path, f"scripts loaded from another host: {page.remote_scripts[:3]}")
if page.runtime_diagrams:
report(path, f"{page.runtime_diagrams} diagram(s) drawn by a script at runtime")
if page.size > MAX_PAGE_BYTES:
report(path, f"{page.size:,} bytes of HTML, over the {MAX_PAGE_BYTES:,} budget")
if page.elements > MAX_PAGE_ELEMENTS \
and path.relative_to(site).as_posix() not in OVER_ELEMENT_BUDGET:
report(path, f"{page.elements:,} elements, over the {MAX_PAGE_ELEMENTS:,} budget")
jumps = _heading_jumps(page.headings)
if jumps:
report(path, f"heading levels skipped: {sorted(set(jumps))}")
if page.empty_headers:
report(path, f"{page.empty_headers} table header cell(s) without text")
if page.placeholders:
# scripts/sitediagrams.py knows no diagram of this name.
report(path, f"image placeholders left unresolved: {page.placeholders[:3]}")
if page.unrendered:
# Bold that reached the reader as asterisks: a block indented
# one level too deep is read as code (the clownmdemu analysis).
report(path, f"markdown left unrendered: {page.unrendered[:3]}")
if not is_404 and len(page.jsonld) != 1:
report(path, f"expected one JSON-LD block, got {len(page.jsonld)}")
for document in page.jsonld:
try:
payload = json.loads(document)
except json.JSONDecodeError as exc:
report(path, f"invalid JSON-LD: {exc}")
continue
if not isinstance(payload, dict) or payload.get("@context") != "https://schema.org":
report(path, "JSON-LD is not a schema.org object")
issues.extend(f"{rel}: {message}" for message in messages)
return issues
def _document_issues(path: Path, page: Page, is_404: bool, titles: dict, descriptions: dict) -> list[str]:
"""The head and landmarks: title, language, description, H1, main, canonical."""
messages = []
if not page.title:
messages.append("missing document title")
elif not is_404:
titles[page.title].append(path)
if page.lang != "en":
messages.append(f"expected lang='en', got {page.lang!r}")
if len(page.descriptions) != 1 or not page.descriptions[0]:
messages.append(f"expected one non-empty description, got {len(page.descriptions)}")
elif not is_404:
descriptions[page.descriptions[0]].append(path)
if not is_404 and page.h1_count != 1:
messages.append(f"expected one H1, got {page.h1_count}")
if page.main_count != 1:
messages.append(f"expected one main landmark, got {page.main_count}")
if not is_404 and (
len(page.canonical) != 1
or not page.canonical[0].startswith("https://")
):
messages.append(f"expected one HTTPS canonical URL, got {page.canonical!r}")
return messages
def _content_issues(page: Page, rel: str) -> list[str]:
messages = []
duplicate_ids = [
value
for value, count in Counter(page.ids).items()
if value and count > 1
]
if duplicate_ids:
messages.append(f"duplicate IDs: {duplicate_ids[:5]}")
if page.missing_alt:
messages.append(f"images missing alt: {page.missing_alt[:5]}")
if page.remote_images:
messages.append(f"images loaded from another host: {page.remote_images[:3]}")
if page.remote_scripts:
messages.append(f"scripts loaded from another host: {page.remote_scripts[:3]}")
if page.runtime_diagrams:
messages.append(f"{page.runtime_diagrams} diagram(s) drawn by a script at runtime")
if page.size > MAX_PAGE_BYTES:
messages.append(f"{page.size:,} bytes of HTML, over the {MAX_PAGE_BYTES:,} budget")
if page.elements > MAX_PAGE_ELEMENTS and rel not in OVER_ELEMENT_BUDGET:
messages.append(f"{page.elements:,} elements, over the {MAX_PAGE_ELEMENTS:,} budget")
jumps = _heading_jumps(page.headings)
if jumps:
messages.append(f"heading levels skipped: {sorted(set(jumps))}")
if page.empty_headers:
messages.append(f"{page.empty_headers} table header cell(s) without text")
if page.placeholders:
# scripts/sitediagrams.py knows no diagram of this name.
messages.append(f"image placeholders left unresolved: {page.placeholders[:3]}")
if page.unrendered:
# Bold that reached the reader as asterisks: a block indented
# one level too deep is read as code (the clownmdemu analysis).
messages.append(f"markdown left unrendered: {page.unrendered[:3]}")
return messages
def _jsonld_issues(page: Page, is_404: bool) -> list[str]:
messages = []
if not is_404 and len(page.jsonld) != 1:
messages.append(f"expected one JSON-LD block, got {len(page.jsonld)}")
for document in page.jsonld:
try:
payload = json.loads(document)
except json.JSONDecodeError as exc:
messages.append(f"invalid JSON-LD: {exc}")
continue
if not isinstance(payload, dict) or payload.get("@context") != "https://schema.org":
messages.append("JSON-LD is not a schema.org object")
return messages
def description_template(page: Page, site_name: str = "RetroBIOS") -> str:
"""A page's description with its own names taken out: its h1 and its
window title. What is left is the text it shares with its template."""