diff --git a/.gitignore b/.gitignore index 22693e6..510836c 100644 --- a/.gitignore +++ b/.gitignore @@ -31,6 +31,8 @@ venv/ .cache/ site/ -# Generated by `python -m docsite`: staged package docs and the rendered header -docs/*/guides/ +# Generated by `python -m docsite`: the assembled docs tree, the rendered header and the +# Zensical config (edit pages/, zensical.base.toml and etc/docsite.yaml instead) +docs/ overrides/partials/site-nav.html +zensical.toml diff --git a/docsite/build.py b/docsite/build.py index de80a47..41805e5 100644 --- a/docsite/build.py +++ b/docsite/build.py @@ -1,18 +1,27 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors -"""The build steps: fetch packages and nav, stage allowlisted docs, render the header.""" +"""The build steps: fetch inputs, assemble the docs tree, render the header and site config.""" +import os +import tomllib from pathlib import Path +import tomli_w from appinfra.log import Logger -from .config import BuildConfig -from .fetch import PackageFetcher, fetch_nav +from .config import BuildConfig, NavItem, Package +from .fetch import PackageFetcher, fetch_nav, fetch_text +from .navtree import SectionIndex, index_sections, package_nav, page_title, render_section_index +from .reference import reference_modules, reference_nav, reference_pages +from .siteconf import render_site_config from .sitenav import render_header -from .stage import DocsStager +from .stage import DocsStager, Source, StageError, merge, sync_tree NAV_SOURCE = "nav.html" +# Where fetch saves the brand stylesheets in build_dir, and where stage puts them in docs_dir +BRAND_SOURCE = "brand" +BRAND_ASSETS = "assets/brand" class Build: @@ -23,19 +32,50 @@ def __init__(self, lg: Logger, cfg: BuildConfig) -> None: self._cfg = cfg def fetch(self) -> None: - """Clone every package at its tag and download the nav partial.""" + """Clone every package at its tag; download the nav partial and brand stylesheets.""" fetcher = PackageFetcher(self._lg, self._cfg.site.build_dir) for pkg in self._cfg.packages: fetcher.fetch(pkg) nav_html = fetch_nav(self._lg, self._cfg.nav) self._nav_source.parent.mkdir(parents=True, exist_ok=True) self._nav_source.write_text(nav_html, encoding="utf-8") + brand_dir = self._cfg.site.build_dir / BRAND_SOURCE + brand_dir.mkdir(parents=True, exist_ok=True) + for name, url in self._brand_files.items(): + css = fetch_text(self._lg, url, self._cfg.brand.timeout_s) + (brand_dir / name).write_text(css, encoding="utf-8") def stage(self) -> None: - """Copy each fetched package's allowlisted docs into the site's docs directory.""" - stager = DocsStager(self._lg, self._cfg.site.docs_dir) + """Sync the docs directory to the site's pages plus each package's docs and reference.""" + site = self._cfg.site + plan: dict[str, Source] = { + p.relative_to(site.pages_dir).as_posix(): p + for p in sorted(site.pages_dir.rglob("*")) + if p.is_file() + } + brand_dir = site.build_dir / BRAND_SOURCE + brand = {f"{BRAND_ASSETS}/{name}": brand_dir / name for name in self._brand_files} + merge(plan, brand, "brand stylesheets") + stager = DocsStager(self._lg) for pkg in self._cfg.packages: - stager.stage(pkg, self._cfg.site.build_dir / pkg.name) + if f"{pkg.name}/index.md" not in plan: + raise StageError( + f"{pkg.name}: no landing page {site.pages_dir}/{pkg.name}/index.md" + ) + self._stage_package(pkg, stager, plan) + sync_tree(self._lg, plan, site.docs_dir) + + def _stage_package(self, pkg: Package, stager: DocsStager, plan: dict[str, Source]) -> None: + """Add a package's docs, its reference and its generated section pages to `plan`.""" + checkout = self._cfg.site.build_dir / pkg.name + files = stager.files(pkg, checkout) + merge(plan, {f"{pkg.name}/{path}": src for path, src in files.items()}, pkg.name) + modules = self._reference_modules(pkg) + if modules is not None: + pages = reference_pages(pkg, modules) + merge(plan, {f"{pkg.name}/{rel}": text for rel, text in pages.items()}, pkg.name) + _, sections = _package_tree(pkg, modules) + merge(plan, _section_pages(pkg.name, sections, plan), pkg.name) def nav(self) -> Path: """Render the fetched nav as the docs header partial.""" @@ -48,13 +88,82 @@ def nav(self) -> Path: self._lg.info("header rendered", extra={"output": str(output)}) return output + def site_config(self) -> Path: + """Write the Zensical config: the base config with each package's docs in the nav.""" + site = self._cfg.site + base = tomllib.loads(site.zensical_base.read_text(encoding="utf-8")) + trees = { + pkg.name: _package_tree(pkg, self._reference_modules(pkg))[0] + for pkg in self._cfg.packages + } + sources = [ + (site.build_dir / pkg.name / pkg.reference.source).as_posix() + for pkg in self._cfg.packages + if pkg.reference is not None + ] + # Zensical resolves docs_dir from the config file's directory + docs_dir = os.path.relpath(site.docs_dir.resolve(), site.zensical_config.parent.resolve()) + config = render_site_config(base, trees, sources, Path(docs_dir).as_posix()) + site.zensical_config.write_text(tomli_w.dumps(config), encoding="utf-8") + self._lg.info("site config rendered", extra={"output": str(site.zensical_config)}) + return site.zensical_config + def all(self) -> None: - """Fetch, stage and render, in order.""" + """Fetch, stage, render the header and the site config, in order.""" self.fetch() self.stage() self.nav() + self.site_config() + + def _reference_modules(self, pkg: Package) -> list[str] | None: + """The modules of the package's API reference; None when it has no reference.""" + if pkg.reference is None: + return None + return reference_modules(self._cfg.site.build_dir / pkg.name, pkg.reference) @property def _nav_source(self) -> Path: """Where fetch saves the nav partial and nav reads it.""" return self._cfg.site.build_dir / NAV_SOURCE + + @property + def _brand_files(self) -> dict[str, str]: + """File name -> URL of each brand stylesheet; the names are what the site config loads.""" + return {"tokens.css": self._cfg.brand.tokens_url, "nav.css": self._cfg.brand.nav_css_url} + + +def _package_tree( + pkg: Package, modules: list[str] | None +) -> tuple[list[NavItem], dict[str, SectionIndex]]: + """The package's nav and the section pages it needs generated. + + The nav is the configured docs tree, then the API reference of `modules` (None: the package + has none), with a generated page first in each section that has none, so that every item in + the tree opens a page. + """ + tree = package_nav(pkg) + if modules is not None: + tree.append(reference_nav(modules)) + return index_sections(tree) + + +def _section_pages( + name: str, sections: dict[str, SectionIndex], plan: dict[str, Source] +) -> dict[str, Source]: + """The generated section pages of package `name`, by docs path. + + Entries without a title are titled as the site titles them: a Markdown page by its front + matter or heading, read from what `plan` stages; any other file by its name. + """ + + def title_of(path: str) -> str: + if not path.endswith(".md"): + return page_title("", path) + src = plan[f"{name}/{path}"] + text = src.read_text(encoding="utf-8") if isinstance(src, Path) else src + return page_title(text, path) + + return { + f"{name}/{path}": render_section_index(path, index, title_of) + for path, index in sections.items() + } diff --git a/docsite/cli/cli.py b/docsite/cli/cli.py index 288a9e9..2f7a665 100644 --- a/docsite/cli/cli.py +++ b/docsite/cli/cli.py @@ -5,7 +5,7 @@ from appinfra.app import AppBuilder -from .tools import BuildTool, FetchTool, NavTool, StageTool +from .tools import BuildTool, FetchTool, NavTool, SiteConfigTool, StageTool def main() -> int: @@ -18,7 +18,7 @@ def main() -> int: .done() .cli.with_all_flags() .done() - .tools.with_tools(FetchTool(), StageTool(), NavTool(), BuildTool()) + .tools.with_tools(FetchTool(), StageTool(), NavTool(), SiteConfigTool(), BuildTool()) .done() .build() ) diff --git a/docsite/cli/tools.py b/docsite/cli/tools.py index 711f5e8..d3e791f 100644 --- a/docsite/cli/tools.py +++ b/docsite/cli/tools.py @@ -3,6 +3,7 @@ """One CLI tool per build step.""" +import tomllib from typing import Any, ClassVar from appinfra.app.tools import Tool, ToolConfig @@ -11,10 +12,23 @@ from ..build import Build from ..config import load_build_config from ..fetch import FetchError +from ..navtree import NavTreeError +from ..reference import ReferenceSourceError +from ..siteconf import SiteConfigError from ..sitenav import NavMarkupError from ..stage import StageError -_STEP_ERRORS = (ValidationError, FetchError, StageError, NavMarkupError, OSError) +_STEP_ERRORS = ( + ValidationError, + FetchError, + StageError, + NavMarkupError, + NavTreeError, + SiteConfigError, + ReferenceSourceError, + tomllib.TOMLDecodeError, + OSError, +) class _StepTool(Tool): @@ -54,10 +68,10 @@ def _step(self, build: Build) -> None: class StageTool(_StepTool): - """Copy allowlisted docs into the site.""" + """Assemble the docs directory from the site's pages and the packages' docs.""" name = "stage" - help_text = "Copy each package's allowlisted docs into the site's docs directory" + help_text = "Rebuild the docs directory from the site pages and each package's docs" def _step(self, build: Build) -> None: """Run Build.stage.""" @@ -75,11 +89,22 @@ def _step(self, build: Build) -> None: build.nav() +class SiteConfigTool(_StepTool): + """Render the Zensical config with each package's docs tree in the nav.""" + + name = "config" + help_text = "Render the Zensical config from the base config and the packages" + + def _step(self, build: Build) -> None: + """Run Build.site_config.""" + build.site_config() + + class BuildTool(_StepTool): """Run every step.""" name = "build" - help_text = "Fetch, stage and render the header" + help_text = "Fetch, stage, and render the header and the Zensical config" def _step(self, build: Build) -> None: """Run Build.all.""" diff --git a/docsite/config.py b/docsite/config.py index 181d711..f7d4758 100644 --- a/docsite/config.py +++ b/docsite/config.py @@ -1,10 +1,10 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors -"""Typed build configuration, validated from the `site`, `nav` and `packages` sections.""" +"""Typed build configuration, validated from the `site`, `nav`, `brand` and `packages` sections.""" import re -from collections.abc import Mapping +from collections.abc import Iterator, Mapping, Sequence from pathlib import Path, PurePosixPath from typing import Any from urllib.parse import urlsplit @@ -25,10 +25,26 @@ class _Frozen(BaseModel): class SiteConfig(_Frozen): - """Where checkouts and staged docs go.""" + """Where checkouts, pages and staged docs live, and the Zensical config in and out.""" build_dir: Path docs_dir: Path + pages_dir: Path + zensical_base: Path + zensical_config: Path + + @model_validator(mode="after") + def _docs_dir_is_disposable(self) -> "SiteConfig": + """stage deletes what docs_dir holds beyond its plan, and reads the pages and checkouts: + docs_dir cannot be, contain or lie inside pages_dir or build_dir.""" + docs = self.docs_dir.resolve() + for name, path in (("pages_dir", self.pages_dir), ("build_dir", self.build_dir)): + other = path.resolve() + if docs == other or docs in other.parents or other in docs.parents: + raise ValueError( + f"site.docs_dir is rebuilt on every stage; it cannot overlap site.{name}" + ) + return self class NavConfig(_Frozen): @@ -44,8 +60,7 @@ class NavConfig(_Frozen): @classmethod def _url_scheme(cls, value: str) -> str: """Accept http(s), and file:// for local previews and tests.""" - if not value.startswith(("https://", "http://", "file://")): - raise ValueError("nav.url must be an http(s) or file URL") + _check_url("nav.url", value) return value @field_validator("site_origin") @@ -64,6 +79,31 @@ def _docs_origin_form(cls, value: str) -> str: return value +class BrandConfig(_Frozen): + """The main site's shared stylesheets, fetched with the nav, loaded before the docs' own CSS. + + tokens.css holds the brand's custom properties (colors, edges, fonts, card spacing); nav.css + styles the nav partial and its theme switch. + """ + + tokens_url: str + nav_css_url: str + timeout_s: float = Field(default=10.0, gt=0) + + @field_validator("tokens_url", "nav_css_url") + @classmethod + def _url_scheme(cls, value: str) -> str: + """Accept http(s), and file:// for local previews and tests.""" + _check_url("brand stylesheet URL", value) + return value + + +def _check_url(field: str, value: str) -> None: + """Accept http(s), and file:// for local previews and tests.""" + if not value.startswith(("https://", "http://", "file://")): + raise ValueError(f"{field} must be an http(s) or file URL") + + def _check_origin(field: str, value: str) -> None: """Reject anything but scheme://host[:port], with no path, query or fragment.""" parts = urlsplit(value) @@ -76,13 +116,62 @@ def _check_origin(field: str, value: str) -> None: raise ValueError(f"{field} must be an http(s) origin: scheme://host[:port], nothing after") +# A site nav entry: a path, {title: path}, or {title: [entries]} for a section. +NavItem = str | dict[str, Any] + +_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +class Reference(_Frozen): + """A generated API reference: one page per top-level module of `package`, with submodules.""" + + # The import name, e.g. appinfra or llm_saia + package: str + # The checkout directory that holds the package directory + source: str = "." + + @field_validator("package") + @classmethod + def _package_name(cls, value: str) -> str: + """An importable top-level name.""" + if not _IDENTIFIER.fullmatch(value): + raise ValueError(f"reference package {value!r} is not an import name") + return value + + @field_validator("source") + @classmethod + def _source_path(cls, value: str) -> str: + """A plain path inside the checkout.""" + _check_doc_path(value, "reference source") + return value + + class Package(_Frozen): - """One package: its repo, the release tag to build from, and its docs allowlist.""" + """One package: its repo, the release tag to build from, and its docs tree. + + `docs` is both the allowlist and the package's place in the site nav: the package's docs are + the source and are published as they are, while the arrangement (order, sections, titles) is + the site's. Every path in it is published, and nothing else is. + """ name: str repo: str = Field(min_length=1) tag: str - docs: tuple[str, ...] = Field(min_length=1) + docs_root: str = "docs" + docs: tuple[NavItem, ...] = Field(min_length=1) + # Staged under another name, e.g. README.md, which the generator would take as the index + rename: dict[str, str] = Field(default_factory=dict) + # Generated API reference; a package without one publishes only its docs + reference: Reference | None = None + + @property + def files(self) -> tuple[str, ...]: + """Every path in the docs tree, in nav order.""" + return tuple(_nav_files(self.docs)) + + def site_path(self, path: str) -> str: + """Where a docs path lands in the site, relative to the package's directory.""" + return self.rename.get(path, path) @field_validator("name") @classmethod @@ -100,31 +189,70 @@ def _tag_form(cls, value: str) -> str: raise ValueError(f"tag {value!r} is not a plain tag name") return value + @field_validator("docs_root") + @classmethod + def _docs_root_path(cls, value: str) -> str: + """The docs directory is a plain path inside the checkout.""" + _check_doc_path(value, "docs_root") + return value + @field_validator("docs") @classmethod - def _docs_paths(cls, value: tuple[str, ...]) -> tuple[str, ...]: - """Each entry is an exact path inside docs/, listed once.""" - for path in value: - _check_doc_path(path) - if len(set(value)) != len(value): + def _docs_paths(cls, value: tuple[NavItem, ...]) -> tuple[NavItem, ...]: + """Each path is exact, inside the docs root, and listed once.""" + files = list(_nav_files(value)) + for path in files: + _check_doc_path(path, "docs path") + if len(set(files)) != len(files): raise ValueError("docs allowlist lists a path twice") return value + @model_validator(mode="after") + def _renames_fit(self) -> "Package": + """Each rename maps a listed file to a free, plain path.""" + files = set(self.files) + for src, dst in self.rename.items(): + _check_doc_path(dst, "rename target") + if src not in files: + raise ValueError(f"rename source {src!r} is not in docs") + targets = [self.site_path(path) for path in files] + if len(set(targets)) != len(targets): + raise ValueError("rename target collides with another docs path") + return self + -def _check_doc_path(path: str) -> None: - """Reject paths that could escape docs/ or match more than one file.""" +def _nav_files(items: Sequence[NavItem]) -> Iterator[str]: + """Yield the paths of a docs tree in order; reject entries of any other shape.""" + for item in items: + if isinstance(item, str): + yield item + continue + if not (isinstance(item, dict) and len(item) == 1): + raise ValueError(f"docs entry {item!r} must be a path or a one-key mapping") + (value,) = item.values() + if isinstance(value, str): + yield value + elif isinstance(value, list | tuple) and value: + yield from _nav_files(value) + else: + raise ValueError(f"docs entry {item!r} needs a path or a non-empty list") + + +def _check_doc_path(path: str, what: str) -> None: + """Reject paths that could escape their root or match more than one file.""" pure = PurePosixPath(path) if pure.is_absolute() or ".." in pure.parts or path != pure.as_posix(): - raise ValueError(f"docs path {path!r} must be a normalized path inside docs/") + raise ValueError(f"{what} {path!r} must be a normalized relative path") if _GLOB_CHARS & set(path): - raise ValueError(f"docs path {path!r} must be an exact path, not a pattern") + raise ValueError(f"{what} {path!r} must be an exact path, not a pattern") class BuildConfig(_Frozen): - """The whole build: site paths, nav source and the packages to publish.""" + """The whole build: site paths, nav source, brand stylesheets and the packages to publish.""" site: SiteConfig nav: NavConfig + brand: BrandConfig packages: tuple[Package, ...] @model_validator(mode="after") @@ -138,7 +266,7 @@ def _unique_names(self) -> "BuildConfig": def load_build_config(raw: Mapping[str, Any]) -> BuildConfig: """Validate the build sections of the app config; other sections are ignored.""" - sections = {key: _plain(raw.get(key)) for key in ("site", "nav", "packages")} + sections = {key: _plain(raw.get(key)) for key in ("site", "nav", "brand", "packages")} return BuildConfig.model_validate(sections) diff --git a/docsite/fetch.py b/docsite/fetch.py index 219c85a..50a56aa 100644 --- a/docsite/fetch.py +++ b/docsite/fetch.py @@ -1,8 +1,10 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors -"""Fetch the inputs of a build: each package at its release tag, and the main site's nav.""" +"""Fetch the inputs of a build: each package at its release tag, and the main site's nav and +brand stylesheets.""" +import http.client import shutil import subprocess import urllib.request @@ -76,19 +78,25 @@ def _git(*args: str) -> str: def fetch_nav(lg: Logger, nav: NavConfig) -> str: """Download the main site's nav partial and return its markup.""" - request = urllib.request.Request(nav.url, headers={"User-Agent": USER_AGENT}) + return fetch_text(lg, nav.url, nav.timeout_s) + + +def fetch_text(lg: Logger, url: str, timeout_s: float) -> str: + """Download a text file from the main site (or a file:// URL) and return it.""" + request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) try: - with urllib.request.urlopen(request, timeout=nav.timeout_s) as response: # noqa: S310 + with urllib.request.urlopen(request, timeout=timeout_s) as response: # noqa: S310 # HTTP responses carry a status; file:// responses (local previews) have None. status = response.status body: bytes = response.read() - except OSError as e: - raise FetchError(f"nav download from {nav.url} failed: {e}") from e + # A body cut off mid-transfer raises IncompleteRead, an HTTPException, not an OSError + except (OSError, http.client.HTTPException) as e: + raise FetchError(f"download from {url} failed: {e}") from e if status is not None and status != 200: - raise FetchError(f"nav download from {nav.url} returned HTTP {status}") + raise FetchError(f"download from {url} returned HTTP {status}") try: - html = body.decode("utf-8") + text = body.decode("utf-8") except UnicodeDecodeError as e: - raise FetchError(f"nav from {nav.url} is not valid UTF-8: {e}") from e - lg.info("nav fetched", extra={"url": nav.url, "bytes": len(body)}) - return html + raise FetchError(f"{url} is not valid UTF-8: {e}") from e + lg.info("fetched", extra={"url": url, "bytes": len(body)}) + return text diff --git a/docsite/navtree.py b/docsite/navtree.py new file mode 100644 index 0000000..86c92a6 --- /dev/null +++ b/docsite/navtree.py @@ -0,0 +1,173 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Nav trees: a package's configured `docs` tree, with each path where it is staged, and a +generated page for each section that has none.""" + +import posixpath +import re +from collections.abc import Callable, Sequence +from dataclasses import dataclass + +from .config import NavItem, Package + +# Zensical takes a section's first entry as the section's own page when it is one of these +INDEX_NAMES = ("index.md", "README.md") + +_HEADING = re.compile(r"#\s+(.+?)(?:\s+#+)?\s*$") +_FRONT_TITLE = re.compile(r"title:\s*(.+)$") +# A code fence line: its marker, then an info string (opening fences only) +_FENCE = re.compile(r"\s*(`{3,}|~{3,})(.*)$") + + +class NavTreeError(ValueError): + """A nav tree the site cannot build pages for.""" + + +@dataclass(frozen=True) +class SectionIndex: + """A generated page for a section without one: the section's title and its entries.""" + + title: str + entries: tuple[NavItem, ...] + + +def package_nav(pkg: Package) -> list[NavItem]: + """The package's docs tree with renames applied, paths relative to the package's directory.""" + return map_paths(pkg.docs, pkg.site_path) + + +def map_paths(items: Sequence[NavItem], fn: Callable[[str], str]) -> list[NavItem]: + """The tree with `fn` applied to every path; titles and sections are kept.""" + out: list[NavItem] = [] + for item in items: + if isinstance(item, str): + out.append(fn(item)) + continue + ((title, value),) = item.items() + out.append({title: fn(value) if isinstance(value, str) else map_paths(value, fn)}) + return out + + +def index_sections( + items: Sequence[NavItem], base: str = "" +) -> tuple[list[NavItem], dict[str, SectionIndex]]: + """The tree with a generated index page first in every section that has no page of its own. + + Every item in the tree then opens a page. A generated page sits at the section's titles + slugged under `base` (Guides > Configuration: guides/configuration/index.md). Returns the + tree and the generated pages by path; a path a source already takes fails at staging. + """ + out: list[NavItem] = [] + pages: dict[str, SectionIndex] = {} + for item in items: + if isinstance(item, str) or isinstance(next(iter(item.values())), str): + out.append(item) + continue + ((title, value),) = item.items() + folder = posixpath.join(base, _slug(title)) + entries, nested = index_sections(value, folder) + pages.update(nested) + if not _has_page(entries): + path = posixpath.join(folder, "index.md") + pages[path] = SectionIndex(title, tuple(entries)) + entries = [path, *entries] + out.append({title: entries}) + return out, pages + + +def render_section_index(path: str, index: SectionIndex, title_of: Callable[[str], str]) -> str: + """The Markdown of a generated section page: its title, then a link to each entry. + + An entry without a title is titled by `title_of(path)`, the page's own heading, as in the + tree; a section links to its own page, its first entry. + """ + folder = posixpath.dirname(path) + lines = [f"# {index.title}", ""] + for entry in index.entries: + title, target = _entry_link(entry, title_of) + lines.append(f"- [{_escape(title)}]({posixpath.relpath(target, folder)})") + return "\n".join(lines) + "\n" + + +def page_title(text: str, path: str) -> str: + """A page's title as the site shows it: the front matter's `title`, else the first level-1 + heading, else the file name.""" + lines = text.splitlines() + body = lines + if lines and lines[0].strip() == "---": + end = next((i for i, line in enumerate(lines[1:], 1) if line.strip() == "---"), 0) + for line in lines[1:end]: + match = _FRONT_TITLE.match(line) + if match: + return match.group(1).strip().strip("\"'") + body = lines[end + 1 :] + return _heading(body) or _file_title(path) + + +def _heading(lines: Sequence[str]) -> str | None: + """The first level-1 heading outside fenced code. + + A fence closes only on a bare marker of its own character, at least as long as the one that + opened it (CommonMark): a ``` line inside a ~~~ block, or inside a ```` block, is code. + """ + fence: str | None = None # the marker of the block the line is in + for line in lines: + marker = _FENCE.match(line) + if marker and fence is None: + fence = marker.group(1) + continue + if marker and _closes(marker, fence): + fence = None + continue + match = None if fence else _HEADING.match(line) + if match: + return match.group(1) + return None + + +def _closes(marker: re.Match[str], fence: str | None) -> bool: + """Whether a fence line closes the block that `fence` opened.""" + close, rest = marker.group(1), marker.group(2) + return ( + fence is not None and close[0] == fence[0] and len(close) >= len(fence) and not rest.strip() + ) + + +def _file_title(path: str) -> str: + """A title from the file name: "getting-started.md" -> "Getting started".""" + stem = posixpath.splitext(posixpath.basename(path))[0] + return stem.replace("-", " ").replace("_", " ").capitalize() + + +def _has_page(entries: Sequence[NavItem]) -> bool: + """Whether the section's first entry is a page the site takes as the section's own.""" + if not entries: + return False + first = entries[0] + path = first if isinstance(first, str) else next(iter(first.values())) + return isinstance(path, str) and posixpath.basename(path) in INDEX_NAMES + + +def _entry_link(entry: NavItem, title_of: Callable[[str], str]) -> tuple[str, str]: + """An entry's title and the path its link goes to.""" + if isinstance(entry, str): + return title_of(entry), entry + ((title, value),) = entry.items() + if isinstance(value, str): + return title, value + first = value[0] + return title, first if isinstance(first, str) else next(iter(first.values())) + + +def _slug(title: str) -> str: + """A section title as a path segment: "Development tooling" -> "development-tooling".""" + slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-") + if not slug: + raise NavTreeError(f"section title has no letters or digits for its page path: {title!r}") + return slug + + +def _escape(title: str) -> str: + """A title as Markdown link text.""" + return title.replace("[", r"\[").replace("]", r"\]") diff --git a/docsite/reference.py b/docsite/reference.py new file mode 100644 index 0000000..d1cd740 --- /dev/null +++ b/docsite/reference.py @@ -0,0 +1,62 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Generated API reference pages: one per top-level module, rendered by mkdocstrings.""" + +from pathlib import Path + +from .config import NavItem, Package, Reference + +REFERENCE_DIR = "reference" +NAV_TITLE = "API reference" + + +class ReferenceSourceError(RuntimeError): + """The package to document is not where the reference config points.""" + + +def reference_modules(checkout: Path, ref: Reference) -> list[str]: + """The package's public top-level modules and subpackages, as dotted names, sorted.""" + root = checkout / ref.source / ref.package + if not (root / "__init__.py").is_file() or root.is_symlink(): + raise ReferenceSourceError(f"{root} is not a package directory") + modules = [] + for entry in sorted(root.iterdir()): + name = entry.stem if entry.suffix == ".py" else entry.name + if name.startswith("_") or entry.is_symlink(): + continue + is_module = entry.is_file() and entry.suffix == ".py" + if is_module or (entry / "__init__.py").is_file(): + modules.append(f"{ref.package}.{name}") + return modules + + +def reference_pages(pkg: Package, modules: list[str]) -> dict[str, str]: + """Page text by path under /: an index, then one page per module.""" + pages = {f"{REFERENCE_DIR}/index.md": _index_page(pkg, modules)} + for module in modules: + pages[_module_path(module)] = f"# {module}\n\n::: {module}\n" + return pages + + +def reference_nav(modules: list[str]) -> NavItem: + """The API reference section: the index, then each module by its short name.""" + entries: list[NavItem] = [f"{REFERENCE_DIR}/index.md"] + entries += [{module.split(".", 1)[1]: _module_path(module)} for module in modules] + return {NAV_TITLE: entries} + + +def _module_path(module: str) -> str: + """The page of a module, under reference/.""" + return f"{REFERENCE_DIR}/{module.split('.', 1)[1]}.md" + + +def _index_page(pkg: Package, modules: list[str]) -> str: + """The reference landing page: what it is generated from, and every module.""" + links = "\n".join(f"- [`{m}`]({m.split('.', 1)[1]}.md)" for m in modules) + return ( + f"# {NAV_TITLE}\n\n" + f"Generated from the docstrings and type hints of {pkg.name} {pkg.tag}. Each page covers " + "one top-level module and its submodules.\n\n" + f"{links}\n" + ) diff --git a/docsite/siteconf.py b/docsite/siteconf.py new file mode 100644 index 0000000..de9916d --- /dev/null +++ b/docsite/siteconf.py @@ -0,0 +1,65 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Render the Zensical config: the tracked base, with each package's docs tree in the nav.""" + +import copy +from collections.abc import Mapping, Sequence +from typing import Any + +from .config import NavItem +from .navtree import map_paths + +PACKAGES_SECTION = "Packages" + + +class SiteConfigError(RuntimeError): + """The base config has no place for a configured package.""" + + +def render_site_config( + base: Mapping[str, Any], + trees: Mapping[str, list[NavItem]], + reference_sources: Sequence[str], + docs_dir: str, +) -> dict[str, Any]: + """Return `base` with each package's `{name: name/index.md}` nav entry expanded. + + The base lists every package under the Packages section by its landing page. `trees` maps a + package name to its tree, with paths relative to the package's directory; the tree goes below + the landing page. `reference_sources` are the checkout directories mkdocstrings reads. + `docs_dir`, the directory stage fills, relative to the written config, replaces the base's + project.docs_dir, so the two cannot disagree. + """ + config = copy.deepcopy(dict(base)) + config.setdefault("project", {})["docs_dir"] = docs_dir + section = _packages_section(config) + for name, tree in trees.items(): + _expand(section, name, tree) + if reference_sources: + project = config.setdefault("project", {}) + handler = project.setdefault("plugins", {}).setdefault("mkdocstrings", {}) + handler.setdefault("handlers", {}).setdefault("python", {})["paths"] = list( + reference_sources + ) + return config + + +def _packages_section(config: dict[str, Any]) -> list[Any]: + """The list under {"Packages": [...]} in project.nav.""" + nav = config.get("project", {}).get("nav", []) + for item in nav: + if isinstance(item, dict) and isinstance(item.get(PACKAGES_SECTION), list): + section: list[Any] = item[PACKAGES_SECTION] + return section + raise SiteConfigError(f"base config has no {PACKAGES_SECTION!r} section in project.nav") + + +def _expand(section: list[Any], name: str, tree: list[NavItem]) -> None: + """Replace the package's landing entry with its landing page plus `tree`.""" + landing = f"{name}/index.md" + for i, item in enumerate(section): + if item == {name: landing}: + section[i] = {name: [landing, *map_paths(tree, lambda path: f"{name}/{path}")]} + return + raise SiteConfigError(f"{PACKAGES_SECTION} has no entry {{{name!r}: {landing!r}}}") diff --git a/docsite/sitenav.py b/docsite/sitenav.py index 1089ed3..8e2206d 100644 --- a/docsite/sitenav.py +++ b/docsite/sitenav.py @@ -9,9 +9,9 @@ root-relative, for a local preview served next to the main site); - the "Docs" item is marked current: an existing link to the docs site is reused, otherwise an item is added after Platform; -- the docs search box sits between the logo and the links, and the main site's theme switch - follows the nav. +- the main site's theme switch follows the nav, unless the partial carries it already. +The docs search is not part of the header: it sits above the tree (overrides/main.html). The output is a Jinja partial for the Zensical theme override. """ @@ -20,7 +20,6 @@ GENERATED_MARK = "{#- generated by docsite from the main site's partials/nav.html -#}\n" DOCS_ITEM = '
  • Docs
  • \n' -SEARCH = ' \n' # Same markup as the switch on the main site's pages. THEME_SWITCH = """\ @@ -39,16 +38,19 @@ class NavMarkupError(ValueError): def render_header(nav_html: str, site_origin: str, docs_origin: str) -> str: - """Return the docs header partial for the given main-site nav markup.""" - return GENERATED_MARK + docs_nav(nav_html, site_origin, docs_origin) + THEME_SWITCH + """Return the docs header partial for the given main-site nav markup. + + The theme switch is appended only when the partial does not carry one itself. + """ + switch = "" if 'id="theme-switch"' in nav_html else THEME_SWITCH + return GENERATED_MARK + docs_nav(nav_html, site_origin, docs_origin) + switch def docs_nav(nav_html: str, site_origin: str, docs_origin: str) -> str: """Rewrite the main site's nav for the docs site at `docs_origin`.""" html = nav_html.replace(_CURRENT, "") html = _ROOT_HREF.sub(f'href="{site_origin}/', html) - html = _mark_docs_item(html, site_origin, docs_origin) - return _insert_after(html, r'.*class="logo".*\n', SEARCH, "logo") + return _mark_docs_item(html, site_origin, docs_origin) def _mark_docs_item(html: str, site_origin: str, docs_origin: str) -> str: diff --git a/docsite/stage.py b/docsite/stage.py index 4ee4b7f..157d949 100644 --- a/docsite/stage.py +++ b/docsite/stage.py @@ -1,25 +1,27 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors -"""Stage a fetched package's allowlisted docs into the site's docs directory.""" +"""Assemble the site's docs directory: select each package's allowlisted docs, then sync.""" -import shutil -from collections.abc import Iterable, Sequence +from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass -from pathlib import Path +from pathlib import Path, PurePosixPath from appinfra.log import Logger from .config import Package +# What a docs file is made from: a file to copy, or generated text +Source = Path | str + class StageError(RuntimeError): - """A package's docs do not match its allowlist.""" + """A package's docs do not match its allowlist, or two sources claim one docs path.""" @dataclass(frozen=True) class Selection: - """How a package's docs/ compares with its allowlist.""" + """How a package's docs directory compares with its allowlist.""" copy: tuple[str, ...] missing: tuple[str, ...] @@ -27,7 +29,7 @@ class Selection: def select(available: Iterable[str], allowlist: Sequence[str]) -> Selection: - """Split docs/ files into those to copy, listed-but-absent, and present-but-unlisted.""" + """Split docs files into those to copy, listed-but-absent, and present-but-unlisted.""" present = set(available) listed = set(allowlist) return Selection( @@ -38,19 +40,15 @@ def select(available: Iterable[str], allowlist: Sequence[str]) -> Selection: class DocsStager: - """Copies allowlisted docs from a checkout to //guides.""" + """Maps a checkout's allowlisted docs to their site paths, relative to the package's dir.""" - def __init__(self, lg: Logger, docs_dir: Path) -> None: + def __init__(self, lg: Logger) -> None: self._lg = lg - self._docs_dir = docs_dir - - def stage(self, pkg: Package, checkout: Path) -> Path: - """Copy `pkg`'s allowlisted docs; fail if any listed file is missing or a symlink.""" - source = checkout / "docs" - # rglob follows a symlinked root, which would list files from wherever it points. - if source.is_symlink(): - raise StageError(f"{pkg.name} {pkg.tag}: docs/ is a symlink") - sel = select(_list_files(source), pkg.docs) + + def files(self, pkg: Package, checkout: Path) -> dict[str, Path]: + """Site path (renames applied) -> source file; fail on a missing file or a symlink.""" + source = _docs_source(pkg, checkout) + sel = select(_list_files(source), pkg.files) if sel.missing: raise StageError(f"{pkg.name} {pkg.tag}: allowlisted docs missing: {list(sel.missing)}") if sel.unlisted: @@ -58,13 +56,65 @@ def stage(self, pkg: Package, checkout: Path) -> Path: "docs not in allowlist, skipped", extra={"package": pkg.name, "files": list(sel.unlisted)}, ) - dest = self._docs_dir / pkg.name / "guides" - if dest.exists(): - shutil.rmtree(dest) + files = {} for path in sel.copy: - _copy_file(source, dest, path, pkg.name) - self._lg.info("docs staged", extra={"package": pkg.name, "files": len(sel.copy)}) - return dest + src = source / path + # A symlink could pull content from outside the docs root. + if src.is_symlink(): + raise StageError(f"{pkg.name}: allowlisted docs path {path!r} is a symlink") + files[pkg.site_path(path)] = src + return files + + +def merge(plan: dict[str, Source], files: Mapping[str, Source], owner: str) -> None: + """Add `files` to `plan`; a path that is already taken is an error, never an overwrite.""" + taken = sorted(plan.keys() & files.keys()) + if taken: + raise StageError(f"{owner}: docs paths already taken by another source: {taken}") + plan.update(files) + + +def sync_tree(lg: Logger, plan: Mapping[str, Source], root: Path) -> None: + """Make `root` hold exactly `plan`: write changed files, remove the rest. + + Files are updated in place rather than by recreating the directory, so a live-reload server + watching `root` keeps seeing changes. + """ + written = 0 + for rel, src in plan.items(): + data = src.read_bytes() if isinstance(src, Path) else src.encode("utf-8") + target = root / rel + if target.is_file() and target.read_bytes() == data: + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + written += 1 + removed = _remove_extras(root, set(plan)) + lg.info("docs synced", extra={"files": len(plan), "written": written, "removed": removed}) + + +def _remove_extras(root: Path, keep: set[str]) -> int: + """Delete files under `root` not in `keep`, then directories left empty.""" + removed = 0 + for path in sorted(root.rglob("*"), reverse=True): + rel = path.relative_to(root).as_posix() + if (path.is_file() or path.is_symlink()) and rel not in keep: + path.unlink() + removed += 1 + elif path.is_dir() and not any(path.iterdir()): + path.rmdir() + return removed + + +def _docs_source(pkg: Package, checkout: Path) -> Path: + """The package's docs directory; no part of its path may be a symlink.""" + path = checkout + for part in PurePosixPath(pkg.docs_root).parts: + path = path / part + # rglob follows a symlinked directory, which would list files from wherever it points. + if path.is_symlink(): + raise StageError(f"{pkg.name} {pkg.tag}: {pkg.docs_root}/ has a symlink in its path") + return path def _list_files(root: Path) -> list[str]: @@ -73,13 +123,3 @@ def _list_files(root: Path) -> list[str]: return [] entries = (p for p in root.rglob("*") if p.is_symlink() or p.is_file()) return [p.relative_to(root).as_posix() for p in entries] - - -def _copy_file(source: Path, dest: Path, path: str, pkg_name: str) -> None: - """Copy one regular file; a symlink could pull content from outside docs/.""" - src = source / path - if src.is_symlink(): - raise StageError(f"{pkg_name}: allowlisted docs path {path!r} is a symlink") - target = dest / path - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(src, target) diff --git a/pyproject.toml b/pyproject.toml index 4960beb..91238b9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,6 +22,17 @@ classifiers = [ dependencies = [ # validation: pydantic, for the build config models "appinfra[validation]>=0.14.0", + # writes the generated zensical.toml + "tomli-w>=1.2", + # the site generator; pinned, upgrades are checked against the built site + "zensical==0.1.2", + # the generated API reference; mkdocstrings-python brings griffe, which the docstring + # extension (docsite/docstring_code.py) builds on + "mkdocstrings==1.0.8", + "mkdocstrings-python==2.0.10", + # GitHub-style lists in package docs: no blank line before a list, two-space nesting + "mdx_breakless_lists==1.0.1", + "mdx_truly_sane_lists==1.3", ] [project.optional-dependencies] diff --git a/tests/conftest.py b/tests/conftest.py index 90ae4f7..22f5cb9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -33,13 +33,23 @@ def package_dict(**overrides: Any) -> dict[str, Any]: def build_dict(**overrides: Any) -> dict[str, Any]: """A valid build config mapping, with top-level sections replaced by `overrides`.""" cfg: dict[str, Any] = { - "site": {"build_dir": ".build/src", "docs_dir": "docs"}, + "site": { + "build_dir": ".build/src", + "docs_dir": "docs", + "pages_dir": "pages", + "zensical_base": "zensical.base.toml", + "zensical_config": "zensical.toml", + }, "nav": { "url": "https://www.llm-works.ai/partials/nav.html", "site_origin": "https://www.llm-works.ai", "docs_origin": "https://docs.llm-works.ai", "output": "overrides/partials/site-nav.html", }, + "brand": { + "tokens_url": "https://www.llm-works.ai/partials/tokens.css", + "nav_css_url": "https://www.llm-works.ai/partials/nav.css", + }, "packages": [package_dict()], } cfg.update(overrides) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 8a4cb3b..7e02eff 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -14,6 +14,11 @@ "demo/demo.gif": "GIF89a", "known-issues.md": "internal notes\n", } +# A small package beside docs/, for the generated reference +SOURCE = { + "pkgmod/__init__.py": '"""The package."""\n', + "pkgmod/core.py": '"""Core module."""\n\n\ndef run() -> None:\n """Run."""\n', +} def git(cwd: Path, *args: str) -> None: @@ -28,10 +33,11 @@ def git(cwd: Path, *args: str) -> None: @pytest.fixture def package_repo(tmp_path: Path) -> Path: - """A repo with docs/ committed and tagged TAG, plus a branch named `rel`.""" + """A repo with docs/ and a package committed and tagged TAG, plus a branch named `rel`.""" repo = tmp_path / "pkg-repo" - for rel, text in DOCS.items(): - path = repo / "docs" / rel + files = {f"docs/{rel}": text for rel, text in DOCS.items()} | SOURCE + for rel, text in files.items(): + path = repo / rel path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") git(tmp_path, "init", "--quiet", "--initial-branch=main", str(repo)) diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py index 96676dc..3c37643 100644 --- a/tests/integration/test_cli.py +++ b/tests/integration/test_cli.py @@ -4,6 +4,7 @@ """The CLI steps, in process, with a config pointing at local inputs.""" import sys +import tomllib from pathlib import Path import pytest @@ -20,13 +21,46 @@ """ +BASE = """\ +[project] +site_name = "Docs" +nav = [ + { "Home" = "index.md" }, + { "Packages" = ["packages/index.md", { "pkg" = "pkg/index.md" }] }, +] +""" + +PACKAGE = """\ + - name: pkg + repo: {repo} + tag: {tag} + rename: + INTRO.md: intro.md + reference: + package: pkgmod + docs: + - Introduction: INTRO.md + - Demo: + - demo/demo.gif +""" + + +def _inputs(tmp_path: Path) -> None: + """The site's own pages, the base Zensical config, and the main site's nav and stylesheets.""" + for rel in ("index.md", "packages/index.md", "pkg/index.md"): + page = tmp_path / "pages" / rel + page.parent.mkdir(parents=True, exist_ok=True) + page.write_text(f"# {rel}\n", encoding="utf-8") + (tmp_path / "base.toml").write_text(BASE, encoding="utf-8") + (tmp_path / "nav-src.html").write_text(NAV, encoding="utf-8") + (tmp_path / "tokens.css").write_text(":root { --bg: #000; }\n", encoding="utf-8") + (tmp_path / "nav.css").write_text(".site-nav { color: red; }\n", encoding="utf-8") -def _config(tmp_path: Path, repo: Path, docs: list[str]) -> Path: - nav_file = tmp_path / "nav-src.html" - nav_file.write_text(NAV, encoding="utf-8") + +def _config(tmp_path: Path, repo: Path, package: str = PACKAGE) -> Path: + _inputs(tmp_path) etc = tmp_path / "etc" etc.mkdir() - allowlist = "".join(f" - {path}\n" for path in docs) (etc / "docsite.yaml").write_text( f"""\ logging: @@ -34,17 +68,19 @@ def _config(tmp_path: Path, repo: Path, docs: list[str]) -> Path: site: build_dir: {tmp_path / "build"} docs_dir: {tmp_path / "docs"} + pages_dir: {tmp_path / "pages"} + zensical_base: {tmp_path / "base.toml"} + zensical_config: {tmp_path / "zensical.toml"} nav: - url: {nav_file.as_uri()} + url: {(tmp_path / "nav-src.html").as_uri()} site_origin: https://www.llm-works.ai docs_origin: https://docs.llm-works.ai output: {tmp_path / "overrides" / "site-nav.html"} +brand: + tokens_url: {(tmp_path / "tokens.css").as_uri()} + nav_css_url: {(tmp_path / "nav.css").as_uri()} packages: - - name: pkg - repo: {repo} - tag: {TAG} - docs: -{allowlist}""", +{package.format(repo=repo, tag=TAG)}""", encoding="utf-8", ) return etc @@ -58,33 +94,73 @@ def _run(monkeypatch: pytest.MonkeyPatch, etc: Path, step: str) -> int: def test_build_runs_every_step( monkeypatch: pytest.MonkeyPatch, package_repo: Path, tmp_path: Path ) -> None: - """`build` fetches, stages the allowlisted docs and renders the header.""" - etc = _config(tmp_path, package_repo, ["INTRO.md", "demo/demo.gif"]) - assert _run(monkeypatch, etc, "build") == 0 - guides = tmp_path / "docs" / "pkg" / "guides" - assert (guides / "INTRO.md").is_file() - assert (guides / "demo" / "demo.gif").is_file() - assert not (guides / "known-issues.md").exists() + """`build` assembles docs/, renders the header and writes the Zensical config.""" + assert _run(monkeypatch, _config(tmp_path, package_repo), "build") == 0 + docs = tmp_path / "docs" + assert (docs / "index.md").is_file() + assert (docs / "pkg" / "intro.md").is_file() + assert (docs / "pkg" / "demo" / "demo.gif").is_file() + assert not (docs / "pkg" / "known-issues.md").exists() + assert ( + (docs / "pkg" / "reference" / "core.md") + .read_text(encoding="utf-8") + .endswith("::: pkgmod.core\n") + ) + assert ( + (docs / "assets" / "brand" / "tokens.css").read_text(encoding="utf-8").startswith(":root") + ) header = (tmp_path / "overrides" / "site-nav.html").read_text(encoding="utf-8") assert 'href="https://www.llm-works.ai/platform/"' in header + config = tomllib.loads((tmp_path / "zensical.toml").read_text(encoding="utf-8")) + # The staged directory, relative to zensical.toml + assert config["project"]["docs_dir"] == "docs" + entry = config["project"]["nav"][1]["Packages"][1]["pkg"] + assert entry[:3] == [ + "pkg/index.md", + {"Introduction": "pkg/intro.md"}, + {"Demo": ["pkg/demo/index.md", "pkg/demo/demo.gif"]}, + ] + assert entry[3]["API reference"][0] == "pkg/reference/index.md" + # The Demo section has no page of its own: one is generated, listing its entries + assert (docs / "pkg" / "demo" / "index.md").read_text(encoding="utf-8") == ( + "# Demo\n\n- [Demo](demo.gif)\n" + ) + python = config["project"]["plugins"]["mkdocstrings"]["handlers"]["python"] + assert python["paths"] == [(tmp_path / "build" / "pkg").as_posix()] def test_steps_run_separately( monkeypatch: pytest.MonkeyPatch, package_repo: Path, tmp_path: Path ) -> None: - """fetch, stage and nav each do their part and read the previous step's output.""" - etc = _config(tmp_path, package_repo, ["INTRO.md"]) + """Each step does its part and reads the previous step's output; stage syncs in place.""" + etc = _config(tmp_path, package_repo) assert _run(monkeypatch, etc, "fetch") == 0 assert (tmp_path / "build" / "nav.html").is_file() + assert (tmp_path / "build" / "brand" / "nav.css").is_file() + stale = tmp_path / "docs" / "stale.md" + stale.parent.mkdir(parents=True) + stale.write_text("left from an earlier build", encoding="utf-8") assert _run(monkeypatch, etc, "stage") == 0 - assert (tmp_path / "docs" / "pkg" / "guides" / "INTRO.md").is_file() + assert (tmp_path / "docs" / "pkg" / "intro.md").is_file() + assert not stale.exists() assert _run(monkeypatch, etc, "nav") == 0 assert (tmp_path / "overrides" / "site-nav.html").is_file() + assert _run(monkeypatch, etc, "config") == 0 + assert (tmp_path / "zensical.toml").is_file() def test_failed_step_exits_1( monkeypatch: pytest.MonkeyPatch, package_repo: Path, tmp_path: Path ) -> None: """A missing allowlisted file fails the build with exit code 1.""" - etc = _config(tmp_path, package_repo, ["absent.md"]) + package = PACKAGE.replace("demo/demo.gif", "absent.md") + assert _run(monkeypatch, _config(tmp_path, package_repo, package), "build") == 1 + + +def test_package_without_landing_page_fails( + monkeypatch: pytest.MonkeyPatch, package_repo: Path, tmp_path: Path +) -> None: + """Each package needs pages//index.md before its docs are staged.""" + etc = _config(tmp_path, package_repo) + (tmp_path / "pages" / "pkg" / "index.md").unlink() assert _run(monkeypatch, etc, "build") == 1 diff --git a/tests/integration/test_reference_modules.py b/tests/integration/test_reference_modules.py new file mode 100644 index 0000000..ed6f494 --- /dev/null +++ b/tests/integration/test_reference_modules.py @@ -0,0 +1,35 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Finding a package's top-level modules for the generated reference.""" + +from pathlib import Path + +import pytest + +from docsite.config import Reference +from docsite.reference import ReferenceSourceError, reference_modules + + +def _package(root: Path) -> Path: + pkg = root / "src" / "mypkg" + for rel in ("__init__.py", "core.py", "_private.py", "__main__.py", "sub/__init__.py"): + (pkg / rel).parent.mkdir(parents=True, exist_ok=True) + (pkg / rel).write_text("", encoding="utf-8") + (pkg / "docs").mkdir() # a folder without __init__.py is not a module + (pkg / "notes.txt").write_text("", encoding="utf-8") + return pkg + + +def test_public_modules_and_subpackages_sorted(tmp_path: Path) -> None: + """Private modules, plain folders, other files and symlinks are left out.""" + pkg = _package(tmp_path) + (pkg / "linked.py").symlink_to(pkg / "core.py") + ref = Reference(package="mypkg", source="src") + assert reference_modules(tmp_path, ref) == ["mypkg.core", "mypkg.sub"] + + +def test_missing_package_fails(tmp_path: Path) -> None: + """The reference config must point at a package directory.""" + with pytest.raises(ReferenceSourceError, match="not a package"): + reference_modules(tmp_path, Reference(package="mypkg")) diff --git a/tests/integration/test_stage_files.py b/tests/integration/test_stage_files.py index 2e6f559..c6ae95a 100644 --- a/tests/integration/test_stage_files.py +++ b/tests/integration/test_stage_files.py @@ -1,84 +1,109 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors -"""Staging allowlisted docs from a checkout on disk.""" +"""Selecting allowlisted docs from a checkout on disk, and syncing the docs directory.""" from pathlib import Path +from typing import Any from unittest.mock import MagicMock import pytest from appinfra.log import Logger from docsite.config import Package -from docsite.stage import DocsStager, StageError +from docsite.stage import DocsStager, Source, StageError, merge, sync_tree -def _checkout(root: Path, files: dict[str, str]) -> Path: +def _checkout(root: Path, files: dict[str, str], docs_root: str = "docs") -> Path: for rel, text in files.items(): - path = root / "docs" / rel + path = root / docs_root / rel path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") return root -def _package(*docs: str) -> Package: - return Package(name="pkg", repo="r", tag="v1.0.0", docs=docs) +def _package(*docs: Any, **fields: Any) -> Package: + return Package(name="pkg", repo="r", tag="v1.0.0", docs=docs, **fields) -def test_copies_only_allowlisted_files(tmp_path: Path) -> None: - """Listed files land under //guides; unlisted ones are logged, not copied.""" +def test_files_maps_allowlisted_docs_and_logs_the_rest(tmp_path: Path) -> None: + """Listed files map to their sources; unlisted ones are logged and left out.""" checkout = _checkout(tmp_path / "co", {"INTRO.md": "i", "demo/a.gif": "g", "notes.md": "n"}) lg = MagicMock(spec=Logger) - dest = DocsStager(lg, tmp_path / "docs").stage(_package("INTRO.md", "demo/a.gif"), checkout) - assert dest == tmp_path / "docs" / "pkg" / "guides" - assert sorted(p.relative_to(dest).as_posix() for p in dest.rglob("*") if p.is_file()) == [ - "INTRO.md", - "demo/a.gif", - ] - skipped = lg.info.call_args_list[0] - assert skipped.kwargs["extra"]["files"] == ["notes.md"] + files = DocsStager(lg).files(_package("INTRO.md", {"Demo": ["demo/a.gif"]}), checkout) + assert files == { + "INTRO.md": checkout / "docs" / "INTRO.md", + "demo/a.gif": checkout / "docs" / "demo" / "a.gif", + } + assert lg.info.call_args.kwargs["extra"]["files"] == ["notes.md"] + + +def test_docs_root_and_renames_apply(lg: Logger, tmp_path: Path) -> None: + """Docs come from docs_root; a renamed file maps under its new name.""" + checkout = _checkout(tmp_path / "co", {"README.md": "r"}, docs_root="pkg/docs") + pkg = _package("README.md", docs_root="pkg/docs", rename={"README.md": "guide.md"}) + assert DocsStager(lg).files(pkg, checkout) == {"guide.md": checkout / "pkg/docs/README.md"} def test_missing_allowlisted_file_fails(lg: Logger, tmp_path: Path) -> None: """A listed file absent at the tag stops the build.""" checkout = _checkout(tmp_path / "co", {"INTRO.md": "i"}) with pytest.raises(StageError, match="gone.md"): - DocsStager(lg, tmp_path / "docs").stage(_package("INTRO.md", "gone.md"), checkout) + DocsStager(lg).files(_package("INTRO.md", "gone.md"), checkout) + + +def test_checkout_without_docs_dir_fails(lg: Logger, tmp_path: Path) -> None: + """A package without its docs directory has every listed file missing.""" + (tmp_path / "co").mkdir() + with pytest.raises(StageError, match="INTRO.md"): + DocsStager(lg).files(_package("INTRO.md"), tmp_path / "co") def test_symlinked_doc_is_rejected(lg: Logger, tmp_path: Path) -> None: - """A symlink could publish a file from outside docs/.""" + """A symlink could publish a file from outside the docs root.""" checkout = _checkout(tmp_path / "co", {"INTRO.md": "i"}) secret = tmp_path / "secret.txt" secret.write_text("s", encoding="utf-8") (checkout / "docs" / "leak.md").symlink_to(secret) with pytest.raises(StageError, match="symlink"): - DocsStager(lg, tmp_path / "docs").stage(_package("leak.md"), checkout) + DocsStager(lg).files(_package("leak.md"), checkout) -def test_symlinked_docs_root_is_rejected(lg: Logger, tmp_path: Path) -> None: - """docs/ pointing elsewhere would publish that directory's files under allowlisted names.""" +@pytest.mark.parametrize("docs_root", ["docs", "pkg/docs"]) +def test_symlink_in_the_docs_root_path_is_rejected( + lg: Logger, tmp_path: Path, docs_root: str +) -> None: + """A symlinked docs root, or a symlinked folder on the way to it, would list files elsewhere.""" checkout = tmp_path / "co" private = checkout / "private" - private.mkdir(parents=True) + (private / "docs").mkdir(parents=True) (private / "INTRO.md").write_text("private", encoding="utf-8") - (checkout / "docs").symlink_to(private) + (private / "docs" / "INTRO.md").write_text("private", encoding="utf-8") + first = docs_root.split("/")[0] + (checkout / first).symlink_to(private) with pytest.raises(StageError, match="symlink"): - DocsStager(lg, tmp_path / "docs").stage(_package("INTRO.md"), checkout) - assert not (tmp_path / "docs" / "pkg").exists() - - -def test_checkout_without_docs_dir_fails(lg: Logger, tmp_path: Path) -> None: - """A package without docs/ has every listed file missing.""" - (tmp_path / "co").mkdir() - with pytest.raises(StageError, match="INTRO.md"): - DocsStager(lg, tmp_path / "docs").stage(_package("INTRO.md"), tmp_path / "co") - - -def test_restage_removes_files_dropped_from_allowlist(lg: Logger, tmp_path: Path) -> None: - """Staging replaces the previous output, so a delisted file disappears.""" - checkout = _checkout(tmp_path / "co", {"INTRO.md": "i", "old.md": "o"}) - stager = DocsStager(lg, tmp_path / "docs") - stager.stage(_package("INTRO.md", "old.md"), checkout) - dest = stager.stage(_package("INTRO.md"), checkout) - assert not (dest / "old.md").exists() + DocsStager(lg).files(_package("INTRO.md", docs_root=docs_root), checkout) + + +def test_merge_refuses_a_taken_path() -> None: + """Two sources for one docs path is an error, never an overwrite.""" + plan: dict[str, Source] = {"pkg/index.md": "landing"} + merge(plan, {"pkg/guide.md": "g"}, "pkg") + with pytest.raises(StageError, match="pkg/index.md"): + merge(plan, {"pkg/index.md": "other"}, "pkg") + assert plan == {"pkg/index.md": "landing", "pkg/guide.md": "g"} + + +def test_sync_writes_changes_and_removes_leftovers(lg: Logger, tmp_path: Path) -> None: + """The docs directory ends up holding exactly the plan; unchanged files are not rewritten.""" + src = tmp_path / "page.md" + src.write_text("from a file", encoding="utf-8") + root = tmp_path / "docs" + (root / "old" / "deep").mkdir(parents=True) + (root / "old" / "deep" / "gone.md").write_text("stale", encoding="utf-8") + (root / "same.md").write_text("generated", encoding="utf-8") + before = (root / "same.md").stat().st_mtime_ns + sync_tree(lg, {"a/page.md": src, "same.md": "generated"}, root) + assert (root / "a" / "page.md").read_text(encoding="utf-8") == "from a file" + assert (root / "same.md").stat().st_mtime_ns == before + assert not (root / "old").exists() diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 0923e2d..5ff1210 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -108,3 +108,105 @@ def test_unknown_keys_are_rejected() -> None: """A misspelt key fails instead of being silently ignored.""" with pytest.raises(ValidationError): load_build_config(build_dict(packages=[package_dict(doc=["INTRO.md"])])) + + +TREE = [ + {"User guide": "README.md"}, + "start.md", + {"Guides": [{"Config": ["guides/a.md", {"B": "guides/b.md"}]}, "guides/c.md"]}, +] + + +def test_docs_tree_lists_its_files_in_nav_order() -> None: + """Sections and titles are arrangement; the files are the allowlist, in tree order.""" + pkg = load_build_config(build_dict(packages=[package_dict(docs=TREE)])).packages[0] + assert pkg.files == ("README.md", "start.md", "guides/a.md", "guides/b.md", "guides/c.md") + + +@pytest.mark.parametrize( + "entry", + [{"A": "a.md", "B": "b.md"}, {"Empty": []}, {"Number": 3}], +) +def test_docs_entry_shapes_are_checked(entry: object) -> None: + """An entry is a path, {title: path} or {section: [entries]}, nothing else.""" + with pytest.raises(ValidationError, match="docs entry"): + load_build_config(build_dict(packages=[package_dict(docs=[entry])])) + + +def test_docs_paths_inside_sections_are_checked() -> None: + """Nested paths get the same checks as top-level ones.""" + with pytest.raises(ValidationError, match="docs path"): + load_build_config(build_dict(packages=[package_dict(docs=[{"S": ["../x.md"]}])])) + with pytest.raises(ValidationError, match="twice"): + load_build_config(build_dict(packages=[package_dict(docs=["a.md", {"S": ["a.md"]}])])) + + +def test_docs_root_is_a_plain_relative_path() -> None: + """The docs directory is inside the checkout.""" + pkg = load_build_config(build_dict(packages=[package_dict(docs_root="pkg/docs")])).packages[0] + assert pkg.docs_root == "pkg/docs" + with pytest.raises(ValidationError, match="docs_root"): + load_build_config(build_dict(packages=[package_dict(docs_root="../elsewhere")])) + + +def test_rename_maps_a_listed_file() -> None: + """A renamed file lands under its new name; others keep theirs.""" + pkg = load_build_config( + build_dict(packages=[package_dict(docs=TREE, rename={"README.md": "guide.md"})]) + ).packages[0] + assert pkg.site_path("README.md") == "guide.md" + assert pkg.site_path("start.md") == "start.md" + + +@pytest.mark.parametrize( + ("rename", "match"), + [ + ({"absent.md": "x.md"}, "not in docs"), + ({"README.md": "start.md"}, "collides"), + ({"README.md": "../x.md"}, "rename target"), + ], +) +def test_rename_is_checked(rename: dict[str, str], match: str) -> None: + """Renames name a listed file and a free, plain path.""" + with pytest.raises(ValidationError, match=match): + load_build_config(build_dict(packages=[package_dict(docs=TREE, rename=rename)])) + + +def test_reference_is_checked() -> None: + """The reference names an importable package in a plain checkout path.""" + ref = {"package": "llm_saia", "source": "src"} + pkg = load_build_config(build_dict(packages=[package_dict(reference=ref)])).packages[0] + assert pkg.reference is not None and pkg.reference.source == "src" + with pytest.raises(ValidationError, match="import name"): + load_build_config(build_dict(packages=[package_dict(reference={"package": "llm-saia"})])) + with pytest.raises(ValidationError, match="reference source"): + bad = {"package": "x", "source": "/abs"} + load_build_config(build_dict(packages=[package_dict(reference=bad)])) + + +def test_brand_urls_are_checked() -> None: + """The stylesheets come from http(s), or file:// for local previews.""" + brand = build_dict()["brand"] | {"nav_css_url": "ftp://example.com/nav.css"} + with pytest.raises(ValidationError, match="brand stylesheet URL"): + load_build_config(build_dict(brand=brand)) + + +@pytest.mark.parametrize( + "docs_dir", + [ + # the pages: equal, containing, inside + "pages", + ".", + "/", + "pages/docs", + # the checkouts (build_dir is .build/src): equal, containing, inside + ".build/src", + ".build", + ".build/src/docs", + ], +) +def test_docs_dir_is_apart_from_the_inputs(docs_dir: str) -> None: + """stage rebuilds docs_dir, so it cannot overlap the pages or the checkouts either way.""" + site = build_dict()["site"] | {"docs_dir": docs_dir} + with pytest.raises(ValidationError, match="docs_dir"): + load_build_config(build_dict(site=site)) diff --git a/tests/unit/test_fetch_nav.py b/tests/unit/test_fetch_nav.py index 7f81fb4..0c083d2 100644 --- a/tests/unit/test_fetch_nav.py +++ b/tests/unit/test_fetch_nav.py @@ -3,6 +3,7 @@ """Downloading the main site's nav, with urlopen mocked at the call site.""" +import http.client from pathlib import Path from unittest.mock import MagicMock, patch @@ -55,6 +56,16 @@ def test_non_utf8_body_fails() -> None: fetch_nav(MagicMock(spec=Logger), NAV) +def test_truncated_response_fails() -> None: + """A body cut off mid-transfer surfaces as FetchError naming the URL, like a network error.""" + response = _response(200, b"") + response.read.side_effect = http.client.IncompleteRead(b" None: """Connection and HTTP errors surface as FetchError naming the URL.""" with ( diff --git a/tests/unit/test_navtree.py b/tests/unit/test_navtree.py new file mode 100644 index 0000000..c43b4a7 --- /dev/null +++ b/tests/unit/test_navtree.py @@ -0,0 +1,97 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""A package's nav tree: the configured tree with each path where it is staged, and the pages +generated for sections without one.""" + +import pytest + +from docsite.config import load_build_config +from docsite.navtree import ( + NavTreeError, + SectionIndex, + index_sections, + map_paths, + package_nav, + page_title, + render_section_index, +) +from tests.conftest import build_dict, package_dict + + +def test_map_paths_keeps_titles_and_sections() -> None: + """Only paths change; titles and nesting stay.""" + tree = ["a.md", {"T": "b.md"}, {"S": ["c.md", {"U": ["d.md"]}]}] + assert map_paths(tree, str.upper) == ["A.MD", {"T": "B.MD"}, {"S": ["C.MD", {"U": ["D.MD"]}]}] + + +def test_package_nav_applies_renames_at_any_depth() -> None: + """A renamed file appears in the nav under the name it is staged as.""" + docs = [{"Guide": "README.md"}, {"Sub": ["sub/README.md", "sub/x.md"]}] + rename = {"README.md": "guide.md", "sub/README.md": "sub/overview.md"} + pkg = load_build_config(build_dict(packages=[package_dict(docs=docs, rename=rename)])).packages[ + 0 + ] + assert package_nav(pkg) == [{"Guide": "guide.md"}, {"Sub": ["sub/overview.md", "sub/x.md"]}] + + +def test_index_sections_adds_a_page_to_sections_without_one() -> None: + """A section gets a generated page first, at its titles slugged; nested sections too.""" + tree = ["intro.md", {"Guides": [{"Dev tooling": ["g/a.md"]}, {"B": "g/b.md"}]}] + out, pages = index_sections(tree) + assert out == [ + "intro.md", + { + "Guides": [ + "guides/index.md", + {"Dev tooling": ["guides/dev-tooling/index.md", "g/a.md"]}, + {"B": "g/b.md"}, + ] + }, + ] + assert pages == { + "guides/dev-tooling/index.md": SectionIndex("Dev tooling", ("g/a.md",)), + "guides/index.md": SectionIndex( + "Guides", ({"Dev tooling": ["guides/dev-tooling/index.md", "g/a.md"]}, {"B": "g/b.md"}) + ), + } + + +def test_index_sections_keeps_a_section_page_of_its_own() -> None: + """A section whose first entry is an index or README page already has its page.""" + tree = [{"A": ["a/index.md", "a/x.md"]}, {"B": [{"Over": "b/README.md"}, "b/y.md"]}] + assert index_sections(tree) == (tree, {}) + + +def test_index_sections_rejects_a_title_without_a_path() -> None: + """A title with no letters or digits gives no path for its page.""" + with pytest.raises(NavTreeError, match="no letters or digits"): + index_sections([{"--": ["a.md"]}]) + + +def test_render_section_index_links_each_entry() -> None: + """Links are relative to the page; bare paths take their page's title, sections their page.""" + index = SectionIndex( + "Guides [all]", ("g/a.md", {"Titled": "g/b.md"}, {"Sub": ["guides/sub/index.md", "x.md"]}) + ) + titles = {"g/a.md": "Page A"} + assert render_section_index("guides/index.md", index, titles.__getitem__) == ( + "# Guides [all]\n\n- [Page A](../g/a.md)\n- [Titled](../g/b.md)\n- [Sub](sub/index.md)\n" + ) + + +@pytest.mark.parametrize( + ("text", "title"), + [ + ("---\ntitle: 'From front'\n---\n# Heading\n", "From front"), + ("---\nkeywords: [a]\n---\n\n# Heading #\n", "Heading"), + ("```\n# not a title\n```\n# Real\n", "Real"), + # A fence closes only on its own character, at least as long as it opened + ("~~~\n```\n# not a title\n~~~\n# Real\n", "Real"), + ("````\n```\n# not a title\n```\n````\n# Real\n", "Real"), + ("## Only a subheading\n", "Getting started"), + ], +) +def test_page_title_follows_the_site(text: str, title: str) -> None: + """Front matter title, else the first level-1 heading outside code, else the file name.""" + assert page_title(text, "docs/getting-started.md") == title diff --git a/tests/unit/test_reference_pages.py b/tests/unit/test_reference_pages.py new file mode 100644 index 0000000..08ec273 --- /dev/null +++ b/tests/unit/test_reference_pages.py @@ -0,0 +1,38 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""The generated reference's pages and nav section, from a module list.""" + +from docsite.config import load_build_config +from docsite.reference import NAV_TITLE, reference_nav, reference_pages +from tests.conftest import build_dict, package_dict + +MODULES = ["llm_saia.core", "llm_saia.verbs"] + + +def test_one_page_per_module_rendered_by_mkdocstrings() -> None: + """Each module page titles the module and hands it to mkdocstrings.""" + pkg = load_build_config(build_dict(packages=[package_dict()])).packages[0] + pages = reference_pages(pkg, MODULES) + assert pages["reference/core.md"] == "# llm_saia.core\n\n::: llm_saia.core\n" + assert set(pages) == {"reference/index.md", "reference/core.md", "reference/verbs.md"} + + +def test_index_names_the_tag_and_links_every_module() -> None: + """The landing page says what the reference is generated from.""" + pkg = load_build_config(build_dict(packages=[package_dict()])).packages[0] + index = reference_pages(pkg, MODULES)["reference/index.md"] + assert f"# {NAV_TITLE}" in index + assert "llm-saia v0.6.3" in index + assert "[`llm_saia.verbs`](verbs.md)" in index + + +def test_nav_section_lists_modules_by_short_name() -> None: + """The section opens with the index, then one entry per module.""" + assert reference_nav(MODULES) == { + NAV_TITLE: [ + "reference/index.md", + {"core": "reference/core.md"}, + {"verbs": "reference/verbs.md"}, + ] + } diff --git a/tests/unit/test_siteconf.py b/tests/unit/test_siteconf.py new file mode 100644 index 0000000..a074ffa --- /dev/null +++ b/tests/unit/test_siteconf.py @@ -0,0 +1,72 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Rendering the Zensical config from the base config and the package trees.""" + +from typing import Any + +import pytest + +from docsite.siteconf import SiteConfigError, render_site_config + + +def _base() -> dict[str, Any]: + return { + "project": { + "site_name": "Docs", + "nav": [ + {"Home": "index.md"}, + { + "Packages": [ + "packages/index.md", + {"pkg": "pkg/index.md"}, + {"other": "other/index.md"}, + ] + }, + ], + } + } + + +def test_package_entry_expands_under_its_landing_page() -> None: + """The landing page stays first, the tree follows under /; other entries stay.""" + tree = ["guide.md", {"API": ["api/a.md"]}] + config = render_site_config(_base(), {"pkg": tree}, [], "docs") + packages = config["project"]["nav"][1]["Packages"] + assert packages[1] == {"pkg": ["pkg/index.md", "pkg/guide.md", {"API": ["pkg/api/a.md"]}]} + assert packages[2] == {"other": "other/index.md"} + + +def test_base_is_not_modified() -> None: + """The base mapping can be rendered again.""" + base = _base() + render_site_config(base, {"pkg": ["guide.md"]}, [], "docs") + assert base == _base() + + +def test_reference_sources_point_mkdocstrings_at_checkouts() -> None: + """With references, the Python handler reads the given checkout directories.""" + config = render_site_config(_base(), {}, [".build/src/pkg"], "docs") + handler = config["project"]["plugins"]["mkdocstrings"]["handlers"]["python"] + assert handler["paths"] == [".build/src/pkg"] + assert "plugins" not in render_site_config(_base(), {}, [], "docs")["project"] + + +def test_docs_dir_is_the_staged_directory() -> None: + """Zensical reads the directory stage fills, whatever the base config says.""" + base = _base() + base["project"]["docs_dir"] = "elsewhere" + config = render_site_config(base, {}, [], docs_dir="build/docs") + assert config["project"]["docs_dir"] == "build/docs" + + +def test_package_without_an_entry_fails() -> None: + """A configured package needs its landing entry in the base nav.""" + with pytest.raises(SiteConfigError, match="'absent'"): + render_site_config(_base(), {"absent": []}, [], "docs") + + +def test_base_without_packages_section_fails() -> None: + """The base nav must have the Packages section.""" + with pytest.raises(SiteConfigError, match="Packages"): + render_site_config({"project": {"nav": [{"Home": "index.md"}]}}, {"pkg": []}, [], "docs") diff --git a/tests/unit/test_sitenav.py b/tests/unit/test_sitenav.py index 5f5b7a2..2260b78 100644 --- a/tests/unit/test_sitenav.py +++ b/tests/unit/test_sitenav.py @@ -8,7 +8,6 @@ from docsite.sitenav import ( DOCS_ITEM, GENERATED_MARK, - SEARCH, THEME_SWITCH, NavMarkupError, docs_nav, @@ -56,13 +55,13 @@ def test_main_site_current_marker_is_dropped() -> None: assert "Platform" in html and 'aria-current="page">Platform' not in html -def test_docs_item_follows_platform_and_search_follows_logo() -> None: - """The Docs item and the search box land at their anchors.""" - lines = docs_nav(NAV, ORIGIN, DOCS).splitlines(keepends=True) +def test_docs_item_follows_platform() -> None: + """The Docs item lands right after Platform; the header carries no search.""" + html = docs_nav(NAV, ORIGIN, DOCS) + lines = html.splitlines(keepends=True) platform = next(i for i, line in enumerate(lines) if "/platform/" in line) - logo = next(i for i, line in enumerate(lines) if 'class="logo"' in line) assert lines[platform + 1] == DOCS_ITEM - assert lines[logo + 1] == SEARCH + assert "search" not in html def test_existing_docs_link_is_marked_instead_of_duplicated() -> None: @@ -86,14 +85,10 @@ def test_empty_origin_keeps_links_root_relative() -> None: assert DOCS_ITEM in html -@pytest.mark.parametrize( - ("needle", "what"), - [('class="logo"', "logo"), ('href="/platform/"', "Platform item")], -) -def test_missing_anchor_fails_loudly(needle: str, what: str) -> None: - """A nav without the logo or the Platform item cannot be rendered.""" - with pytest.raises(NavMarkupError, match=what): - docs_nav(NAV.replace(needle, 'class="other"'), ORIGIN, DOCS) +def test_missing_platform_item_fails_loudly() -> None: + """Without the Platform item there is no place for the Docs item.""" + with pytest.raises(NavMarkupError, match="Platform item"): + docs_nav(NAV.replace('href="/platform/"', 'class="other"'), ORIGIN, DOCS) def test_header_wraps_nav_with_mark_and_theme_switch() -> None: @@ -101,3 +96,9 @@ def test_header_wraps_nav_with_mark_and_theme_switch() -> None: header = render_header(NAV, ORIGIN, DOCS) assert header.startswith(GENERATED_MARK) assert header.endswith(THEME_SWITCH) + + +def test_nav_with_its_own_theme_switch_gets_no_second_one() -> None: + """Once the main site's partial carries the switch, the header keeps exactly that one.""" + header = render_header(NAV + THEME_SWITCH, ORIGIN, DOCS) + assert header.count('id="theme-switch"') == 1