Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 9 additions & 0 deletions docsite/__main__.py
Original file line number Diff line number Diff line change
@@ -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())
60 changes: 60 additions & 0 deletions docsite/build.py
Original file line number Diff line number Diff line change
@@ -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
8 changes: 8 additions & 0 deletions docsite/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors

"""Command-line interface: `python -m docsite <step>`."""

from .cli import main

__all__ = ["main"]
26 changes: 26 additions & 0 deletions docsite/cli/cli.py
Original file line number Diff line number Diff line change
@@ -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
86 changes: 86 additions & 0 deletions docsite/cli/tools.py
Original file line number Diff line number Diff line change
@@ -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()
151 changes: 151 additions & 0 deletions docsite/config.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading