#!/usr/bin/env python3 """Build and drift-check the Impossible OS website and documentation site. One generator owns every published surface, so no fact is maintained in two places by hand: * ``project.json`` is the single source of truth for project facts (owner, repository URL, site URL, release date). The landing page templates under ``gh-pages/`` reference them as ``{{key}}``; Markdown files carry them in ``value`` regions that stay readable on GitHub and are rewritten by ``--sync``. * ``docs/**/*.md`` is rendered to ``/docs/`` with a generated navigation tree, per-page table of contents, client-side search index, and a documentation-coverage page computed from ```` directives against every ``todo/**/TODO-*.md`` file. Modes: (default) build the site into build/site/ (never committed) --check build in memory and fail on any drift: stale project regions, dead doc links, a README line-count badge that disagrees with COUNT.md, an unknown owner in a live repo URL, or a documentation-coverage baseline that is stale or missing a new undocumented TODO --sync rewrite project regions in tracked Markdown in place --update-baseline SHRINK the coverage baseline (never adds entries) --release REF render only the docs tree as it was at commit REF into /docs//, every link to main or to REF itself pinned to REF's full SHA (keeping release trees published is roadmap work) Stdlib plus the vendored markdown-it-py under tools/vendor/, so the output is identical on every host and in CI. Deterministic: stable ordering, no timestamps. """ from __future__ import annotations import argparse from html.parser import HTMLParser import datetime as _dt import hashlib import html import html.entities import json import os import posixpath import re import shlex import shutil import subprocess import sys import tempfile import unicodedata from urllib.parse import parse_qs, quote, unquote, urlsplit from dataclasses import dataclass, field from pathlib import Path REPO = Path(__file__).resolve().parents[2] # the real checkout; every git call runs here ROOT = REPO # where inputs are READ; set_root() moves it to a snapshot sys.path.insert(0, str(REPO / "tools" / "vendor")) sys.path.insert(0, str(REPO / "scripts")) import todo_fence # noqa: E402 (the shared `## N.` heading rule) from markdown_it import MarkdownIt # noqa: E402 (vendored, path set above) from markdown_it.token import Token # noqa: E402 PROJECT_FILE = ROOT / "project.json" SITE_SRC = ROOT / "gh-pages" DOCS = ROOT / "docs" TODO = ROOT / "todo" BASELINE = DOCS / ".coverage-baseline.json" DEFAULT_OUT = REPO / "build" / "site" # What the site reads. A snapshot (--staged, --emit-readme) materialises only these # plus every tracked *.md, so a check judges exactly what a commit contains. SNAP_PATHS = ["project.json", "COUNT.md", "docs", "todo", "gh-pages", "resources/icons/src", "resources/brand", "resources/backgrounds", "resources/icons/color", "include/desktop/theme_tokens.h", "*.md"] SOURCE = "worktree" # "worktree" | "index" | a commit ref # Release rendering (--release). The defaults reproduce the main-branch site byte # for byte; a release build pins every repository link to the release commit and # publishes under docs// instead of docs/. LINK_REF = "main" # the git ref every blob/tree/raw link names DOCS_BASE = "docs/" # site path the docs tree is published under RELEASE: str | None = None # the version path segment(s) of a release build VERSION_SEGMENT_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*") PUBLISH_KEYS = ("site_url", "docs_url", "repo_url", "owner", "repo") _FILESET: set[str] | None = None _DIRSET: set[str] | None = None # Every git call the site build makes is local and finishes in well under a second # on this repository; the limit turns a hung git (a stuck lock, a wedged filesystem) # into a failed build instead of a job held until its workflow limit (check_nets.py). GIT_TIMEOUT = 300 NODE_TIMEOUT = 120 def git(*args: str, binary: bool = False): out = subprocess.run(["git", *args], cwd=REPO, check=True, capture_output=True, timeout=GIT_TIMEOUT).stdout return out if binary else out.decode() def has_commit(ref: str) -> bool: """Whether REF resolves to a commit. False does not say why: see commit_state().""" return subprocess.run(["git", "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], cwd=REPO, capture_output=True, timeout=GIT_TIMEOUT).returncode == 0 def commit_state(ref: str) -> str: """"ok" when REF (HEAD or HEAD~1) resolves to a commit, "unborn" when HEAD's branch has no commit yet, "root" when HEAD is a root commit so HEAD~1 has nothing to name. Each absence is PROVED from the repository, never inferred from a failed lookup: a shallow boundary or an unreadable object raises RuntimeError, because reading it as "nothing came before" would switch off every check that compares against the previous commit.""" if has_commit(ref): return "ok" if ref == "HEAD": branch = subprocess.run(["git", "symbolic-ref", "-q", "HEAD"], cwd=REPO, capture_output=True, text=True, timeout=GIT_TIMEOUT).stdout.strip() if branch and subprocess.run(["git", "show-ref", "--verify", "--quiet", branch], cwd=REPO, capture_output=True, timeout=GIT_TIMEOUT).returncode == 1: return "unborn" raise RuntimeError("HEAD does not resolve to a readable commit") if ref == "HEAD~1" and has_commit("HEAD"): if git("rev-parse", "--is-shallow-repository").strip() == "true": raise RuntimeError("this shallow clone lacks HEAD~1; fetch full history (actions/checkout fetch-depth: 0)") header = git("cat-file", "commit", "HEAD").split("\n\n", 1)[0] if not any(line.startswith("parent ") for line in header.splitlines()): return "root" raise RuntimeError("HEAD names a parent that git cannot read") raise RuntimeError(f"{ref} does not resolve to a readable commit") def fileset() -> tuple[set[str], set[str]]: """Repo-relative files that exist in SOURCE, and their parent directories. Link existence is judged against this, never the filesystem, so an ignored local artifact (build/...) can never satisfy a link.""" global _FILESET, _DIRSET if _FILESET is None: if SOURCE == "worktree": raw = git("ls-files", "-z", "--cached", "--others", "--exclude-standard") elif SOURCE == "index": raw = git("ls-files", "-z") else: raw = git("ls-tree", "-r", "-z", "--name-only", SOURCE) files = {p for p in raw.split("\0") if p} if SOURCE == "worktree": files = {p for p in files if (REPO / p).exists()} dirs: set[str] = set() for f in files: parts = f.split("/") for i in range(1, len(parts)): dirs.add("/".join(parts[:i])) _FILESET, _DIRSET = files, dirs return _FILESET, _DIRSET # type: ignore[return-value] def set_root(root: Path) -> None: global ROOT, PROJECT_FILE, SITE_SRC, DOCS, TODO, BASELINE, _TRACKED ROOT = root _TRACKED = None PROJECT_FILE, SITE_SRC, DOCS, TODO = root / "project.json", root / "gh-pages", root / "docs", root / "todo" BASELINE = DOCS / ".coverage-baseline.json" sys.path.insert(0, str(REPO / "scripts" / "site")) import gen_theme_header as g # noqa: E402 (sibling module) g.ROOT, g.TOKENS, g.HEADER = root, root / "docs" / "design" / "tokens.json", root / "include" / "desktop" / "theme_tokens.h" # The freshness module is handed this build's repository where it is used (tracked_sources, the build); # a root set again puts it back with the rest, so no earlier build's checkout outlives its own root. if "freshness" in sys.modules: sys.modules["freshness"].REPO = REPO DOC_FACTS: tuple[int, set[str]] | None = None # page count and covered TODOs of a snapshot limited to some paths def directive_covers(text: str) -> set[str]: return {c.strip() for c in parse_directives(text).get("covers", "").split(",") if c.strip()} # What --emit-readme reads: the facts' inputs and README.md. README_PATHS = ["project.json", "COUNT.md", "README.md", "docs/*.md", "docs/design/tokens.json", "docs/test-coverage/coverage.json"] def snapshot(source: str, paths: list[str] | None = None) -> Path: """Materialise the site inputs from the index ("index") or a commit into a temp dir.""" global SOURCE, _FILESET, _DIRSET, DOC_FACTS SOURCE, _FILESET, _DIRSET, DOC_FACTS = source, None, None, None tmp = Path(tempfile.mkdtemp(prefix="site-snap-")) try: _materialise(source, paths, tmp) except BaseException: shutil.rmtree(tmp, ignore_errors=True) raise set_root(tmp) return tmp def _materialise(source: str, paths: list[str] | None, tmp: Path) -> None: import fnmatch global DOC_FACTS global _FILESET, _DIRSET pages = 0 covered: set[str] = set() blobs: dict[str, str] = {} # the ids already read, so cat-file resolves no path again if paths is not None: # only names these can match, and the TODO names load_stats counts raw = git("ls-tree", "-r", "-z", source, "--", "todo", *sorted({p.split("/")[0] for p in paths})) blobs = {path: entry.split()[2] for entry, path in (e.split("\t", 1) for e in raw.split("\0") if e)} _FILESET, _DIRSET = set(blobs), set() files, _ = fileset() want = sorted(f for f in files if any( f == p or f.startswith(p + "/") or ("*" in p and fnmatch.fnmatchcase(f, p)) for p in (SNAP_PATHS if paths is None else paths))) if source == "index": subprocess.run(["git", "checkout-index", "-z", "--stdin", f"--prefix={tmp}/"], cwd=REPO, check=True, input="\0".join(want).encode(), capture_output=True, timeout=GIT_TIMEOUT) else: # One `git cat-file --batch` for every blob instead of a `git show` per file # (measured: 797 processes / 3.2 s down to one process / ~0.5 s). proc = subprocess.run(["git", "cat-file", "--batch"], cwd=REPO, check=True, capture_output=True, input="".join(blobs.get(f, f"{source}:{f}") + "\n" for f in want).encode(), timeout=GIT_TIMEOUT) out, pos = proc.stdout, 0 for f in want: nl = out.index(b"\n", pos) header = out[pos:nl].split() if len(header) != 3: raise RuntimeError(f"snapshot: cannot read {source}:{f}") size = int(header[2]) data = out[nl + 1:nl + 1 + size] pos = nl + 1 + size + 1 if paths is not None and f.startswith("docs/") and f.endswith(".md"): pages += 1 covered |= directive_covers(data.decode("utf-8")) continue # load_stats needs no more of it dest = tmp / f dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) if paths is not None: DOC_FACTS = pages, covered TEMPLATE_EXTS = {".html", ".js", ".css", ".json", ".xml", ".txt", ".svg", ""} # parser-allow: this repo's own project-region markers, rewritten in place by --sync byte for byte REGION_RE = re.compile(r"(?(.*?)", re.S) # not inside `code` TEMPLATE_RE = re.compile(r"\{\{([a-z_]+)\}\}") # parser-allow: this repo's own `` page directive, read from the Markdown source DIRECTIVE_RE = re.compile(r"", re.S) # parser-allow: finds repository mentions in any text, links or not (a clone command in a code block) REPO_URL_RE = re.compile(r"github\.com/([A-Za-z0-9-]+)/impossible-os\b") # -------------------------------------------------------------------------- # Project facts # -------------------------------------------------------------------------- def load_project() -> dict[str, str]: raw = json.loads(PROJECT_FILE.read_text(encoding="utf-8")) d = _dt.date.fromisoformat(raw["release_date"]) facts = {k: v for k, v in raw.items() if isinstance(v, str)} facts["release_date_long"] = f"{d.strftime('%B')} {d.day}, {d.year}" facts["release_date_ts"] = f"{raw['release_date']}T00:00:00Z" facts["release_year"] = str(d.year) facts["_historical_owners"] = raw.get("historical_owners", []) facts["_historical_owner_files"] = raw.get("historical_owner_files", []) facts["_gtm_id"] = raw.get("gtm_id") facts.update(load_stats()) facts.update(load_materials()) return facts MATERIAL_ROWS = ("taskbar", "start", "flyout", "menu", "frame") def load_materials() -> dict[str, str]: """The cells of the Materials table in docs/design/shell.md (``mat_*``), from docs/design/tokens.json, so the specification cannot state a glass value the tokens do not hold. The tint differs by theme; every other value is one number for both, and a token file where they differ is refused.""" tokens = DOCS / "design" / "tokens.json" if not tokens.is_file(): return {} # fail-direction: a tree without the design tokens has no mat_* keys, so a region that names one is an unknown-key error t = json.loads(tokens.read_text(encoding="utf-8")) mat = t["material"] if "glass" not in t: return {} # a release from before the glass tokens has no mat_* regions in its pages to fill out: dict[str, str] = {} for surface in MATERIAL_ROWS: dark, light = mat["dark"][surface], mat["light"][surface] for name in ("blur", "saturate", "edge", "noise"): if dark[name] != light[name]: raise SystemExit(f"docs/design/tokens.json: material {surface} {name} differs between dark and light " f"({dark[name]} and {light[name]}); the specification states one value") out[f"mat_{surface}_dark"] = f"`{dark['tint']}` at {dark['tint_opacity']}/255" out[f"mat_{surface}_light"] = f"`{light['tint']}` at {light['tint_opacity']}/255" out[f"mat_{surface}_blur"] = str(dark["blur"]) out[f"mat_{surface}_saturate"] = f"{dark['saturate']}%" out[f"mat_{surface}_edge"] = f"{dark['edge']}%" out[f"mat_{surface}_grain"] = f"{dark['noise']}%" out.update(glass_cells(t)) return out SHELL_SURFACES = ("taskbar", "start", "flyout", "menu") def glass_material(t: dict, theme: str, surface: str, strength: str | None) -> dict: """One surface's material at a glass strength: the balanced recipe of ``material`` with the strength's adjustments added (tokens.json ``glass``). ``material`` is the only place the balanced values are written, so the default strength must adjust nothing. ``strength`` None is a token file from before the glass block: the material as written.""" spec = dict(t["material"][theme][surface]) if strength is None: return spec adj = t["glass"]["strengths"][strength] if strength == t["glass"]["default"] and any(v for k, v in adj.items() if k != "setting"): raise SystemExit(f"docs/design/tokens.json: glass strength {strength} is the default, so its adjustments are all 0; " "the balanced values are written in material") part = "frame" if surface == "frame" else "shell" spec["tint_opacity"] = max(0, min(255, spec["tint_opacity"] + adj[f"{part}_tint_opacity"])) spec["blur"] = max(0, spec["blur"] + adj[f"{part}_blur"]) spec["saturate"] = max(0, spec["saturate"] + adj["saturate"]) spec["edge"] = max(0, min(100, spec["edge"] + adj["edge"])) return spec def glass_cells(t: dict) -> dict[str, str]: """The cells of the glass strength table in docs/design/shell.md (``glass_*``): the frame and the taskbar at each strength, worked out from the tokens.""" out: dict[str, str] = {} for name, adj in t["glass"]["strengths"].items(): frame, bar = glass_material(t, "dark", "frame", name), glass_material(t, "dark", "taskbar", name) out[f"glass_{name}_setting"] = str(adj["setting"]) + (" (default)" if name == t["glass"]["default"] else "") out[f"glass_{name}_frame"] = f"blur {frame['blur']}, tint {frame['tint_opacity']}/255" out[f"glass_{name}_taskbar"] = f"blur {bar['blur']}, tint {bar['tint_opacity']}/255" out[f"glass_{name}_saturate"] = f"{frame['saturate']}%" out[f"glass_{name}_edge"] = f"{frame['edge']}%" return out def load_stats() -> dict[str, str]: """Computed repository facts (``stat_*``). They move with ordinary work, so the post-commit hook re-syncs README.md after every commit and the pre-commit lint skips them (--skip-stats); CI still checks them.""" todos = todo_files() domains = {t.split("/")[1] for t in todos} pages, covered = DOC_FACTS or (0, set()) if DOC_FACTS is None: for d in DOCS.rglob("*.md"): pages += 1 covered |= directive_covers(d.read_text(encoding="utf-8")) cov = json.loads((DOCS / "test-coverage" / "coverage.json").read_text(encoding="utf-8")) m = COUNT_TOTAL_RE.search((ROOT / "COUNT.md").read_text(encoding="utf-8")) lines = int(m.group(1)) if m else 0 return { "stat_todo_files": str(len(todos)), "stat_todo_domains": str(len(domains)), "stat_doc_pages": str(pages), "stat_docs_covered": str(len(covered & set(todos))), "stat_test_suites": f"{cov['total_suites']:,}", "stat_test_assertions": f"{cov['total_assertions']:,}", # The same exact whole-tree total the README badge shows. "stat_lines": f"{lines:,}", } def render_template(text: str, facts: dict, where: str, errors: list[str]) -> str: def sub(m: re.Match) -> str: key = m.group(1) if key not in facts or key.startswith("_"): errors.append(f"{where}: unknown template key {{{{{key}}}}}") return m.group(0) return facts[key] return TEMPLATE_RE.sub(sub, text) def sync_regions(text: str, facts: dict, where: str, errors: list[str]) -> str: def sub(m: re.Match) -> str: key = m.group(1) if key not in facts or key.startswith("_"): errors.append(f"{where}: unknown project region key '{key}'") return m.group(0) return f"{facts[key]}" return REGION_RE.sub(sub, text) def tracked_files(*pathspecs: str) -> list[Path]: """Files in SOURCE matching pathspecs, as paths under ROOT (the snapshot when one is active).""" import fnmatch files, _ = fileset() return [ROOT / f for f in sorted(files) if any(fnmatch.fnmatch(f, p) for p in pathspecs)] # -------------------------------------------------------------------------- # Markdown rendering # -------------------------------------------------------------------------- def github_slug(text: str) -> str: """GitHub's heading id rule: lowercase, keep word characters as Ruby's `\\p{Word}` defines them (letters, combining marks, decimal digits, connector punctuation such as `_`), hyphens and spaces, drop everything else, then turn spaces into hyphens. Nothing is trimmed: a heading ending in ` ` keeps its trailing hyphen, as on github.com.""" out = [] for ch in text.lower(): cat = unicodedata.category(ch) if ch in "- " or cat[0] in "LM" or cat in ("Nd", "Pc"): out.append(ch) return "".join(out).replace(" ", "-") class Slugger: """GitHub's heading ids (github-slugger): a repeated slug takes the first free `-N` suffix and every id handed out is reserved, so the headings `Foo`, `Foo`, `Foo-1` get `foo`, `foo-1`, `foo-1-1`.""" def __init__(self) -> None: self.seen: dict[str, int] = {} def slug(self, text: str) -> str: base = s = github_slug(text) while s in self.seen: self.seen[base] += 1 s = f"{base}-{self.seen[base]}" self.seen[s] = 0 return s class _AnchorParser(HTMLParser): """`id` and `name` of tags in raw HTML, any attribute order or quoting; HTMLParser skips comments, so a commented-out anchor is not an anchor.""" def __init__(self) -> None: super().__init__(convert_charrefs=True) self.found: set[str] = set() def handle_starttag(self, tag, attrs): if tag == "a": a = first_attrs(attrs) self.found.update(v for v in (a.get("id"), a.get("name")) if v) handle_startendtag = handle_starttag # Raw HTML in docs pages is an ALLOWLIST, not a list of known-bad shapes: every # denylist round found another construct that hides a link from the checker # (srcset, srcdoc, CSS url(), foreign content). Links go through `href` on # and `src` on , which the rewriter validates and pins; the other allowed # attributes carry no URL. The corpus used none of what this refuses (surveyed # 2026-09-29: no raw HTML attributes at all outside comments). RAW_HTML_LINK_ATTRS = {"a": "href", "img": "src"} RAW_HTML_ATTRS = frozenset({ "alt", "title", "id", "name", "class", "width", "height", "align", "valign", "border", "open", "colspan", "rowspan", "scope", "headers", "start", "reversed", "type", "lang", "dir", "role", "hidden"}) # Every element that takes the HTML tokenizer out of normal parsing, per the # HTML Standard's "in body" insertion mode: RCDATA (title, textarea), RAWTEXT # (style, xmp, iframe, noembed, noframes, and noscript when scripting is on), # script data (script), PLAINTEXT (plaintext), and the foreign-content roots # (svg, math). Inside any of them a browser and html.parser can disagree about # where markup is, so the set is closed by the standard, not by examples. RAW_HTML_REFUSED_TAGS = { **dict.fromkeys(("title", "textarea"), "RCDATA text"), **dict.fromkeys(("style", "xmp", "iframe", "noembed", "noframes", "noscript"), "raw text"), "script": "script code", "plaintext": "plain text to the end of the page", "svg": "foreign content", "math": "foreign content"} def url_scheme(url: str) -> str: """The scheme a link names ("https", "mailto"; "" for a path relative to the page), by urlsplit's reading of RFC 3986's scheme grammar (a letter, then letters, digits, `+`, `-` or `.`), lower-cased as browsers read it: `1:x.md` and `+x:y.png` are relative paths. urlsplit validates the authority too and raises on a malformed one (`http://[broken`); that URL still names its scheme, so the part before the authority is read on its own.""" try: return urlsplit(url).scheme except ValueError: return urlsplit(url.partition("//")[0] + "//").scheme def has_scheme(url: str) -> bool: return bool(url_scheme(url)) _C0_OR_SPACE = "".join(chr(c) for c in range(0x21)) def browser_url_input(url: str) -> str: """`url` after the WHATWG URL parser's first steps: leading and trailing C0 controls and spaces stripped, every ASCII tab, LF and CR removed. What a browser does before it reads the scheme, so a policy on schemes must see this form, not the attribute value as written.""" return url.strip(_C0_OR_SPACE).replace("\t", "").replace("\n", "").replace("\r", "") _LEGACY_REFS = frozenset(k for k in html.entities.html5 if not k.endswith(";")) _LEGACY_MAX = max(map(len, _LEGACY_REFS)) # 6 (`middot`): no longer prefix can match def ambiguous_charref(raw: str) -> str: """The first named character reference in `raw` that html.unescape decodes but a browser, inside an attribute value, keeps as text ("" when none). Both decode `&name;`; without the `;`, html.unescape also decodes the longest legacy prefix (`©`, `¬`), while the HTML Standard's character-reference state leaves an unterminated reference alone in an attribute when the next character is alphanumeric or `=` (`?a=1©=2`, `¬it;`). html.parser decodes attribute values with html.unescape, so a tag the rewriter re-serializes from them would change.""" i = raw.find("&") while i != -1: j = i + 1 while j < len(raw) and raw[j].isascii() and raw[j].isalnum(): j += 1 name = raw[i + 1:j] if name and not (raw[j:j + 1] == ";" and len(name) < 64 and name + ";" in html.entities.html5): for k in range(min(len(name), _LEGACY_MAX), 0, -1): if name[:k] in _LEGACY_REFS: after = raw[i + 1 + k:i + 2 + k] if (after.isascii() and after.isalnum()) or after == "=": return raw[i:j + 1] if raw[j:j + 1] == ";" else raw[i:j] break i = raw.find("&", i + 1) return "" class _RawAttrs(HTMLParser): """What Renderer.rewrite_raw_html rewrites, read from a raw HTML fragment the way a browser does. `links` holds every / start tag with its character offset, its source text and its parsed attributes, so the rewriter replaces exactly the tags the parser saw (text inside \n" f'' ) ASSET_DIRS = ( ("resources/icons/src", "icons", (".svg",)), ("resources/brand", "brand", (".svg", ".png")), ("resources/backgrounds", "wallpapers", (".jpg",)), ) # Which index a docs template reads, named by the template itself. A release # tree is rendered with ITS OWN template, so every layout ever shipped stays # emittable. There is one URL, search.json, and it carries one schema at a time: # flat no marker: the [{t,u,h,x}] index (templates before section 25) # v2 data-search-index="2": the sharded v2 manifest (since commit c73146aa3) # A page holding a cached copy of the other schema recovers on its next typed # search, which revalidates the manifest after a failed load. SEARCH_LAYOUTS = (('data-search-index="2"', "v2"),) SEARCH_BUDGET = 2 * 1024 * 1024 # bytes, per file: the v2 manifest and every shard SEARCH_SHARD_TARGET = 512 * 1024 # a shard is cut once it would pass this def search_layout(template: str) -> str: return next((layout for mark, layout in SEARCH_LAYOUTS if mark in template), "flat") def _json_bytes(value) -> bytes: return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8") def search_files(pages: dict[str, Page], layout: str, errors: list[str]) -> dict[str, bytes]: """The client-side search index for a template's layout (search_layout()), as {path under the docs root: bytes}. The v2 manifest lists pages and sections, [page index, anchor, heading path], with the full text of each section in shards named by their content hash. It names every shard with its record count, so a manifest and a shard from different builds can never be read together: a stale manifest names shards the new deploy does not have, and the client refuses a count that does not add up. Nothing in v2 is dropped to meet the budget; a v2 file over it fails the build. The flat index, for a release tree whose template predates v2, cuts each page at 4,000 characters exactly as that template was published with; it is not held to the v2 budget, since it must render the old tree as it was.""" ordered = sorted(pages.values(), key=lambda p: p.rel) if layout == "flat": return {"search.json": _json_bytes([{"t": p.title, "u": p.url or "./", "h": [t for _, _, t in p.toc], "x": p.text[:4000]} for p in ordered])} out: dict[str, bytes] = {} plist: list[list[str]] = [] sections: list[list] = [] shards: list[list[str]] = [[]] size = 0 for n, page in enumerate(ordered): plist.append([page.title, page.url or "./"]) for anchor, path, text in page.records: sections.append([n, anchor, path]) cost = len(_json_bytes(text)) + 1 if shards[-1] and size + cost > SEARCH_SHARD_TARGET: shards.append([]) size = 0 shards[-1].append(text) size += cost names: list[list] = [] for shard in shards: if not shard: continue data = _json_bytes(shard) name = f"search-{hashlib.sha256(data).hexdigest()[:16]}.json" out[name] = data names.append([name, len(shard)]) out = {"search.json": _json_bytes({"v": 2, "p": plist, "s": sections, "shards": names}), **out} for name, data in out.items(): if len(data) > SEARCH_BUDGET: errors.append(f"search index {name} is {len(data):,} bytes, over the {SEARCH_BUDGET:,}-byte budget " f"(content is never dropped to fit; cut more shards or split the page)") return out def build(facts: dict, errors: list[str]) -> dict[str, bytes]: """Return {site-relative path: bytes} for the whole site.""" files: dict[str, bytes] = {} sources: dict[str, str] = {} # site path -> the tracked file it is rendered from ("" = generated) # A release build publishes its docs tree only; the landing pages, assets, # sitemap and robots.txt belong to the main site. landing = RELEASE is None facts = dict(facts, design_tokens_css=design_tokens_css()) if landing else dict(facts) # A retained release is frozen, so analytics in it could never be switched off. facts["analytics_head"] = analytics_head(gtm_container(facts, errors)) if landing else "" # Only when a template uses it: a snapshot of an older tree has no features.json. if landing and any("{{feature_cards}}" in f.read_text(encoding="utf-8", errors="replace") for f in SITE_SRC.rglob("*.html")): facts["feature_cards"] = feature_cards(facts, errors) for src_dir, dest, exts in (ASSET_DIRS if landing else ()): base = ROOT / src_dir if base.is_dir(): for f in sorted(base.iterdir()): if f.is_file() and f.suffix in exts: files[f"{dest}/{f.name}"] = f.read_bytes() # 1. Landing site templates. for src in (sorted(SITE_SRC.rglob("*")) if landing else ()): if src.is_dir(): continue rel = src.relative_to(SITE_SRC).as_posix() data = src.read_bytes() if src.suffix in TEMPLATE_EXTS and rel not in ("docs-template.html",): data = render_template(data.decode("utf-8"), facts, f"gh-pages/{rel}", errors).encode("utf-8") if rel not in ("docs-template.html", FEATURES_FILE): files[rel] = data sources[rel] = f"gh-pages/{rel}" # 2. Docs. pages, _ = load_pages(facts, errors) covered, undocumented = coverage(pages, errors) if landing: # Roadmap and sources= hygiene judge the CURRENT commit; a release is # published as it was, so only rendering errors (dead links, images, # anchors, unknown covers=) fail a release build. check_design_lines(pages, errors) for page in pages.values(): check_sources(f"docs/{page.rel}", page.sources, errors) import freshness freshness.REPO = REPO page_sources = {f"docs/{p.rel}": p.sources for p in pages.values() if p.sources} if SOURCE in ("worktree", "index") and freshness.merging(): page_sources = freshness.with_head_sources( page_sources, [f"docs/{p.rel}" for p in pages.values()], directive_sources, SOURCE) records = freshness.check_all(page_sources, SOURCE) build.freshness = records # type: ignore[attr-defined] cov = coverage_page(pages, covered, records) tpl = render_template((SITE_SRC / "docs-template.html").read_text(encoding="utf-8"), facts, "gh-pages/docs-template.html", errors) all_pages = dict(pages) all_pages[cov.rel] = cov found = results_page(tpl, pages, errors) dates = last_updated() build.shallow = dates is None # type: ignore[attr-defined] dates = dates or {} for page in all_pages.values(): out = out_path(page.url) updated = "" if page is cov else dates.get(f"docs/{page.rel}", "") rendered = render_page(tpl, facts, all_pages, page, updated) rendered = render_template(rendered, facts, f"docs/{page.rel}", []) if page is cov else rendered files[f"{DOCS_BASE}{out}"] = rendered.encode("utf-8") sources[f"{DOCS_BASE}{out}"] = "" if page is cov else f"docs/{page.rel}" if found: # Rendered against the pages it searches, and so absent from their navigation. files[f"{DOCS_BASE}{found.url}"] = render_page(tpl, facts, all_pages, found).encode("utf-8") sources[f"{DOCS_BASE}{found.url}"] = "" if landing: for name in ("sitemap.xml", "robots.txt"): if name in files: errors.append(f"gh-pages/{name}: generated by build.py; remove the hand-written copy") files["sitemap.xml"] = sitemap(facts, files, sources, dates) files["robots.txt"] = (f"User-agent: *\nAllow: /\n\nSitemap: {site_url(facts, 'sitemap.xml')}\n").encode("utf-8") if landing: # Page hygiene of the CURRENT tree, like check_design_lines: a release is # published as it was. for page in all_pages.values(): errors.extend(f"docs/{page.rel}: accessibility: {f}" for f in page.a11y) for name, data in search_files(pages, search_layout(tpl), errors).items(): files[f"{DOCS_BASE}{name}"] = data build.undocumented = undocumented # type: ignore[attr-defined] return files # -------------------------------------------------------------------------- # Drift checks outside the site # -------------------------------------------------------------------------- def check_regions(facts: dict, errors: list[str], write: bool, only: list[str] | None = None, skip_stats: bool = False) -> None: for path in (tracked_files(*only) if only else tracked_files("*.md")): if not path.exists(): continue text = path.read_text(encoding="utf-8") if "`, `` or a marked section), inside which html.parser would hide a script or a meta tag that a browser runs or reads.""" def __init__(self, text: str) -> None: super().__init__(convert_charrefs=False) self.noindex = False self.scripts: list[str] = [] self.self_closing = 0 self.ambiguous = "" self._cur: list[str] | None = None self._text = text self._line_starts: list[int] | None = None # built on the first comment only def handle_starttag(self, tag, attrs): if tag == "meta": a = first_attrs(attrs) if (a.get("name") or "").strip().lower() == "robots": self.noindex |= "noindex" in (a.get("content") or "").lower().replace(",", " ").split() elif tag == "script": classic = is_classic_script(attrs) and "src" not in first_attrs(attrs) self._cur = [] if classic else None def handle_startendtag(self, tag, attrs): if tag == "script": self.self_closing += 1 else: self.handle_starttag(tag, attrs) def handle_data(self, data): if self._cur is not None and self.cdata_elem == "script": self._cur.append(data) def handle_endtag(self, tag): if tag == "script" and self._cur is not None: self.scripts.append("".join(self._cur)) if tag == "script": self._cur = None def handle_comment(self, data): if self._line_starts is None: starts, at = [0], self._text.find("\n") while at != -1: starts.append(at + 1) at = self._text.find("\n", at + 1) self._line_starts = starts line, col = self.getpos() start = self._line_starts[line - 1] + col opener = self._text[start:start + 5] if not self.ambiguous and (opener.startswith("", "->")))): self.ambiguous = f"a comment a browser ends earlier than html.parser does ({opener}...)" def unknown_decl(self, data): self.ambiguous = self.ambiguous or "a marked section ( None: self.path, self.version, self.dirty = path, _anchor_cache_version(), False self.pages: dict[str, list] = {} self.scripts: dict[str, str] = {} self.memo: dict[str, PageFacts] = {} try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, ValueError): return # fail-direction: a missing or corrupt cache is a cold one; every entry is rebuilt from source if isinstance(data, dict) and data.get("version") == self.version: pages, scripts = data.get("pages"), data.get("scripts") if isinstance(pages, dict) and isinstance(scripts, dict): # A cache can only ever cost a re-parse: a script whose text no longer # hashes to its key, or an entry of any other shape, is dropped and # its page parsed again, so no stored fact can stand in for the page. self.scripts = {k: v for k, v in scripts.items() if isinstance(v, str) and hashlib.sha256(v.encode("utf-8")).hexdigest() == k} self.pages = {k: v for k, v in pages.items() if self._well_formed(v)} def _well_formed(self, entry) -> bool: return (isinstance(entry, list) and len(entry) == 4 and type(entry[0]) is bool and isinstance(entry[1], list) and all(isinstance(k, str) and k in self.scripts for k in entry[1]) and type(entry[2]) is int and entry[2] >= 0 and isinstance(entry[3], str)) def get(self, data: bytes) -> PageFacts: key = hashlib.sha256(data).hexdigest() if key in self.memo: return self.memo[key] hit = self.pages.get(key) if hit is not None: noindex, script_keys, self_closing, ambiguous = hit facts = PageFacts(noindex, [self.scripts[k] for k in script_keys], self_closing, ambiguous) else: text = data.decode("utf-8", "replace") p = _PageScan(text) p.feed(text) p.close() facts = PageFacts(p.noindex, p.scripts, p.self_closing, p.ambiguous) keys = [] for src in facts.scripts: k = hashlib.sha256(src.encode("utf-8")).hexdigest() self.scripts[k] = src keys.append(k) self.pages[key], self.dirty = [facts.noindex, keys, facts.self_closing, facts.ambiguous], True self.memo[key] = facts return facts def save(self) -> None: """Keep only the pages this run read, and the scripts they use.""" used = {k: self.pages[k] for k in self.memo if k in self.pages} if not self.dirty and len(used) == len(self.pages): return scripts = {k: self.scripts[k] for v in used.values() for k in v[1] if k in self.scripts} tmp = self.path.with_suffix(f".{os.getpid()}.tmp") try: # write-then-rename, so a concurrent build never reads half a file self.path.parent.mkdir(parents=True, exist_ok=True) tmp.write_text(json.dumps({"version": self.version, "pages": used, "scripts": scripts}), encoding="utf-8") os.replace(tmp, self.path) except OSError: try: tmp.unlink(missing_ok=True) except OSError: pass self.pages, self.dirty = used, False _PAGE_FACTS: _PageFactsCache | None = None def page_facts(data: bytes | str) -> PageFacts: """PageFacts of one published page (see _PageScan), cached by content.""" global _PAGE_FACTS if _PAGE_FACTS is None: _PAGE_FACTS = _PageFactsCache(PAGE_CACHE) return _PAGE_FACTS.get(data.encode("utf-8") if isinstance(data, str) else data) def is_noindex(page_html: str) -> bool: return page_facts(page_html).noindex NODE_SYNTAX_CHECK = r""" const vm = require("vm"); let bad = 0; for (const [name, src] of JSON.parse(require("fs").readFileSync(0, "utf8"))) { try { new vm.Script(src, { filename: name }); } catch (e) { bad++; console.log(name + ": " + String(e.message).split("\n")[0]); } } process.exit(bad ? 1 : 0); """ def check_scripts(files: dict[str, bytes], errors: list[str]) -> None: """Every classic script the site ships must PARSE. One syntax error stops the whole block, so a stray brace on the landing page froze the countdown and left every scroll-revealed section invisible, while every link and fact check stayed green. Needs `node` (present locally and on the Actions runner); skipped when absent. The page checks that need no node (self-closing ") if facts.ambiguous: errors.append(f"{rel}: {facts.ambiguous}; a script or meta tag inside it would go unchecked") for i, src in enumerate(facts.scripts): seen.setdefault(src, f"{rel} (inline script {i + 1})") if _PAGE_FACTS is not None: _PAGE_FACTS.save() node = shutil.which("node") if not node: return batch = json.dumps([[name, src] for src, name in seen.items()]) r = subprocess.run([node, "-e", NODE_SYNTAX_CHECK], input=batch, capture_output=True, text=True, timeout=NODE_TIMEOUT) if r.returncode not in (0, 1): errors.append(f"script syntax check could not run: {r.stderr.strip()[:200]}") for line in r.stdout.splitlines(): errors.append(f"JavaScript syntax error in {line}") COUNT_TOTAL_RE = re.compile(r"\*\*All lines in tree\*\*\s*\|\s*\*\*\d+\*\*\s*\|\s*\*\*(\d+)\*\*") class _ImgSrcs(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.srcs: list[str] = [] def handle_starttag(self, tag, attrs): src = first_attrs(attrs).get("src") if tag == "img" else None # a repeated src: the first stands if src: self.srcs.append(src) handle_startendtag = handle_starttag def count_badge(readme: str) -> int | None: """The line count README's shields.io badge shows (`/badge/lines-1%2C349%2C692-`), or None when there is no such badge. Images are read as a browser would see them: Markdown images through markdown-it, raw (the form .githooks/post-commit writes) through html.parser. The count must be the comma-grouped number the hook renders.""" srcs: list[str] = [] for tok in make_md().parse(readme, {}): chunks = [tok] if tok.type == "html_block" else (tok.children or []) if tok.type == "inline" else [] for c in chunks: if c.type == "image": srcs.append(c.attrGet("src") or "") elif c.type in ("html_block", "html_inline"): p = _ImgSrcs() p.feed(c.content) p.close() srcs.extend(p.srcs) for src in srcs: try: parts = urlsplit(src) except ValueError: continue if parts.hostname != "img.shields.io" or not parts.path.startswith("/badge/lines-"): continue message = unquote(parts.path[len("/badge/lines-"):]).split("-", 1)[0] digits = message.replace(",", "") if digits.isascii() and digits.isdigit() and message == f"{int(digits):,}": return int(digits) return None def check_count_badge(errors: list[str]) -> None: count = (ROOT / "COUNT.md").read_text(encoding="utf-8") m = COUNT_TOTAL_RE.search(count) shown = count_badge((ROOT / "README.md").read_text(encoding="utf-8")) if not m or shown is None: errors.append("README/COUNT.md: line-count badge or COUNT.md total not found") return if shown != int(m.group(1)): errors.append(f"README.md: line-count badge says {shown:,}, COUNT.md says {int(m.group(1)):,} " f"(run: COUNT_ONLY=1 bash .githooks/post-commit)") def main() -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) mode = ap.add_mutually_exclusive_group() mode.add_argument("--check", action="store_true") mode.add_argument("--sync", nargs="*", metavar="FILE", help="rewrite project regions (all tracked Markdown, or only FILEs)") mode.add_argument("--update-baseline", action="store_true") mode.add_argument("--freshness", action="store_true", help="list every page and card with sources= and whether its code changed since") mode.add_argument("--emit-readme", action="store_true", help="post-commit: print README.md as committed at --ref with its project regions synced") ap.add_argument("--out", type=Path, default=DEFAULT_OUT) ap.add_argument("--quiet", action="store_true") ap.add_argument("--ref", default="HEAD", help="commit that --emit-readme reads (default HEAD)") ap.add_argument("--staged", action="store_true", help="read every input from the INDEX (pre-commit), not the working tree") ap.add_argument("--skip-stats", action="store_true", help="do not compare stat_* regions (pre-commit; post-commit re-syncs them)") ap.add_argument("--release", metavar="REF", help="render only the docs tree as it was at commit REF into /docs//, " "every repository link pinned to REF's full SHA") args = ap.parse_args() if args.release is not None and (args.staged or args.sync is not None or args.emit_readme or args.update_baseline or args.freshness or args.skip_stats): ap.error("--release combines only with --check, --out and --quiet") args.out = args.out.resolve() snap = None try: if args.release is not None: try: snap = prepare_release(args.release) except ReleaseError as e: print(f"ERROR: {e}", file=sys.stderr) return 1 elif args.emit_readme: snap = snapshot(args.ref, README_PATHS) elif args.staged: snap = snapshot("index") return run(args) finally: if snap is not None: shutil.rmtree(snap, ignore_errors=True) class ReleaseError(Exception): pass RELEASE_FACTS: dict = {} # publishing facts of the CURRENT tree, applied over a release's own # A commit whose tree lacks any of these predates the docs site and cannot be rendered. SITE_ERA_FILES = ("project.json", "gh-pages/docs-template.html", "COUNT.md", "docs/test-coverage/coverage.json") def is_site_era(commit: str) -> bool: """Whether a release build of COMMIT can run, judged without materialising it (scripts/site/releases.py skips earlier tags rather than failing on them).""" return all(subprocess.run(["git", "cat-file", "-e", f"{commit}:{p}"], cwd=REPO, capture_output=True, timeout=GIT_TIMEOUT).returncode == 0 for p in (*SITE_ERA_FILES, "docs")) def prepare_release(ref: str) -> Path | None: """Resolve REF, materialise its tree and switch rendering to release mode. The version path is REF itself, so every /-separated part must be a plain name (no `..`, no leading dash, nothing git would read as revision syntax). Links pin to the full SHA rather than the tag, because a tag can be moved and a published page must keep naming the commit it was built from. Publishing facts (site, repository, owner) come from the current tree: the repository has changed owners before, and the release is served from today's site.""" global LINK_REF, DOCS_BASE, RELEASE, RELEASE_FACTS parts = ref.split("/") if not all(VERSION_SEGMENT_RE.fullmatch(p) for p in parts): raise ReleaseError(f"release ref {ref!r}: each /-separated part must match " f"{VERSION_SEGMENT_RE.pattern} (it becomes the docs// path)") if parts[0] in ("main", "refs"): # A link naming blob/main/v1/x could mean branch main or tag main/v1; # refusing the name keeps every pinned link unambiguous. raise ReleaseError(f"release ref {ref!r}: a version may not start with main/ or refs/ " f"(it would be ambiguous with the branch in repository links)") r = subprocess.run(["git", "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], cwd=REPO, capture_output=True, text=True, timeout=GIT_TIMEOUT) if r.returncode != 0: raise ReleaseError(f"release ref {ref!r} does not name a commit") sha = r.stdout.strip() current = json.loads((REPO / "project.json").read_text(encoding="utf-8")) snap = snapshot(sha) missing = [p for p in SITE_ERA_FILES if not (ROOT / p).is_file()] if missing or not DOCS.is_dir(): shutil.rmtree(snap, ignore_errors=True) raise ReleaseError(f"release ref {ref!r} ({sha[:12]}) predates the docs site: no " + ", ".join(missing or ["docs/"])) LINK_REF, DOCS_BASE, RELEASE = sha, f"docs/{ref}/", ref RELEASE_FACTS = {k: current[k] for k in PUBLISH_KEYS if isinstance(current.get(k), str)} RELEASE_FACTS["_historical_owners"] = list(current.get("historical_owners", [])) return snap def check_release_paths(files: dict[str, bytes], errors: list[str]) -> None: """A main page or directory may not take a path a retained release is published at (scripts/site/releases.py): the deploy would refuse to assemble. Judged against the store commit this checkout last fetched, so it runs offline and is skipped where no store has been fetched; the deploy repeats it against the live store either way.""" sys.path.insert(0, str(Path(__file__).resolve().parent)) import releases # noqa: E402 (sibling module) r = subprocess.run(["git", "show", f"{releases.STORE_REF}:{releases.MANIFEST}"], cwd=REPO, capture_output=True, text=True, timeout=GIT_TIMEOUT) stored = [] if r.returncode == 0: try: stored = [e["version"] for e in json.loads(r.stdout).get("releases", []) if isinstance(e, dict) and isinstance(e.get("version"), str)] except (ValueError, AttributeError): errors.append(f"{releases.BRANCH}: {releases.MANIFEST} is not valid JSON") if releases.PUBLISHED in files: errors.append(f"{releases.PUBLISHED}: reserved for the version picker's manifest (releases.py)") main_files = set(files) - {releases.PUBLISHED} for v in stored: hit = releases.collisions(v, main_files) if releases.valid_version(v) else [] hit = [h for h in hit if h != releases.PUBLISHED] if hit: errors.append(f"docs path {hit[0]} collides with retained release {v} (docs/{v}/); rename the page") def run(args: argparse.Namespace) -> int: facts = load_project() errors: list[str] = [] if RELEASE is not None: owners = RELEASE_FACTS["_historical_owners"] + facts["_historical_owners"] facts.update(RELEASE_FACTS) facts["_historical_owners"] = sorted(set(owners)) if args.emit_readme: out = sync_regions((ROOT / "README.md").read_bytes().decode("utf-8"), facts, "README.md", errors) for e in errors: print(f"ERROR: {e}", file=sys.stderr) sys.stdout.buffer.write(out.encode("utf-8")) # the hook commits these bytes: no stream encoding, no newline return 1 if errors else 0 if args.sync is not None: check_regions(facts, errors, write=True, only=args.sync or None) for e in errors: print(f"ERROR: {e}", file=sys.stderr) return 1 if errors else 0 files = build(facts, errors) undocumented = build.undocumented # type: ignore[attr-defined] # A shallow clone cannot date pages. A check may still run there (warned), but # a written site would publish different bytes for the same commit, which # verify_live.py would then report as drift, so writing one is refused. shallow = build.shallow # type: ignore[attr-defined] if shallow and not (args.check or args.freshness or args.update_baseline): errors.append("shallow clone: page dates need full history (fetch-depth: 0); refusing to write the site") import freshness records = build.freshness # type: ignore[attr-defined] if args.freshness: for e in errors: print(f"ERROR: {e}", file=sys.stderr) for r in records: extra = f" ({', '.join(r.changed[:5])})" if r.changed else f" ({r.error})" if r.error else "" print(f"{r.state:8} {r.baseline_date or '-':10} {r.kind:4} {r.name}{extra}") stale = sum(1 for r in records if r.state == "stale") unknown = sum(1 for r in records if r.state == "unknown") print(f"freshness: {stale} of {len(records)} stale" + (f", {unknown} unknown" if unknown else ""), file=sys.stderr) return 1 if errors else 0 if args.update_baseline: # fail-direction: no file yet is the documented first creation, from the current undocumented set data = json.loads(BASELINE.read_text(encoding="utf-8")) if BASELINE.exists() else None BASELINE.write_text(json.dumps(shrink_baseline(data, undocumented), indent=2) + "\n", encoding="utf-8") print(f"baseline: {len(json.loads(BASELINE.read_text(encoding='utf-8'))['undocumented'])} undocumented TODO file(s)") return 0 check_scripts(files, errors) if RELEASE is None: # Repository hygiene of the CURRENT commit; a release is published as it was. check_regions(facts, errors, write=False, skip_stats=args.skip_stats) check_owner_urls(facts, errors) check_donate_links(facts, errors) check_count_badge(errors) check_icon_renders(errors) check_mockup_materials(errors) check_baseline(undocumented, errors) if args.check: # Source check only: a rebuild for verify_live must not judge against # whatever store this checkout fetched last; its assembly from the # pinned store enforces the same rule. check_release_paths(files, errors) sys.path.insert(0, str(REPO / "scripts" / "site")) import gen_theme_header # noqa: E402 (sibling module; set_root() repoints it at a snapshot) errors.extend(gen_theme_header.check()) import repo_meta # noqa: E402 (offline half; the live GitHub comparison is repo-metadata.yml) errors.extend(repo_meta.validate(json.loads(PROJECT_FILE.read_text(encoding="utf-8")))) if errors: for e in errors: print(f"ERROR: {e}", file=sys.stderr) print(f"site: {len(errors)} drift error(s)", file=sys.stderr) return 1 # Warnings, never errors: printed even under --quiet so lint Check 30 can # forward them (a code change is not always a docs change). for r in records: w = freshness.warning(r) if w: print(f"WARN: {w}", file=sys.stderr) if shallow: print("WARN: shallow clone: docs pages carry no last-updated dates and sitemap.xml no lastmod", file=sys.stderr) if not args.check: if args.out.exists(): shutil.rmtree(args.out) for rel, data in files.items(): dest = args.out / rel dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(data) if not args.quiet: docs = sum(1 for k in files if k.startswith("docs/") and k.endswith(".html")) total = len(todo_files()) print(f"site: OK ({len(files)} files, {docs} doc pages, " f"{total - len(undocumented)}/{total} TODO files documented)" + (f" [release {RELEASE} @ {LINK_REF[:12]}]" if RELEASE is not None else "") + ("" if args.check else f" -> {args.out}")) return 0 if __name__ == "__main__": sys.exit(main())