From 42ebc75c3965e7c0c47699691916d24475b80299 Mon Sep 17 00:00:00 2001 From: serendip-ml <64741025+serendip-ml@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:05:59 -0500 Subject: [PATCH 1/5] feat(build): fetch packages at tags, stage allowlisted docs, render header `python -m docsite build` (or the fetch, stage and nav steps alone) prepares the inputs of the site from etc/docsite.yaml: - fetch: shallow-clones each package at its pinned tag into .build/src and checks the pin is a tag, not a branch; downloads the main site's nav from www.llm-works.ai. Cloudflare answers urllib's default User-Agent with 403, so the request names this build instead. - stage: copies only the files listed in a package's docs allowlist to docs//guides; a listed file that is missing or a symlink fails the build, unlisted files are logged and skipped. - nav: renders the nav as the Zensical header partial: links made absolute, Docs item marked current (added after Platform unless the nav already links to the docs site), search after the logo, theme switch appended. Config is validated by Pydantic models (appinfra[validation]): package names are slugs, tags cannot start with '-', allowlist entries are exact paths inside docs/. The CLI uses appinfra's AppBuilder; the config spec is anchored at the repo root since a root launcher named docsite.py would shadow the package. Signed-off-by: serendip-ml <64741025+serendip-ml@users.noreply.github.com> --- .gitignore | 4 + docsite/__main__.py | 9 ++ docsite/build.py | 58 ++++++++++++ docsite/cli/__init__.py | 8 ++ docsite/cli/cli.py | 26 ++++++ docsite/cli/tools.py | 86 +++++++++++++++++ docsite/config.py | 130 ++++++++++++++++++++++++++ docsite/fetch.py | 68 ++++++++++++++ docsite/sitenav.py | 72 ++++++++++++++ docsite/stage.py | 82 ++++++++++++++++ etc/docsite.yaml | 38 ++++++++ pyproject.toml | 5 +- tests/conftest.py | 38 ++++++++ tests/integration/__init__.py | 2 + tests/integration/conftest.py | 41 ++++++++ tests/integration/test_cli.py | 89 ++++++++++++++++++ tests/integration/test_fetch_git.py | 47 ++++++++++ tests/integration/test_stage_files.py | 72 ++++++++++++++ tests/unit/test_config.py | 98 +++++++++++++++++++ tests/unit/test_fetch_nav.py | 55 +++++++++++ tests/unit/test_sitenav.py | 92 ++++++++++++++++++ tests/unit/test_stage_select.py | 24 +++++ 22 files changed, 1143 insertions(+), 1 deletion(-) create mode 100644 docsite/__main__.py create mode 100644 docsite/build.py create mode 100644 docsite/cli/__init__.py create mode 100644 docsite/cli/cli.py create mode 100644 docsite/cli/tools.py create mode 100644 docsite/config.py create mode 100644 docsite/fetch.py create mode 100644 docsite/sitenav.py create mode 100644 docsite/stage.py create mode 100644 etc/docsite.yaml create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/conftest.py create mode 100644 tests/integration/test_cli.py create mode 100644 tests/integration/test_fetch_git.py create mode 100644 tests/integration/test_stage_files.py create mode 100644 tests/unit/test_config.py create mode 100644 tests/unit/test_fetch_nav.py create mode 100644 tests/unit/test_sitenav.py create mode 100644 tests/unit/test_stage_select.py 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..f0b1b97 --- /dev/null +++ b/docsite/build.py @@ -0,0 +1,58 @@ +# 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") + output = self._cfg.nav.output + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(render_header(nav_html, self._cfg.nav.site_origin), 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..5ec5123 --- /dev/null +++ b/docsite/config.py @@ -0,0 +1,130 @@ +# 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 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 + 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 _origin_form(cls, value: str) -> str: + """An origin without a trailing slash, or empty for root-relative links.""" + if value and (not value.startswith(("https://", "http://")) or value.endswith("/")): + raise ValueError("nav.site_origin must be empty or an http(s) origin without '/'") + return value + + +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..eff8a3f --- /dev/null +++ b/docsite/fetch.py @@ -0,0 +1,68 @@ +# 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 + # --branch also accepts a branch name; only a release tag is a valid pin. + _git("-C", str(dest), "rev-parse", "--quiet", "--verify", f"refs/tags/{pkg.tag}") + self._lg.info("package fetched", extra={"package": pkg.name, "tag": pkg.tag}) + return dest + + +def _git(*args: str) -> None: + """Run git; raise FetchError with its 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) + + +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}") + lg.info("nav fetched", extra={"url": nav.url, "bytes": len(body)}) + return body.decode("utf-8") diff --git a/docsite/sitenav.py b/docsite/sitenav.py new file mode 100644 index 0000000..b83fcb6 --- /dev/null +++ b/docsite/sitenav.py @@ -0,0 +1,72 @@ +# 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 + +from .site import SITE_URL + +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) -> str: + """Return the docs header partial for the given main-site nav markup.""" + return GENERATED_MARK + docs_nav(nav_html, site_origin) + THEME_SWITCH + + +def docs_nav(nav_html: str, site_origin: str) -> str: + """Rewrite the main site's nav for the docs site.""" + html = nav_html.replace(_CURRENT, "") + html = _ROOT_HREF.sub(f'href="{site_origin}/', html) + html = _mark_docs_item(html, site_origin) + return _insert_after(html, r'.*class="logo".*\n', SEARCH, "logo") + + +def _mark_docs_item(html: str, site_origin: str) -> str: + """Mark the nav's own docs link current, or add a Docs item after Platform.""" + docs_origin = SITE_URL.rstrip("/") + 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..3e2dfd9 --- /dev/null +++ b/docsite/stage.py @@ -0,0 +1,82 @@ +# 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" + 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..dda2e5d --- /dev/null +++ b/etc/docsite.yaml @@ -0,0 +1,38 @@ +# 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 + 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..400a7a1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,5 +3,43 @@ """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", + "output": "overrides/partials/site-nav.html", + }, + "packages": [package_dict()], + } + cfg.update(overrides) + return cfg diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..7bd7114 --- /dev/null +++ b/tests/integration/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 0000000..9376e70 --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,41 @@ +# 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: + 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..de8df76 --- /dev/null +++ b/tests/integration/test_cli.py @@ -0,0 +1,89 @@ +# 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 + 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..0a5761a --- /dev/null +++ b/tests/integration/test_fetch_git.py @@ -0,0 +1,47 @@ +# 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.""" + +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 + + +def _package(repo: Path, tag: str = TAG) -> Package: + return Package(name="pkg", repo=str(repo), 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.""" + dest = PackageFetcher(lg, tmp_path / "build").fetch(_package(package_repo)) + assert dest == tmp_path / "build" / "pkg" + assert (dest / "docs" / "INTRO.md").is_file() + + +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_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): + PackageFetcher(lg, tmp_path / "build").fetch(_package(package_repo, "rel")) diff --git a/tests/integration/test_stage_files.py b/tests/integration/test_stage_files.py new file mode 100644 index 0000000..c731af8 --- /dev/null +++ b/tests/integration/test_stage_files.py @@ -0,0 +1,72 @@ +# 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_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..b7810a3 --- /dev/null +++ b/tests/unit/test_config.py @@ -0,0 +1,98 @@ +# 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"), + ("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_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..db13985 --- /dev/null +++ b/tests/unit/test_fetch_nav.py @@ -0,0 +1,55 @@ +# 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", + 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_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_sitenav.py b/tests/unit/test_sitenav.py new file mode 100644 index 0000000..62a9c66 --- /dev/null +++ b/tests/unit/test_sitenav.py @@ -0,0 +1,92 @@ +# 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" + +NAV = """\ + +""" + + +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) + 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) + 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).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.""" + nav = NAV.replace( + '
  • ', + '
  • Docs
  • \n
  • ', + ) + html = docs_nav(nav, ORIGIN) + assert DOCS_ITEM not in html + assert '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, "") + 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) + + +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) + 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 == () From a41503218b4849356aac7bf7a7470c72001c7c80 Mon Sep 17 00:00:00 2001 From: serendip-ml <64741025+serendip-ml@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:52:26 -0500 Subject: [PATCH 2/5] fix(build): pin checkouts to the tagged commit, docs origin from config - fetch: `git clone --branch` prefers a branch that shares the tag's name, so checking that refs/tags/ exists passed while HEAD sat on the branch. The checkout is now compared with refs/tags/^{commit}, which also peels annotated tags. - fetch: a nav body that is not UTF-8 raises FetchError, so the CLI logs it and exits 1 instead of printing a traceback. - nav: the docs origin used to recognise an existing Docs link in the main site's nav is nav.docs_origin in etc/docsite.yaml; the hardcoded docsite/site.py constant is removed. Signed-off-by: serendip-ml <64741025+serendip-ml@users.noreply.github.com> --- docsite/build.py | 6 +++-- docsite/config.py | 20 ++++++++++++++--- docsite/fetch.py | 19 +++++++++++----- docsite/site.py | 6 ----- docsite/sitenav.py | 17 ++++++-------- etc/docsite.yaml | 2 ++ tests/conftest.py | 1 + tests/integration/conftest.py | 13 ++++++----- tests/integration/test_cli.py | 1 + tests/integration/test_fetch_git.py | 20 ++++++++++++++++- tests/unit/test_config.py | 2 ++ tests/unit/test_fetch_nav.py | 9 ++++++++ tests/unit/test_site.py | 11 --------- tests/unit/test_sitenav.py | 35 +++++++++++++++++++---------- 14 files changed, 106 insertions(+), 56 deletions(-) delete mode 100644 docsite/site.py delete mode 100644 tests/unit/test_site.py diff --git a/docsite/build.py b/docsite/build.py index f0b1b97..de80a47 100644 --- a/docsite/build.py +++ b/docsite/build.py @@ -40,9 +40,11 @@ def stage(self) -> None: def nav(self) -> Path: """Render the fetched nav as the docs header partial.""" nav_html = self._nav_source.read_text(encoding="utf-8") - output = self._cfg.nav.output + nav = self._cfg.nav + output = nav.output output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(render_header(nav_html, self._cfg.nav.site_origin), encoding="utf-8") + 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 diff --git a/docsite/config.py b/docsite/config.py index 5ec5123..d203098 100644 --- a/docsite/config.py +++ b/docsite/config.py @@ -35,6 +35,7 @@ class NavConfig(_Frozen): url: str site_origin: str + docs_origin: str output: Path timeout_s: float = Field(default=10.0, gt=0) @@ -48,12 +49,25 @@ def _url_scheme(cls, value: str) -> str: @field_validator("site_origin") @classmethod - def _origin_form(cls, value: str) -> str: + def _site_origin_form(cls, value: str) -> str: """An origin without a trailing slash, or empty for root-relative links.""" - if value and (not value.startswith(("https://", "http://")) or value.endswith("/")): - raise ValueError("nav.site_origin must be empty or an http(s) origin without '/'") + 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 an http(s) origin without a trailing slash.""" + if not value.startswith(("https://", "http://")) or value.endswith("/"): + raise ValueError(f"{field} must be an http(s) origin without a trailing '/'") + class Package(_Frozen): """One package: its repo, the release tag to build from, and its docs allowlist.""" diff --git a/docsite/fetch.py b/docsite/fetch.py index eff8a3f..0708b05 100644 --- a/docsite/fetch.py +++ b/docsite/fetch.py @@ -38,18 +38,23 @@ def fetch(self, pkg: Package) -> Path: "-c", "advice.detachedHead=false", "clone", "--quiet", "--depth", "1", "--branch", pkg.tag, "--", pkg.repo, str(dest), ) # fmt: skip - # --branch also accepts a branch name; only a release tag is a valid pin. - _git("-C", str(dest), "rev-parse", "--quiet", "--verify", f"refs/tags/{pkg.tag}") + # --branch also accepts a branch, and prefers one that shares the tag's name; only the + # tagged commit is a valid pin. ^{commit} peels an annotated tag to its commit. + head = _git("-C", str(dest), "rev-parse", "HEAD") + tagged = _git("-C", str(dest), "rev-parse", "--verify", f"refs/tags/{pkg.tag}^{{commit}}") + if head != tagged: + raise FetchError(f"{pkg.name}: checkout is not at tag {pkg.tag}") self._lg.info("package fetched", extra={"package": pkg.name, "tag": pkg.tag}) return dest -def _git(*args: str) -> None: - """Run git; raise FetchError with its stderr when it fails.""" +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: @@ -64,5 +69,9 @@ def fetch_nav(lg: Logger, nav: NavConfig) -> str: 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 body.decode("utf-8") + return html diff --git a/docsite/site.py b/docsite/site.py deleted file mode 100644 index 39d8a50..0000000 --- a/docsite/site.py +++ /dev/null @@ -1,6 +0,0 @@ -# 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/docsite/sitenav.py b/docsite/sitenav.py index b83fcb6..1089ed3 100644 --- a/docsite/sitenav.py +++ b/docsite/sitenav.py @@ -17,8 +17,6 @@ import re -from .site import SITE_URL - GENERATED_MARK = "{#- generated by docsite from the main site's partials/nav.html -#}\n" DOCS_ITEM = '
  • Docs
  • \n' @@ -40,22 +38,21 @@ class NavMarkupError(ValueError): """The nav partial lacks an anchor the docs header depends on.""" -def render_header(nav_html: str, site_origin: str) -> str: +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) + THEME_SWITCH + return GENERATED_MARK + docs_nav(nav_html, site_origin, docs_origin) + THEME_SWITCH -def docs_nav(nav_html: str, site_origin: str) -> str: - """Rewrite the main site's nav for the docs site.""" +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) + 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) -> str: - """Mark the nav's own docs link current, or add a Docs item after Platform.""" - docs_origin = SITE_URL.rstrip("/") +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() diff --git a/etc/docsite.yaml b/etc/docsite.yaml index dda2e5d..8c6acaf 100644 --- a/etc/docsite.yaml +++ b/etc/docsite.yaml @@ -22,6 +22,8 @@ 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 diff --git a/tests/conftest.py b/tests/conftest.py index 400a7a1..90ae4f7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -37,6 +37,7 @@ def build_dict(**overrides: Any) -> dict[str, Any]: "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()], diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 9376e70..8a4cb3b 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -16,7 +16,8 @@ } -def _git(cwd: Path, *args: str) -> None: +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, @@ -33,9 +34,9 @@ def package_repo(tmp_path: Path) -> Path: 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") + 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 index de8df76..96676dc 100644 --- a/tests/integration/test_cli.py +++ b/tests/integration/test_cli.py @@ -37,6 +37,7 @@ def _config(tmp_path: Path, repo: Path, docs: list[str]) -> Path: 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 diff --git a/tests/integration/test_fetch_git.py b/tests/integration/test_fetch_git.py index 0a5761a..8f7d986 100644 --- a/tests/integration/test_fetch_git.py +++ b/tests/integration/test_fetch_git.py @@ -10,7 +10,7 @@ from docsite.config import Package from docsite.fetch import FetchError, PackageFetcher -from tests.integration.conftest import TAG +from tests.integration.conftest import TAG, git def _package(repo: Path, tag: str = TAG) -> Package: @@ -39,6 +39,24 @@ def test_unknown_tag_fails(lg: Logger, package_repo: Path, tmp_path: Path) -> No 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)) + + +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: diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index b7810a3..b52f97c 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -76,6 +76,8 @@ def test_package_names_are_unique() -> None: ("url", "ftp://example.com/nav.html"), ("site_origin", "https://www.llm-works.ai/"), ("site_origin", "www.llm-works.ai"), + ("docs_origin", ""), + ("docs_origin", "https://docs.llm-works.ai/"), ("timeout_s", 0), ], ) diff --git a/tests/unit/test_fetch_nav.py b/tests/unit/test_fetch_nav.py index db13985..7f81fb4 100644 --- a/tests/unit/test_fetch_nav.py +++ b/tests/unit/test_fetch_nav.py @@ -15,6 +15,7 @@ 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"), ) @@ -46,6 +47,14 @@ def test_non_200_status_fails() -> None: 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 ( 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 index 62a9c66..5f5b7a2 100644 --- a/tests/unit/test_sitenav.py +++ b/tests/unit/test_sitenav.py @@ -16,6 +16,7 @@ ) ORIGIN = "https://www.llm-works.ai" +DOCS = "https://docs.llm-works.ai" NAV = """\