diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 26955e5..3b7ae33 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,8 @@ jobs: # TODO: remove after appinfra is released to PyPI # check: ruff, mypy and pylint, which the duplicated-code check runs python -m pip install "appinfra[check] @ git+https://github.com/llm-works/appinfra.git@develop" + # the project's own dependencies (pydantic), so mypy sees real types + python -m pip install -e ".[dev]" - name: Lint workflows # zizmor policy in .github/zizmor.yml; actionlint runs shellcheck on run: scripts diff --git a/.gitignore b/.gitignore index 9d0b3af..22693e6 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,7 @@ venv/ # Site build: Zensical cache and output .cache/ site/ + +# Generated by `python -m docsite`: staged package docs and the rendered header +docs/*/guides/ +overrides/partials/site-nav.html diff --git a/docsite/__main__.py b/docsite/__main__.py new file mode 100644 index 0000000..4701a71 --- /dev/null +++ b/docsite/__main__.py @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Allow running as `python -m docsite`.""" + +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docsite/build.py b/docsite/build.py new file mode 100644 index 0000000..de80a47 --- /dev/null +++ b/docsite/build.py @@ -0,0 +1,60 @@ +# 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.""" + +from pathlib import Path + +from appinfra.log import Logger + +from .config import BuildConfig +from .fetch import PackageFetcher, fetch_nav +from .sitenav import render_header +from .stage import DocsStager + +NAV_SOURCE = "nav.html" + + +class Build: + """Runs the build steps for one configuration; each step reads the previous one's output.""" + + def __init__(self, lg: Logger, cfg: BuildConfig) -> None: + self._lg = lg + self._cfg = cfg + + def fetch(self) -> None: + """Clone every package at its tag and download the nav partial.""" + 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") + + 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) + for pkg in self._cfg.packages: + stager.stage(pkg, self._cfg.site.build_dir / pkg.name) + + def nav(self) -> Path: + """Render the fetched nav as the docs header partial.""" + nav_html = self._nav_source.read_text(encoding="utf-8") + nav = self._cfg.nav + output = nav.output + output.parent.mkdir(parents=True, exist_ok=True) + header = render_header(nav_html, nav.site_origin, nav.docs_origin) + output.write_text(header, encoding="utf-8") + self._lg.info("header rendered", extra={"output": str(output)}) + return output + + def all(self) -> None: + """Fetch, stage and render, in order.""" + self.fetch() + self.stage() + self.nav() + + @property + def _nav_source(self) -> Path: + """Where fetch saves the nav partial and nav reads it.""" + return self._cfg.site.build_dir / NAV_SOURCE diff --git a/docsite/cli/__init__.py b/docsite/cli/__init__.py new file mode 100644 index 0000000..33dffc9 --- /dev/null +++ b/docsite/cli/__init__.py @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Command-line interface: `python -m docsite `.""" + +from .cli import main + +__all__ = ["main"] diff --git a/docsite/cli/cli.py b/docsite/cli/cli.py new file mode 100644 index 0000000..288a9e9 --- /dev/null +++ b/docsite/cli/cli.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""CLI entry point for the docs build.""" + +from appinfra.app import AppBuilder + +from .tools import BuildTool, FetchTool, NavTool, StageTool + + +def main() -> int: + """Build the app from etc/docsite.yaml and run the requested step.""" + app = ( + AppBuilder("docsite") + .with_description("Build tooling for docs.llm-works.ai") + # The repo root holds etc/docsite.yaml; origin is relative to this file. + .config.with_spec("llm-works", "docsite", origin="../..") + .done() + .cli.with_all_flags() + .done() + .tools.with_tools(FetchTool(), StageTool(), NavTool(), BuildTool()) + .done() + .build() + ) + result: int = app.main() + return result diff --git a/docsite/cli/tools.py b/docsite/cli/tools.py new file mode 100644 index 0000000..711f5e8 --- /dev/null +++ b/docsite/cli/tools.py @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""One CLI tool per build step.""" + +from typing import Any, ClassVar + +from appinfra.app.tools import Tool, ToolConfig +from pydantic import ValidationError + +from ..build import Build +from ..config import load_build_config +from ..fetch import FetchError +from ..sitenav import NavMarkupError +from ..stage import StageError + +_STEP_ERRORS = (ValidationError, FetchError, StageError, NavMarkupError, OSError) + + +class _StepTool(Tool): + """Loads the build config and runs one step; a failed step exits 1.""" + + name: ClassVar[str] + help_text: ClassVar[str] + + def __init__(self, parent: Any = None) -> None: + """Register under the subclass's step name.""" + super().__init__(parent, ToolConfig(name=self.name, help_text=self.help_text)) + + def run(self, **kwargs: Any) -> int: + """Run the step; log and return 1 on a config, fetch, stage or nav error.""" + try: + build = Build(self.lg, load_build_config(self.app.config)) + self._step(build) + except _STEP_ERRORS as e: + self.lg.error("build step failed", extra={"step": self.name, "exception": e}) + return 1 + return 0 + + def _step(self, build: Build) -> None: + """The step itself; each subclass calls one Build method.""" + raise NotImplementedError + + +class FetchTool(_StepTool): + """Clone packages at their tags and download the nav partial.""" + + name = "fetch" + help_text = "Clone each package at its tag and download the main site's nav" + + def _step(self, build: Build) -> None: + """Run Build.fetch.""" + build.fetch() + + +class StageTool(_StepTool): + """Copy allowlisted docs into the site.""" + + name = "stage" + help_text = "Copy each package's allowlisted docs into the site's docs directory" + + def _step(self, build: Build) -> None: + """Run Build.stage.""" + build.stage() + + +class NavTool(_StepTool): + """Render the docs header from the fetched nav.""" + + name = "nav" + help_text = "Render the docs header from the fetched nav" + + def _step(self, build: Build) -> None: + """Run Build.nav.""" + build.nav() + + +class BuildTool(_StepTool): + """Run every step.""" + + name = "build" + help_text = "Fetch, stage and render the header" + + def _step(self, build: Build) -> None: + """Run Build.all.""" + build.all() diff --git a/docsite/config.py b/docsite/config.py new file mode 100644 index 0000000..181d711 --- /dev/null +++ b/docsite/config.py @@ -0,0 +1,151 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Typed build configuration, validated from the `site`, `nav` and `packages` sections.""" + +import re +from collections.abc import Mapping +from pathlib import Path, PurePosixPath +from typing import Any +from urllib.parse import urlsplit + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +# A package name becomes a directory name; keep it to a plain slug. +_NAME = re.compile(r"^[a-z0-9][a-z0-9-]*$") +# A tag is passed to git; no leading dash, no path or shell metacharacters. +_TAG = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") +_GLOB_CHARS = frozenset("*?[]") + + +class _Frozen(BaseModel): + """Immutable model that rejects unknown keys, so a misspelt key fails loudly.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + +class SiteConfig(_Frozen): + """Where checkouts and staged docs go.""" + + build_dir: Path + docs_dir: Path + + +class NavConfig(_Frozen): + """The main site's nav partial and where the rendered header goes.""" + + url: str + site_origin: str + docs_origin: str + output: Path + timeout_s: float = Field(default=10.0, gt=0) + + @field_validator("url") + @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") + return value + + @field_validator("site_origin") + @classmethod + def _site_origin_form(cls, value: str) -> str: + """An origin without a trailing slash, or empty for root-relative links.""" + if value: + _check_origin("nav.site_origin", value) + return value + + @field_validator("docs_origin") + @classmethod + def _docs_origin_form(cls, value: str) -> str: + """The docs site's origin, without a trailing slash.""" + _check_origin("nav.docs_origin", value) + return value + + +def _check_origin(field: str, value: str) -> None: + """Reject anything but scheme://host[:port], with no path, query or fragment.""" + parts = urlsplit(value) + # Comparing against the rebuilt origin also catches what urlsplit drops, like a bare '?'. + if ( + parts.scheme not in ("https", "http") + or not parts.hostname + or value != f"{parts.scheme}://{parts.netloc}" + ): + raise ValueError(f"{field} must be an http(s) origin: scheme://host[:port], nothing after") + + +class Package(_Frozen): + """One package: its repo, the release tag to build from, and its docs allowlist.""" + + name: str + repo: str = Field(min_length=1) + tag: str + docs: tuple[str, ...] = Field(min_length=1) + + @field_validator("name") + @classmethod + def _name_slug(cls, value: str) -> str: + """The name becomes a directory name.""" + if not _NAME.fullmatch(value): + raise ValueError(f"package name {value!r} must be a lowercase slug") + return value + + @field_validator("tag") + @classmethod + def _tag_form(cls, value: str) -> str: + """The tag is passed to git, so it cannot look like an option.""" + if not _TAG.fullmatch(value): + raise ValueError(f"tag {value!r} is not a plain tag name") + 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): + raise ValueError("docs allowlist lists a path twice") + return value + + +def _check_doc_path(path: str) -> None: + """Reject paths that could escape docs/ 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/") + if _GLOB_CHARS & set(path): + raise ValueError(f"docs path {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.""" + + site: SiteConfig + nav: NavConfig + packages: tuple[Package, ...] + + @model_validator(mode="after") + def _unique_names(self) -> "BuildConfig": + """Two packages cannot stage into the same directory.""" + names = [pkg.name for pkg in self.packages] + if len(set(names)) != len(names): + raise ValueError("package names must be unique") + return self + + +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")} + return BuildConfig.model_validate(sections) + + +def _plain(value: Any) -> Any: + """Turn the config library's mapping and sequence types into dicts and lists.""" + if isinstance(value, Mapping): + return {key: _plain(item) for key, item in value.items()} + if isinstance(value, list | tuple): + return [_plain(item) for item in value] + return value diff --git a/docsite/fetch.py b/docsite/fetch.py new file mode 100644 index 0000000..219c85a --- /dev/null +++ b/docsite/fetch.py @@ -0,0 +1,94 @@ +# 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.""" + +import shutil +import subprocess +import urllib.request +from pathlib import Path + +from appinfra.log import Logger + +from .config import NavConfig, Package + +# www.llm-works.ai sits behind Cloudflare, which rejects urllib's default User-Agent with a +# 403; an agent naming this build is accepted. +USER_AGENT = "llm-works-docs-build (+https://github.com/llm-works/docs)" + + +class FetchError(RuntimeError): + """A package or the nav partial could not be fetched.""" + + +class PackageFetcher: + """Shallow-clones packages at their pinned tags into the build directory.""" + + def __init__(self, lg: Logger, build_dir: Path) -> None: + self._lg = lg + self._build_dir = build_dir + + def fetch(self, pkg: Package) -> Path: + """Clone `pkg` at its tag into /, replacing an older checkout.""" + dest = self._build_dir / pkg.name + if dest.exists(): + shutil.rmtree(dest) + self._build_dir.mkdir(parents=True, exist_ok=True) + _git( + "-c", "advice.detachedHead=false", "clone", "--quiet", "--depth", "1", + "--branch", pkg.tag, "--", pkg.repo, str(dest), + ) # fmt: skip + try: + _check_pin(dest, pkg) + except FetchError: + # A later stage step must not find the rejected checkout. + shutil.rmtree(dest) + raise + self._lg.info("package fetched", extra={"package": pkg.name, "tag": pkg.tag}) + return dest + + +def _check_pin(dest: Path, pkg: Package) -> None: + """Fail unless HEAD is the tagged commit; ^{commit} peels an annotated tag. + + --branch also accepts a branch, and prefers one that shares the tag's name; only the + tagged commit is a valid pin. + """ + error = f"{pkg.name}: checkout is not at tag {pkg.tag}" + head = _git("-C", str(dest), "rev-parse", "HEAD") + try: + tagged = _git("-C", str(dest), "rev-parse", "--verify", f"refs/tags/{pkg.tag}^{{commit}}") + except FetchError as e: + # A shallow clone of a branch lacks any tag that points at an older commit. + raise FetchError(error) from e + if head != tagged: + raise FetchError(error) + + +def _git(*args: str) -> str: + """Run git and return its stripped stdout; raise FetchError with stderr when it fails.""" + result = subprocess.run(["git", *args], capture_output=True, text=True, check=False) + if result.returncode != 0: + detail = result.stderr.strip() or f"git exited with {result.returncode}" + raise FetchError(detail) + return result.stdout.strip() + + +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}) + try: + with urllib.request.urlopen(request, timeout=nav.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 + if status is not None and status != 200: + raise FetchError(f"nav download from {nav.url} returned HTTP {status}") + try: + html = 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 diff --git a/docsite/sitenav.py b/docsite/sitenav.py new file mode 100644 index 0000000..1089ed3 --- /dev/null +++ b/docsite/sitenav.py @@ -0,0 +1,69 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Render the main site's nav partial as the docs header. + +The markup stays the main site's own, with three changes: + +- root-relative links point at the main site's origin (an empty origin keeps them + 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 output is a Jinja partial for the Zensical theme override. +""" + +import re + +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 = """\ + +""" + +_CURRENT = ' aria-current="page"' +_ROOT_HREF = re.compile(r'href="/(?!/)') + + +class NavMarkupError(ValueError): + """The nav partial lacks an anchor the docs header depends on.""" + + +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 + + +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") + + +def _mark_docs_item(html: str, site_origin: str, docs_origin: str) -> str: + """Mark the nav's link to `docs_origin` current, or add a Docs item after Platform.""" + existing = re.search(rf'href="{re.escape(docs_origin)}/?"', html) + if existing: + end = existing.end() + return html[:end] + _CURRENT + html[end:] + platform = rf'.*href="{re.escape(site_origin)}/platform/".*\n' + return _insert_after(html, platform, DOCS_ITEM, "Platform item") + + +def _insert_after(html: str, line_pattern: str, insert: str, what: str) -> str: + """Insert `insert` after the first line matching `line_pattern`.""" + match = re.search(line_pattern, html) + if not match: + raise NavMarkupError(f"no {what} in the main site's nav") + return html[: match.end()] + insert + html[match.end() :] diff --git a/docsite/stage.py b/docsite/stage.py new file mode 100644 index 0000000..4ee4b7f --- /dev/null +++ b/docsite/stage.py @@ -0,0 +1,85 @@ +# 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.""" + +import shutil +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path + +from appinfra.log import Logger + +from .config import Package + + +class StageError(RuntimeError): + """A package's docs do not match its allowlist.""" + + +@dataclass(frozen=True) +class Selection: + """How a package's docs/ compares with its allowlist.""" + + copy: tuple[str, ...] + missing: tuple[str, ...] + unlisted: tuple[str, ...] + + +def select(available: Iterable[str], allowlist: Sequence[str]) -> Selection: + """Split docs/ files into those to copy, listed-but-absent, and present-but-unlisted.""" + present = set(available) + listed = set(allowlist) + return Selection( + copy=tuple(path for path in allowlist if path in present), + missing=tuple(path for path in allowlist if path not in present), + unlisted=tuple(sorted(present - listed)), + ) + + +class DocsStager: + """Copies allowlisted docs from a checkout to //guides.""" + + def __init__(self, lg: Logger, docs_dir: Path) -> 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) + if sel.missing: + raise StageError(f"{pkg.name} {pkg.tag}: allowlisted docs missing: {list(sel.missing)}") + if sel.unlisted: + self._lg.info( + "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) + 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 + + +def _list_files(root: Path) -> list[str]: + """Every file and symlink under `root`, as POSIX paths relative to it.""" + if not root.is_dir(): + 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/etc/docsite.yaml b/etc/docsite.yaml new file mode 100644 index 0000000..8c6acaf --- /dev/null +++ b/etc/docsite.yaml @@ -0,0 +1,40 @@ +# docsite build configuration, loaded by `python -m docsite` (appinfra config spec). + +logging: + level: info + handlers: + console: + type: console + enabled: true + format: text + stream: stderr + colors: true + +site: + # Package checkouts and the downloaded nav partial + build_dir: .build/src + # Zensical docs_dir; each package's guides are staged under //guides + docs_dir: docs + +# The header is the main site's nav, fetched live at every build so a nav change on +# www.llm-works.ai needs only a docs rebuild, not a change here. +nav: + url: https://www.llm-works.ai/partials/nav.html + # Root-relative links in the nav are rewritten to this origin + site_origin: https://www.llm-works.ai + # This site's origin: a link to it in the main site's nav becomes the current Docs item + docs_origin: https://docs.llm-works.ai + output: overrides/partials/site-nav.html + timeout_s: 10 + +# Each package is fetched at a pinned release tag. `docs` is an allowlist of paths under +# the package's docs/ directory: only these files are published, so internal notes in a +# package's docs/ never reach the site. No wildcards: a new file must be listed to ship. +# +# - name: appinfra +# repo: https://github.com/llm-works/appinfra.git +# tag: vX.Y.Z +# docs: +# - index.md +# - guides/getting-started.md +packages: [] diff --git a/pyproject.toml b/pyproject.toml index d348e32..4960beb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,7 +19,10 @@ classifiers = [ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.12", ] -dependencies = [] +dependencies = [ + # validation: pydantic, for the build config models + "appinfra[validation]>=0.14.0", +] [project.optional-dependencies] dev = [ diff --git a/tests/conftest.py b/tests/conftest.py index f9a8d32..90ae4f7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,5 +3,44 @@ """Shared pytest configuration for all test suites.""" +from typing import Any + +import pytest +from appinfra.log import LogConfig, Logger, LoggerFactory + # Gives each test the suite of its marker or its tests// directory pytest_plugins = ["appinfra.pytest_suites"] + + +@pytest.fixture(scope="session") +def lg() -> Logger: + """A real logger that only prints errors, for tests that do not inspect log calls.""" + return LoggerFactory.create_root(LogConfig.from_params(level="error")) + + +def package_dict(**overrides: Any) -> dict[str, Any]: + """A valid `packages` entry, with fields replaced by `overrides`.""" + pkg: dict[str, Any] = { + "name": "llm-saia", + "repo": "https://github.com/llm-works/llm-saia.git", + "tag": "v0.6.3", + "docs": ["INTRO.md", "demo/demo.gif"], + } + pkg.update(overrides) + return pkg + + +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"}, + "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", + }, + "packages": [package_dict()], + } + cfg.update(overrides) + return cfg diff --git a/docsite/site.py b/tests/integration/__init__.py similarity index 51% rename from docsite/site.py rename to tests/integration/__init__.py index 39d8a50..7bd7114 100644 --- a/docsite/site.py +++ b/tests/integration/__init__.py @@ -1,6 +1,2 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors - -"""Site-wide constants shared by the build steps.""" - -SITE_URL = "https://docs.llm-works.ai/" diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 0000000..8a4cb3b --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""A local git repository standing in for a package repo, so fetch needs no network.""" + +import subprocess +from pathlib import Path + +import pytest + +TAG = "v1.0.0" +DOCS = { + "INTRO.md": "# Intro\n\n![demo](./demo/demo.gif)\n", + "demo/demo.gif": "GIF89a", + "known-issues.md": "internal notes\n", +} + + +def git(cwd: Path, *args: str) -> None: + """Run git in `cwd` with a fixed test identity.""" + subprocess.run( + ["git", "-c", "user.name=test", "-c", "user.email=test@example.invalid", *args], + cwd=cwd, + check=True, + capture_output=True, + ) + + +@pytest.fixture +def package_repo(tmp_path: Path) -> Path: + """A repo with docs/ committed and tagged TAG, plus a branch named `rel`.""" + repo = tmp_path / "pkg-repo" + for rel, text in DOCS.items(): + path = repo / "docs" / 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)) + git(repo, "add", ".") + git(repo, "commit", "--quiet", "-m", "docs") + git(repo, "tag", TAG) + git(repo, "branch", "rel") + return repo diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py new file mode 100644 index 0000000..96676dc --- /dev/null +++ b/tests/integration/test_cli.py @@ -0,0 +1,90 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""The CLI steps, in process, with a config pointing at local inputs.""" + +import sys +from pathlib import Path + +import pytest + +from docsite.cli import main +from tests.integration.conftest import TAG + +NAV = """\ + +""" + + +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") + etc = tmp_path / "etc" + etc.mkdir() + allowlist = "".join(f" - {path}\n" for path in docs) + (etc / "docsite.yaml").write_text( + f"""\ +logging: + level: error +site: + build_dir: {tmp_path / "build"} + docs_dir: {tmp_path / "docs"} +nav: + url: {nav_file.as_uri()} + site_origin: https://www.llm-works.ai + docs_origin: https://docs.llm-works.ai + output: {tmp_path / "overrides" / "site-nav.html"} +packages: + - name: pkg + repo: {repo} + tag: {TAG} + docs: +{allowlist}""", + encoding="utf-8", + ) + return etc + + +def _run(monkeypatch: pytest.MonkeyPatch, etc: Path, step: str) -> int: + monkeypatch.setattr(sys, "argv", ["docsite", "--etc-dir", str(etc), step]) + return main() + + +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() + header = (tmp_path / "overrides" / "site-nav.html").read_text(encoding="utf-8") + assert 'href="https://www.llm-works.ai/platform/"' in header + + +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"]) + assert _run(monkeypatch, etc, "fetch") == 0 + assert (tmp_path / "build" / "nav.html").is_file() + assert _run(monkeypatch, etc, "stage") == 0 + assert (tmp_path / "docs" / "pkg" / "guides" / "INTRO.md").is_file() + assert _run(monkeypatch, etc, "nav") == 0 + assert (tmp_path / "overrides" / "site-nav.html").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"]) + assert _run(monkeypatch, etc, "build") == 1 diff --git a/tests/integration/test_fetch_git.py b/tests/integration/test_fetch_git.py new file mode 100644 index 0000000..f5c1f83 --- /dev/null +++ b/tests/integration/test_fetch_git.py @@ -0,0 +1,91 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Cloning packages at their tags with real git, against a local repository.""" + +import subprocess +from pathlib import Path + +import pytest +from appinfra.log import Logger + +from docsite.config import Package +from docsite.fetch import FetchError, PackageFetcher +from tests.integration.conftest import TAG, git + + +def _package(repo: Path, tag: str = TAG) -> Package: + # A file:// URL goes through git's transport like a remote, so --depth applies; a plain + # path takes the local-copy shortcut, which ignores it. + return Package(name="pkg", repo=repo.as_uri(), tag=tag, docs=("INTRO.md",)) + + +def test_clones_the_tag_into_build_dir(lg: Logger, package_repo: Path, tmp_path: Path) -> None: + """The checkout holds the tagged docs, as a shallow clone.""" + dest = PackageFetcher(lg, tmp_path / "build").fetch(_package(package_repo)) + assert dest == tmp_path / "build" / "pkg" + assert (dest / "docs" / "INTRO.md").is_file() + shallow = subprocess.run( + ["git", "-C", str(dest), "rev-parse", "--is-shallow-repository"], + capture_output=True, + text=True, + check=True, + ) + assert shallow.stdout.strip() == "true" + + +def test_refetch_replaces_the_old_checkout(lg: Logger, package_repo: Path, tmp_path: Path) -> None: + """Files left from an earlier fetch do not survive a new one.""" + fetcher = PackageFetcher(lg, tmp_path / "build") + stale = fetcher.fetch(_package(package_repo)) / "stale.md" + stale.write_text("old", encoding="utf-8") + fetcher.fetch(_package(package_repo)) + assert not stale.exists() + + +def test_unknown_tag_fails(lg: Logger, package_repo: Path, tmp_path: Path) -> None: + """A tag that does not exist stops the build with git's message.""" + with pytest.raises(FetchError, match="v9.9.9"): + PackageFetcher(lg, tmp_path / "build").fetch(_package(package_repo, "v9.9.9")) + + +def test_branch_sharing_the_tag_name_is_rejected( + lg: Logger, package_repo: Path, tmp_path: Path +) -> None: + """clone --branch prefers a same-name branch; its newer commit is not the pinned one.""" + (package_repo / "docs" / "INTRO.md").write_text("# Newer\n", encoding="utf-8") + git(package_repo, "commit", "--quiet", "-am", "newer") + git(package_repo, "branch", TAG) + with pytest.raises(FetchError, match=f"not at tag {TAG}"): + PackageFetcher(lg, tmp_path / "build").fetch(_package(package_repo)) + assert not (tmp_path / "build" / "pkg").exists() + + +def test_branch_sharing_the_tag_name_is_rejected_in_a_full_clone( + lg: Logger, package_repo: Path, tmp_path: Path +) -> None: + """A plain-path repo is copied whole, so the tag is present but HEAD is the branch.""" + (package_repo / "docs" / "INTRO.md").write_text("# Newer\n", encoding="utf-8") + git(package_repo, "commit", "--quiet", "-am", "newer") + git(package_repo, "branch", TAG) + pkg = Package(name="pkg", repo=str(package_repo), tag=TAG, docs=("INTRO.md",)) + with pytest.raises(FetchError, match=f"not at tag {TAG}") as raised: + PackageFetcher(lg, tmp_path / "build").fetch(pkg) + assert raised.value.__cause__ is None + assert not (tmp_path / "build" / "pkg").exists() + + +def test_annotated_tag_is_accepted(lg: Logger, package_repo: Path, tmp_path: Path) -> None: + """An annotated tag resolves to its commit, so the pin check passes.""" + git(package_repo, "tag", "-a", "v2.0.0", "-m", "release") + dest = PackageFetcher(lg, tmp_path / "build").fetch(_package(package_repo, "v2.0.0")) + assert (dest / "docs" / "INTRO.md").is_file() + + +def test_branch_name_is_not_accepted_as_a_pin( + lg: Logger, package_repo: Path, tmp_path: Path +) -> None: + """git clone --branch takes branches too; only a release tag is a valid pin.""" + with pytest.raises(FetchError, match="pkg: checkout is not at tag rel"): + PackageFetcher(lg, tmp_path / "build").fetch(_package(package_repo, "rel")) + assert not (tmp_path / "build" / "pkg").exists() diff --git a/tests/integration/test_stage_files.py b/tests/integration/test_stage_files.py new file mode 100644 index 0000000..2e6f559 --- /dev/null +++ b/tests/integration/test_stage_files.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Staging allowlisted docs from a checkout on disk.""" + +from pathlib import Path +from unittest.mock import MagicMock + +import pytest +from appinfra.log import Logger + +from docsite.config import Package +from docsite.stage import DocsStager, StageError + + +def _checkout(root: Path, files: dict[str, str]) -> Path: + for rel, text in files.items(): + path = root / "docs" / 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 test_copies_only_allowlisted_files(tmp_path: Path) -> None: + """Listed files land under //guides; unlisted ones are logged, not copied.""" + 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"] + + +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) + + +def test_symlinked_doc_is_rejected(lg: Logger, tmp_path: Path) -> None: + """A symlink could publish a file from outside docs/.""" + 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) + + +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.""" + checkout = tmp_path / "co" + private = checkout / "private" + private.mkdir(parents=True) + (private / "INTRO.md").write_text("private", encoding="utf-8") + (checkout / "docs").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() diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py new file mode 100644 index 0000000..0923e2d --- /dev/null +++ b/tests/unit/test_config.py @@ -0,0 +1,110 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Build config validation.""" + +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from docsite.config import load_build_config +from tests.conftest import build_dict, package_dict + + +def test_valid_config_loads() -> None: + """A complete config yields typed sections, with the nav timeout defaulted.""" + cfg = load_build_config(build_dict()) + assert cfg.site.docs_dir == Path("docs") + assert cfg.nav.timeout_s == 10.0 + assert cfg.packages[0].docs == ("INTRO.md", "demo/demo.gif") + + +def test_no_packages_is_valid() -> None: + """A build with no packages only renders the header.""" + assert load_build_config(build_dict(packages=[])).packages == () + + +def test_unrelated_sections_are_ignored() -> None: + """Logging and other app sections do not reach the build models.""" + raw = build_dict() + raw["logging"] = {"level": "info"} + assert load_build_config(raw).packages[0].name == "llm-saia" + + +@pytest.mark.parametrize( + "path", + ["../secrets.md", "/etc/passwd", "a/../b.md", "./INTRO.md", "*.md", "guide[1].md"], +) +def test_docs_path_must_be_exact_and_inside_docs(path: str) -> None: + """Allowlist entries cannot escape docs/ or act as patterns.""" + with pytest.raises(ValidationError, match="docs path"): + load_build_config(build_dict(packages=[package_dict(docs=[path])])) + + +def test_docs_allowlist_rejects_duplicates_and_empty() -> None: + """Each path is listed once, and a package publishes at least one file.""" + with pytest.raises(ValidationError, match="twice"): + load_build_config(build_dict(packages=[package_dict(docs=["a.md", "a.md"])])) + with pytest.raises(ValidationError): + load_build_config(build_dict(packages=[package_dict(docs=[])])) + + +@pytest.mark.parametrize("name", ["../x", "LLM", "-x", "a/b"]) +def test_package_name_is_a_slug(name: str) -> None: + """The name becomes a directory, so it is a lowercase slug.""" + with pytest.raises(ValidationError, match="slug"): + load_build_config(build_dict(packages=[package_dict(name=name)])) + + +@pytest.mark.parametrize("tag", ["--upload-pack=x", "v1 2", "v1;rm"]) +def test_tag_is_a_plain_name(tag: str) -> None: + """The tag reaches git, so options and metacharacters are rejected.""" + with pytest.raises(ValidationError, match="tag"): + load_build_config(build_dict(packages=[package_dict(tag=tag)])) + + +def test_package_names_are_unique() -> None: + """Two packages cannot stage into the same directory.""" + with pytest.raises(ValidationError, match="unique"): + load_build_config(build_dict(packages=[package_dict(), package_dict()])) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("url", "ftp://example.com/nav.html"), + ("site_origin", "https://www.llm-works.ai/"), + ("site_origin", "www.llm-works.ai"), + ("site_origin", "https://www.llm-works.ai?preview=1"), + ("site_origin", "https://www.llm-works.ai/sub"), + ("site_origin", "https://www.llm-works.ai#x"), + ("docs_origin", ""), + ("docs_origin", "https://"), + ("docs_origin", "https://docs.llm-works.ai/"), + ("timeout_s", 0), + ], +) +def test_nav_fields_are_checked(field: str, value: object) -> None: + """Nav URL scheme, origin form and timeout are validated.""" + nav = build_dict()["nav"] | {field: value} + with pytest.raises(ValidationError): + load_build_config(build_dict(nav=nav)) + + +def test_origin_with_port_is_allowed() -> None: + """A local preview server's origin carries a port.""" + nav = build_dict()["nav"] | {"docs_origin": "http://localhost:8000"} + assert load_build_config(build_dict(nav=nav)).nav.docs_origin == "http://localhost:8000" + + +def test_empty_site_origin_is_allowed() -> None: + """An empty origin keeps links root-relative, for a local preview.""" + nav = build_dict()["nav"] | {"site_origin": ""} + assert load_build_config(build_dict(nav=nav)).nav.site_origin == "" + + +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"])])) diff --git a/tests/unit/test_fetch_nav.py b/tests/unit/test_fetch_nav.py new file mode 100644 index 0000000..7f81fb4 --- /dev/null +++ b/tests/unit/test_fetch_nav.py @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Downloading the main site's nav, with urlopen mocked at the call site.""" + +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from appinfra.log import Logger + +from docsite.config import NavConfig +from docsite.fetch import USER_AGENT, FetchError, fetch_nav + +NAV = NavConfig( + url="https://www.llm-works.ai/partials/nav.html", + site_origin="https://www.llm-works.ai", + docs_origin="https://docs.llm-works.ai", + output=Path("overrides/partials/site-nav.html"), +) + + +def _response(status: int, body: bytes) -> MagicMock: + response = MagicMock() + response.status = status + response.read.return_value = body + response.__enter__.return_value = response + return response + + +def test_returns_decoded_markup_and_sends_build_user_agent() -> None: + """The body is decoded as UTF-8; the request names this build, which Cloudflare accepts.""" + with patch("docsite.fetch.urllib.request.urlopen") as urlopen: + urlopen.return_value = _response(200, "".encode()) + assert fetch_nav(MagicMock(spec=Logger), NAV) == "" + request = urlopen.call_args.args[0] + assert request.full_url == NAV.url + assert request.get_header("User-agent") == USER_AGENT + assert urlopen.call_args.kwargs["timeout"] == NAV.timeout_s + + +def test_non_200_status_fails() -> None: + """A redirect page or error body never becomes the header.""" + with patch("docsite.fetch.urllib.request.urlopen") as urlopen: + urlopen.return_value = _response(204, b"") + with pytest.raises(FetchError, match="HTTP 204"): + fetch_nav(MagicMock(spec=Logger), NAV) + + +def test_non_utf8_body_fails() -> None: + """Undecodable markup surfaces as FetchError, which the CLI reports as exit 1.""" + with patch("docsite.fetch.urllib.request.urlopen") as urlopen: + urlopen.return_value = _response(200, b"") + with pytest.raises(FetchError, match="not valid UTF-8"): + fetch_nav(MagicMock(spec=Logger), NAV) + + +def test_network_error_fails() -> None: + """Connection and HTTP errors surface as FetchError naming the URL.""" + with ( + patch("docsite.fetch.urllib.request.urlopen", side_effect=OSError("refused")), + pytest.raises(FetchError, match="refused"), + ): + fetch_nav(MagicMock(spec=Logger), NAV) diff --git a/tests/unit/test_site.py b/tests/unit/test_site.py deleted file mode 100644 index f414b50..0000000 --- a/tests/unit/test_site.py +++ /dev/null @@ -1,11 +0,0 @@ -# SPDX-License-Identifier: MIT -# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors - -"""Site-wide constants.""" - -from docsite.site import SITE_URL - - -def test_site_url_is_the_docs_subdomain() -> None: - """The site URL is the absolute docs origin, with the trailing slash Zensical expects.""" - assert SITE_URL == "https://docs.llm-works.ai/" diff --git a/tests/unit/test_sitenav.py b/tests/unit/test_sitenav.py new file mode 100644 index 0000000..5f5b7a2 --- /dev/null +++ b/tests/unit/test_sitenav.py @@ -0,0 +1,103 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Rendering the main site's nav as the docs header.""" + +import pytest + +from docsite.sitenav import ( + DOCS_ITEM, + GENERATED_MARK, + SEARCH, + THEME_SWITCH, + NavMarkupError, + docs_nav, + render_header, +) + +ORIGIN = "https://www.llm-works.ai" +DOCS = "https://docs.llm-works.ai" + +NAV = """\ + +""" + + +def _with_docs_link(href: str) -> str: + """NAV with a Docs item linking to `href` before Blog.""" + return NAV.replace( + '
  • ', f'
  • Docs
  • \n
  • ' + ) + + +def test_root_relative_links_point_at_the_main_site() -> None: + """Root-relative hrefs gain the origin; absolute ones are left alone.""" + html = docs_nav(NAV, ORIGIN, DOCS) + assert f'href="{ORIGIN}/"' in html + assert f'href="{ORIGIN}/#agents"' in html + assert 'href="https://github.com/llm-works"' in html + assert 'href="/' not in html + + +def test_main_site_current_marker_is_dropped() -> None: + """Only the Docs item is current on the docs site.""" + html = docs_nav(NAV, ORIGIN, DOCS) + assert html.count('aria-current="page"') == 1 + 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) + 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 + + +def test_existing_docs_link_is_marked_instead_of_duplicated() -> None: + """Once the main site links to the docs, that item becomes current.""" + html = docs_nav(_with_docs_link(f"{DOCS}/"), ORIGIN, DOCS) + assert DOCS_ITEM not in html + assert f'Docs' in html + + +def test_docs_link_to_another_origin_is_not_matched() -> None: + """Only a link to the configured docs origin counts as the Docs item.""" + html = docs_nav(_with_docs_link(f"{DOCS}/"), ORIGIN, "https://staging.llm-works.ai") + assert DOCS_ITEM in html + assert f'Docs' in html + + +def test_empty_origin_keeps_links_root_relative() -> None: + """A local preview served next to the main site keeps root-relative links.""" + html = docs_nav(NAV, "", DOCS) + assert 'href="/platform/"' in html + 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_header_wraps_nav_with_mark_and_theme_switch() -> None: + """The partial starts with the generated mark and ends with the theme switch.""" + header = render_header(NAV, ORIGIN, DOCS) + assert header.startswith(GENERATED_MARK) + assert header.endswith(THEME_SWITCH) diff --git a/tests/unit/test_stage_select.py b/tests/unit/test_stage_select.py new file mode 100644 index 0000000..552adae --- /dev/null +++ b/tests/unit/test_stage_select.py @@ -0,0 +1,24 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Comparing a package's docs/ with its allowlist.""" + +from docsite.stage import select + + +def test_select_splits_copy_missing_and_unlisted() -> None: + """Listed files present are copied; listed-absent are missing; extras are unlisted.""" + sel = select( + ["INTRO.md", "known-issues.md", "demo/demo.gif", "demo/demo.tape"], + ["INTRO.md", "demo/demo.gif", "gone.md"], + ) + assert sel.copy == ("INTRO.md", "demo/demo.gif") + assert sel.missing == ("gone.md",) + assert sel.unlisted == ("demo/demo.tape", "known-issues.md") + + +def test_select_keeps_allowlist_order() -> None: + """Copy order follows the allowlist, not the filesystem.""" + sel = select(["b.md", "a.md"], ["b.md", "a.md"]) + assert sel.copy == ("b.md", "a.md") + assert sel.missing == () and sel.unlisted == ()