diff --git a/Makefile b/Makefile index 8b8e4a3..ef31d75 100644 --- a/Makefile +++ b/Makefile @@ -26,7 +26,7 @@ APPINFRA_DEV_CQ_DEAD ?= strict APPINFRA_DEV_TEST_HEALTH ?= warn # Test coverage threshold (percentage), measured over unit and integration tests -APPINFRA_PYTEST_COVERAGE_THRESHOLD ?= 95 +APPINFRA_PYTEST_COVERAGE_THRESHOLD ?= 90 APPINFRA_PYTEST_COVERAGE_MARKERS ?= unit or integration # Docstring coverage threshold (percentage) diff --git a/SECURITY.md b/SECURITY.md index 1eded48..69990df 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -23,3 +23,8 @@ one. This repository builds a static site. In scope: the build tooling, the GitHub Actions workflows, and the site shell (header, scripts, styles). Issues in a package's own code or docs belong to that package's repository and its security policy. + +The build trusts its inputs: `etc/docsite.yaml`, the `INFRA_*` environment variables that +override it, and the llm-works package repositories at the refs it names. It does not defend +against a malicious config or package repository (for example a symlink or path in a package's +docs pointing outside them); reports that need control of those inputs are out of scope. diff --git a/docsite/build.py b/docsite/build.py index 41805e5..51baf56 100644 --- a/docsite/build.py +++ b/docsite/build.py @@ -12,6 +12,7 @@ from .config import BuildConfig, NavItem, Package from .fetch import PackageFetcher, fetch_nav, fetch_text +from .links import link_to_repo from .navtree import SectionIndex, index_sections, package_nav, page_title, render_section_index from .reference import reference_modules, reference_nav, reference_pages from .siteconf import render_site_config @@ -32,7 +33,7 @@ def __init__(self, lg: Logger, cfg: BuildConfig) -> None: self._cfg = cfg def fetch(self) -> None: - """Clone every package at its tag; download the nav partial and brand stylesheets.""" + """Clone every package at its ref; download the nav partial and brand stylesheets.""" fetcher = PackageFetcher(self._lg, self._cfg.site.build_dir) for pkg in self._cfg.packages: fetcher.fetch(pkg) @@ -68,7 +69,7 @@ def stage(self) -> None: def _stage_package(self, pkg: Package, stager: DocsStager, plan: dict[str, Source]) -> None: """Add a package's docs, its reference and its generated section pages to `plan`.""" checkout = self._cfg.site.build_dir / pkg.name - files = stager.files(pkg, checkout) + files = link_to_repo(self._lg, pkg, checkout, stager.files(pkg, checkout)) merge(plan, {f"{pkg.name}/{path}": src for path, src in files.items()}, pkg.name) modules = self._reference_modules(pkg) if modules is not None: @@ -83,7 +84,7 @@ def nav(self) -> Path: 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) + header = render_header(nav_html, nav.site_origin) output.write_text(header, encoding="utf-8") self._lg.info("header rendered", extra={"output": str(output)}) return output diff --git a/docsite/cli/cli.py b/docsite/cli/cli.py index 2f7a665..5a32a7f 100644 --- a/docsite/cli/cli.py +++ b/docsite/cli/cli.py @@ -5,7 +5,7 @@ from appinfra.app import AppBuilder -from .tools import BuildTool, FetchTool, NavTool, SiteConfigTool, StageTool +from .tools import BuildTool def main() -> int: @@ -18,7 +18,7 @@ def main() -> int: .done() .cli.with_all_flags() .done() - .tools.with_tools(FetchTool(), StageTool(), NavTool(), SiteConfigTool(), BuildTool()) + .tools.with_tools(BuildTool()) .done() .build() ) diff --git a/docsite/cli/tools.py b/docsite/cli/tools.py index d3e791f..5f3c151 100644 --- a/docsite/cli/tools.py +++ b/docsite/cli/tools.py @@ -1,111 +1,43 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors -"""One CLI tool per build step.""" +"""The CLI's one tool: the build.""" -import tomllib -from typing import Any, ClassVar +from typing import Any 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 ..navtree import NavTreeError from ..reference import ReferenceSourceError from ..siteconf import SiteConfigError -from ..sitenav import NavMarkupError from ..stage import StageError -_STEP_ERRORS = ( - ValidationError, +# ValueError covers an invalid config, the nav markup, the docs tree and the base TOML +_BUILD_ERRORS = ( + ValueError, FetchError, StageError, - NavMarkupError, - NavTreeError, SiteConfigError, ReferenceSourceError, - tomllib.TOMLDecodeError, OSError, ) -class _StepTool(Tool): - """Loads the build config and runs one step; a failed step exits 1.""" - - name: ClassVar[str] - help_text: ClassVar[str] +class BuildTool(Tool): + """Fetch, stage, and render the header and the Zensical config; a failure exits 1.""" 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)) + """Register as `build`.""" + help_text = "Fetch, stage, and render the header and the Zensical config" + super().__init__(parent, ToolConfig(name="build", help_text=help_text)) def run(self, **kwargs: Any) -> int: - """Run the step; log and return 1 on a config, fetch, stage or nav error.""" + """Run every build step; log and return 1 on a known 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}) + Build(self.lg, load_build_config(self.app.config)).all() + except _BUILD_ERRORS as e: + self.lg.error("build failed", extra={"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): - """Assemble the docs directory from the site's pages and the packages' docs.""" - - name = "stage" - help_text = "Rebuild the docs directory from the site pages and each package's docs" - - 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 SiteConfigTool(_StepTool): - """Render the Zensical config with each package's docs tree in the nav.""" - - name = "config" - help_text = "Render the Zensical config from the base config and the packages" - - def _step(self, build: Build) -> None: - """Run Build.site_config.""" - build.site_config() - - -class BuildTool(_StepTool): - """Run every step.""" - - name = "build" - help_text = "Fetch, stage, and render the header and the Zensical config" - - def _step(self, build: Build) -> None: - """Run Build.all.""" - build.all() diff --git a/docsite/config.py b/docsite/config.py index f7d4758..585e3ae 100644 --- a/docsite/config.py +++ b/docsite/config.py @@ -3,19 +3,11 @@ """Typed build configuration, validated from the `site`, `nav`, `brand` and `packages` sections.""" -import re from collections.abc import Iterator, Mapping, Sequence -from pathlib import Path, PurePosixPath +from pathlib import Path 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("*?[]") +from pydantic import BaseModel, ConfigDict, Field, model_validator class _Frozen(BaseModel): @@ -48,35 +40,16 @@ def _docs_dir_is_disposable(self) -> "SiteConfig": class NavConfig(_Frozen): - """The main site's nav partial and where the rendered header goes.""" + """The main site's nav partial and where the rendered header goes. + + `site_origin` is scheme://host[:port] with no trailing slash; empty keeps the nav's links + root-relative, for a local preview. + """ 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.""" - _check_url("nav.url", value) - 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 + timeout_s: float = 10.0 class BrandConfig(_Frozen): @@ -88,39 +61,12 @@ class BrandConfig(_Frozen): tokens_url: str nav_css_url: str - timeout_s: float = Field(default=10.0, gt=0) - - @field_validator("tokens_url", "nav_css_url") - @classmethod - def _url_scheme(cls, value: str) -> str: - """Accept http(s), and file:// for local previews and tests.""" - _check_url("brand stylesheet URL", value) - return value - - -def _check_url(field: str, value: str) -> None: - """Accept http(s), and file:// for local previews and tests.""" - if not value.startswith(("https://", "http://", "file://")): - raise ValueError(f"{field} must be an http(s) or file URL") - - -def _check_origin(field: str, value: str) -> None: - """Reject anything but scheme://host[:port], with no path, query or fragment.""" - parts = urlsplit(value) - # 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") + timeout_s: float = 10.0 # A site nav entry: a path, {title: path}, or {title: [entries]} for a section. NavItem = str | dict[str, Any] -_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") - class Reference(_Frozen): """A generated API reference: one page per top-level module of `package`, with submodules.""" @@ -130,24 +76,12 @@ class Reference(_Frozen): # The checkout directory that holds the package directory source: str = "." - @field_validator("package") - @classmethod - def _package_name(cls, value: str) -> str: - """An importable top-level name.""" - if not _IDENTIFIER.fullmatch(value): - raise ValueError(f"reference package {value!r} is not an import name") - return value - - @field_validator("source") - @classmethod - def _source_path(cls, value: str) -> str: - """A plain path inside the checkout.""" - _check_doc_path(value, "reference source") - return value - class Package(_Frozen): - """One package: its repo, the release tag to build from, and its docs tree. + """One package: its repo, the git ref to build from, and its docs tree. + + `ref` is a tag, a branch, or @ for a commit on that branch (the commit may + be abbreviated). The published site builds from release tags; a branch is for previews. `docs` is both the allowlist and the package's place in the site nav: the package's docs are the source and are published as they are, while the arrangement (order, sections, titles) is @@ -155,8 +89,8 @@ class Package(_Frozen): """ name: str - repo: str = Field(min_length=1) - tag: str + repo: str + ref: str docs_root: str = "docs" docs: tuple[NavItem, ...] = Field(min_length=1) # Staged under another name, e.g. README.md, which the generator would take as the index @@ -173,53 +107,6 @@ def site_path(self, path: str) -> str: """Where a docs path lands in the site, relative to the package's directory.""" return self.rename.get(path, path) - @field_validator("name") - @classmethod - 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_root") - @classmethod - def _docs_root_path(cls, value: str) -> str: - """The docs directory is a plain path inside the checkout.""" - _check_doc_path(value, "docs_root") - return value - - @field_validator("docs") - @classmethod - def _docs_paths(cls, value: tuple[NavItem, ...]) -> tuple[NavItem, ...]: - """Each path is exact, inside the docs root, and listed once.""" - files = list(_nav_files(value)) - for path in files: - _check_doc_path(path, "docs path") - if len(set(files)) != len(files): - raise ValueError("docs allowlist lists a path twice") - return value - - @model_validator(mode="after") - def _renames_fit(self) -> "Package": - """Each rename maps a listed file to a free, plain path.""" - files = set(self.files) - for src, dst in self.rename.items(): - _check_doc_path(dst, "rename target") - if src not in files: - raise ValueError(f"rename source {src!r} is not in docs") - targets = [self.site_path(path) for path in files] - if len(set(targets)) != len(targets): - raise ValueError("rename target collides with another docs path") - return self - def _nav_files(items: Sequence[NavItem]) -> Iterator[str]: """Yield the paths of a docs tree in order; reject entries of any other shape.""" @@ -238,15 +125,6 @@ def _nav_files(items: Sequence[NavItem]) -> Iterator[str]: raise ValueError(f"docs entry {item!r} needs a path or a non-empty list") -def _check_doc_path(path: str, what: str) -> None: - """Reject paths that could escape their root or match more than one file.""" - pure = PurePosixPath(path) - if pure.is_absolute() or ".." in pure.parts or path != pure.as_posix(): - raise ValueError(f"{what} {path!r} must be a normalized relative path") - if _GLOB_CHARS & set(path): - raise ValueError(f"{what} {path!r} must be an exact path, not a pattern") - - class BuildConfig(_Frozen): """The whole build: site paths, nav source, brand stylesheets and the packages to publish.""" @@ -255,18 +133,16 @@ class BuildConfig(_Frozen): brand: BrandConfig 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", "brand", "packages")} + """Validate the build sections of the app config; other sections are ignored. + + `packages` maps each package name to its settings, so an environment variable can override + one of them, e.g. INFRA_PACKAGES_APPINFRA_REF=develop. + """ + sections = {key: _plain(raw.get(key)) for key in ("site", "nav", "brand")} + packages = _plain(raw.get("packages")) or {} + sections["packages"] = [{"name": name, **pkg} for name, pkg in packages.items()] return BuildConfig.model_validate(sections) diff --git a/docsite/fetch.py b/docsite/fetch.py index 50a56aa..b73f55f 100644 --- a/docsite/fetch.py +++ b/docsite/fetch.py @@ -1,8 +1,8 @@ # 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 and -brand stylesheets.""" +"""Fetch the inputs of a build: each package at its git ref, and the main site's nav and brand +stylesheets.""" import http.client import shutil @@ -24,49 +24,41 @@ class FetchError(RuntimeError): class PackageFetcher: - """Shallow-clones packages at their pinned tags into the build directory.""" + """Clones packages at their refs 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.""" + """Clone `pkg` at its ref into /, replacing an older checkout. + + A tag or a branch is a shallow clone of its tip. @ clones the branch's + history, which an abbreviated commit needs to resolve, and checks the commit out; a + commit that is not on the branch is not in the clone, and fails. + """ dest = self._build_dir / pkg.name if dest.exists(): shutil.rmtree(dest) self._build_dir.mkdir(parents=True, exist_ok=True) + branch, _, commit = pkg.ref.partition("@") + depth = [] if commit else ["--depth", "1"] _git( - "-c", "advice.detachedHead=false", "clone", "--quiet", "--depth", "1", - "--branch", pkg.tag, "--", pkg.repo, str(dest), + "-c", "advice.detachedHead=false", "clone", "--quiet", "--single-branch", *depth, + "--branch", branch, "--", 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}) + if commit: + _git( + "-C", str(dest), "-c", "advice.detachedHead=false", + "checkout", "--quiet", commit, "--", + ) # fmt: skip + head = _git("-C", str(dest), "rev-parse", "--short", "HEAD") + self._lg.info( + "package fetched", extra={"package": pkg.name, "ref": pkg.ref, "commit": head} + ) 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) diff --git a/docsite/links.py b/docsite/links.py new file mode 100644 index 0000000..328d2ab --- /dev/null +++ b/docsite/links.py @@ -0,0 +1,144 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Links in package docs that leave the docs tree, made into links to the repo at the ref. + +A package's docs link to files beside them in the repo (the README, the changelog, examples) +with relative paths that work on GitHub. Only the docs tree is published, so on the site those +links point nowhere. A link whose target lies outside the docs root but inside the repo, and +exists at the ref, is rewritten to that file on GitHub at the ref. Links into the docs tree, to +files that do not exist, or out of the repo are left as written, so the build still warns about +them. +""" + +import os +import posixpath +import re +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import quote, unquote + +from appinfra.log import Logger + +from .config import Package +from .markdown import prose_flags +from .stage import Source + +_GITHUB = re.compile(r"(https://github\.com/[\w.-]+/[\w.-]+?)(?:\.git)?/?") +# An inline link or image target: "](target" with an optional <...> around it +_INLINE = re.compile(r"(\]\(\s*)(<[^>\n]*>|[^)\s]+)") +# A reference definition: "[label]: target" +_REFDEF = re.compile(r"^(\s{0,3}\[[^\]]+\]:[ \t]*)(<[^>\n]*>|\S+)") +# An inline code span: a run of backticks to the next run of the same length +_CODE_SPAN = re.compile(r"(`+).+?(? str | None: + """The web address of the repo's files at `ref`, for a GitHub https repo; else None.""" + match = _GITHUB.fullmatch(repo) + return f"{match.group(1)}/blob/{ref}" if match else None + + +def repo_paths(checkout: Path) -> frozenset[str]: + """Every file and directory in the checkout, relative to it, leaving out .git.""" + paths = set() + for dirpath, dirnames, filenames in os.walk(checkout): + dirnames[:] = [d for d in dirnames if d != ".git"] + rel = Path(dirpath).relative_to(checkout) + for name in dirnames + filenames: + paths.add((rel / name).as_posix()) + return frozenset(paths) + + +@dataclass(frozen=True) +class RepoLinks: + """Where a package's docs sit in its repo, the repo's paths at the ref, and their address.""" + + docs_root: str + paths: frozenset[str] + base: str + + def rewrite(self, text: str, doc: str) -> tuple[str, int]: + """`text` of the doc at repo path `doc`, with its links out of the docs tree pointing at + the repo, and how many were rewritten.""" + doc_dir = posixpath.dirname(doc) + count = 0 + + def target(match: re.Match[str]) -> str: + nonlocal count + url = self._url(match.group(2), doc_dir) + if url is None: + return match.group(0) + count += 1 + return match.group(1) + url + + lines = text.splitlines(keepends=True) + out = [ + _outside_code(line, target) if prose else line + for line, prose in zip(lines, prose_flags(lines), strict=True) + ] + return "".join(out), count + + def _url(self, target: str, doc_dir: str) -> str | None: + """The repo address for a link target that leaves the docs tree; None to keep it.""" + raw = target[1:-1] if target.startswith("<") else target + if not raw or raw.startswith(("#", "/")) or _SCHEME.match(raw): + return None + cut = min((i for i in (raw.find("#"), raw.find("?")) if i >= 0), default=len(raw)) + path = posixpath.normpath(posixpath.join(doc_dir, unquote(raw[:cut]))) + inside = path == self.docs_root or path.startswith(self.docs_root + "/") + if inside or path.startswith("../") or path == ".." or path not in self.paths: + return None + return f"{self.base}/{quote(path)}{raw[cut:]}" + + +def link_to_repo( + lg: Logger, pkg: Package, checkout: Path, files: Mapping[str, Path] +) -> dict[str, Source]: + """`files` (site path -> file in the checkout), with each Markdown page whose links leave + the docs tree replaced by its rewritten text.""" + # GitHub addresses a file by tag, branch or commit; of @, the commit, and + # the branch when the commit is empty, as fetch does + branch, _, commit = pkg.ref.partition("@") + base = blob_base(pkg.repo, commit or branch) + if base is None: + return dict(files) + links = RepoLinks(pkg.docs_root, repo_paths(checkout), base) + linked: dict[str, Source] = {} + total = 0 + for site_path, src in files.items(): + linked[site_path] = src + if src.suffix == ".md": + text, count = links.rewrite(src.read_text(encoding="utf-8"), _repo_path(src, checkout)) + if count: + linked[site_path] = text + total += count + if total: + lg.info("links out of the docs rewritten", extra={"package": pkg.name, "links": total}) + return linked + + +def _repo_path(src: Path, checkout: Path) -> str: + """The file's path in the repo.""" + return src.relative_to(checkout).as_posix() + + +def _outside_code(line: str, replace: Callable[[re.Match[str]], str]) -> str: + """`line` with its link targets replaced, outside inline code spans.""" + parts = [] + pos = 0 + for span in _CODE_SPAN.finditer(line): + parts.append(_links(line[pos : span.start()], replace, line_start=pos == 0)) + parts.append(span.group(0)) + pos = span.end() + parts.append(_links(line[pos:], replace, line_start=pos == 0)) + return "".join(parts) + + +def _links(text: str, replace: Callable[[re.Match[str]], str], line_start: bool) -> str: + """`text` with its inline link targets replaced, and a reference definition when the text + starts the line (the only place one can be).""" + text = _INLINE.sub(replace, text) + return _REFDEF.sub(replace, text) if line_start else text diff --git a/docsite/markdown.py b/docsite/markdown.py new file mode 100644 index 0000000..c8dfb71 --- /dev/null +++ b/docsite/markdown.py @@ -0,0 +1,39 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Markdown source: which lines are prose and which are fenced code.""" + +import re +from collections.abc import Sequence + +# A code fence line: its marker, then an info string (opening fences only) +_FENCE = re.compile(r"\s*(`{3,}|~{3,})(.*)$") + + +def prose_flags(lines: Sequence[str]) -> list[bool]: + """For each line, whether it is prose: outside fenced code and not a fence line itself. + + A fence closes only on a bare marker of its own character, at least as long as the one that + opened it (CommonMark): a ``` line inside a ~~~ block, or inside a ```` block, is code. + """ + flags = [] + fence: str | None = None # the marker of the block the line is in + for line in lines: + marker = _FENCE.match(line) + if marker and fence is None: + fence = marker.group(1) + flags.append(False) + elif marker and _closes(marker, fence): + fence = None + flags.append(False) + else: + flags.append(fence is None) + return flags + + +def _closes(marker: re.Match[str], fence: str | None) -> bool: + """Whether a fence line closes the block that `fence` opened.""" + close, rest = marker.group(1), marker.group(2) + return ( + fence is not None and close[0] == fence[0] and len(close) >= len(fence) and not rest.strip() + ) diff --git a/docsite/navtree.py b/docsite/navtree.py index 86c92a6..9ac92e8 100644 --- a/docsite/navtree.py +++ b/docsite/navtree.py @@ -10,14 +10,13 @@ from dataclasses import dataclass from .config import NavItem, Package +from .markdown import prose_flags # Zensical takes a section's first entry as the section's own page when it is one of these INDEX_NAMES = ("index.md", "README.md") _HEADING = re.compile(r"#\s+(.+?)(?:\s+#+)?\s*$") _FRONT_TITLE = re.compile(r"title:\s*(.+)$") -# A code fence line: its marker, then an info string (opening fences only) -_FENCE = re.compile(r"\s*(`{3,}|~{3,})(.*)$") class NavTreeError(ValueError): @@ -106,34 +105,14 @@ def page_title(text: str, path: str) -> str: def _heading(lines: Sequence[str]) -> str | None: - """The first level-1 heading outside fenced code. - - A fence closes only on a bare marker of its own character, at least as long as the one that - opened it (CommonMark): a ``` line inside a ~~~ block, or inside a ```` block, is code. - """ - fence: str | None = None # the marker of the block the line is in - for line in lines: - marker = _FENCE.match(line) - if marker and fence is None: - fence = marker.group(1) - continue - if marker and _closes(marker, fence): - fence = None - continue - match = None if fence else _HEADING.match(line) + """The first level-1 heading outside fenced code.""" + for line, prose in zip(lines, prose_flags(lines), strict=True): + match = _HEADING.match(line) if prose else None if match: return match.group(1) return None -def _closes(marker: re.Match[str], fence: str | None) -> bool: - """Whether a fence line closes the block that `fence` opened.""" - close, rest = marker.group(1), marker.group(2) - return ( - fence is not None and close[0] == fence[0] and len(close) >= len(fence) and not rest.strip() - ) - - def _file_title(path: str) -> str: """A title from the file name: "getting-started.md" -> "Getting started".""" stem = posixpath.splitext(posixpath.basename(path))[0] diff --git a/docsite/reference.py b/docsite/reference.py index d1cd740..f73f2eb 100644 --- a/docsite/reference.py +++ b/docsite/reference.py @@ -56,7 +56,7 @@ def _index_page(pkg: Package, modules: list[str]) -> str: links = "\n".join(f"- [`{m}`]({m.split('.', 1)[1]}.md)" for m in modules) return ( f"# {NAV_TITLE}\n\n" - f"Generated from the docstrings and type hints of {pkg.name} {pkg.tag}. Each page covers " + f"Generated from the docstrings and type hints of {pkg.name} {pkg.ref}. Each page covers " "one top-level module and its submodules.\n\n" f"{links}\n" ) diff --git a/docsite/sitenav.py b/docsite/sitenav.py index 8e2206d..3117753 100644 --- a/docsite/sitenav.py +++ b/docsite/sitenav.py @@ -3,13 +3,11 @@ """Render the main site's nav partial as the docs header. -The markup stays the main site's own, with three changes: +The markup, theme switch included, stays the main site's own, with two 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 main site's theme switch follows the nav, unless the partial carries it already. +- a "Docs" item, marked current, follows Platform. The docs search is not part of the header: it sits above the tree (overrides/main.html). The output is a Jinja partial for the Zensical theme override. @@ -21,14 +19,6 @@ DOCS_ITEM = '
  • Docs
  • \n' -# Same markup as the switch on the main site's pages. -THEME_SWITCH = """\ - -""" - _CURRENT = ' aria-current="page"' _ROOT_HREF = re.compile(r'href="/(?!/)') @@ -37,35 +27,11 @@ 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. - - The theme switch is appended only when the partial does not carry one itself. - """ - switch = "" if 'id="theme-switch"' in nav_html else THEME_SWITCH - return GENERATED_MARK + docs_nav(nav_html, site_origin, docs_origin) + switch - - -def docs_nav(nav_html: str, site_origin: str, docs_origin: str) -> str: - """Rewrite the main site's nav for the docs site at `docs_origin`.""" +def render_header(nav_html: str, site_origin: str) -> str: + """Return the docs header partial for the given main-site nav markup.""" html = nav_html.replace(_CURRENT, "") html = _ROOT_HREF.sub(f'href="{site_origin}/', html) - return _mark_docs_item(html, site_origin, docs_origin) - - -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() :] + platform = re.search(rf'.*href="{re.escape(site_origin)}/platform/".*\n', html) + if not platform: + raise NavMarkupError("no Platform item in the main site's nav") + return GENERATED_MARK + html[: platform.end()] + DOCS_ITEM + html[platform.end() :] diff --git a/docsite/stage.py b/docsite/stage.py index 157d949..b931c8c 100644 --- a/docsite/stage.py +++ b/docsite/stage.py @@ -5,7 +5,7 @@ from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass -from pathlib import Path, PurePosixPath +from pathlib import Path from appinfra.log import Logger @@ -46,24 +46,17 @@ def __init__(self, lg: Logger) -> None: self._lg = lg def files(self, pkg: Package, checkout: Path) -> dict[str, Path]: - """Site path (renames applied) -> source file; fail on a missing file or a symlink.""" - source = _docs_source(pkg, checkout) + """Site path (renames applied) -> source file; fail on a missing file.""" + source = checkout / pkg.docs_root sel = select(_list_files(source), pkg.files) if sel.missing: - raise StageError(f"{pkg.name} {pkg.tag}: allowlisted docs missing: {list(sel.missing)}") + raise StageError(f"{pkg.name} {pkg.ref}: 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)}, ) - files = {} - for path in sel.copy: - src = source / path - # A symlink could pull content from outside the docs root. - if src.is_symlink(): - raise StageError(f"{pkg.name}: allowlisted docs path {path!r} is a symlink") - files[pkg.site_path(path)] = src - return files + return {pkg.site_path(path): source / path for path in sel.copy} def merge(plan: dict[str, Source], files: Mapping[str, Source], owner: str) -> None: @@ -106,17 +99,6 @@ def _remove_extras(root: Path, keep: set[str]) -> int: return removed -def _docs_source(pkg: Package, checkout: Path) -> Path: - """The package's docs directory; no part of its path may be a symlink.""" - path = checkout - for part in PurePosixPath(pkg.docs_root).parts: - path = path / part - # rglob follows a symlinked directory, which would list files from wherever it points. - if path.is_symlink(): - raise StageError(f"{pkg.name} {pkg.tag}: {pkg.docs_root}/ has a symlink in its path") - return path - - def _list_files(root: Path) -> list[str]: """Every file and symlink under `root`, as POSIX paths relative to it.""" if not root.is_dir(): diff --git a/etc/docsite.yaml b/etc/docsite.yaml index 95e9afe..429a54d 100644 --- a/etc/docsite.yaml +++ b/etc/docsite.yaml @@ -27,8 +27,6 @@ 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 @@ -40,8 +38,10 @@ brand: nav_css_url: https://www.llm-works.ai/partials/nav.css timeout_s: 10 -# Each package is fetched at a pinned release tag. `docs_root` is its docs directory in the -# repo (default: docs). The package's docs are the source and are published as they are; the +# Packages by name. Each is fetched at its git `ref`: a release tag for the published site; for a +# preview, a branch or @ (pushed), set in a gitignored Makefile.local as +# `serve: export INFRA_PACKAGES__REF := develop@9843ff` (NAME upper-cased, - as _). +# `docs_root` is its docs directory in the repo (default: docs). The package's docs are the source and are published as they are; the # arrangement is the site's. `docs` is the package's tree in the site nav and its allowlist at # once: only the files it lists are published, in that order. An entry is a path (titled by the # page's heading), {Title: path}, or {Section: [entries]}. No wildcards: a new file must be @@ -50,18 +50,18 @@ brand: # pages//index.md, and an entry {: /index.md} under Packages in # zensical.base.toml. packages: - - name: appinfra + appinfra: repo: https://github.com/llm-works/appinfra.git - tag: v0.15.0 + ref: v0.15.0 docs_root: appinfra/docs # Zensical takes a README.md as the folder's index, which is the landing page here rename: README.md: user-guide.md - # Generated from the docstrings at the tag: one page per top-level module of appinfra/ + # Generated from the docstrings at the ref: one page per top-level module of appinfra/ reference: package: appinfra - # Not listed: SECURITY.md, and index.md, the `appinfra docs` CLI's navigation page - # (the landing page here is pages/appinfra/index.md) + # Not listed: index.md, the `appinfra docs` CLI's navigation page (the landing page here is + # pages/appinfra/index.md) docs: - User guide: README.md - Getting started: getting-started.md @@ -110,5 +110,6 @@ packages: - api/subprocess.md - api/utilities.md - api/errors.md + - Security policy: SECURITY.md # The docs are published under appinfra's licence (Apache 2.0), which ships with them - License: LICENSE diff --git a/pages/appinfra/index.md b/pages/appinfra/index.md index 621f7cb..c89e081 100644 --- a/pages/appinfra/index.md +++ b/pages/appinfra/index.md @@ -3,6 +3,9 @@ hide: - toc --- + + # appinfra Production-grade Python infrastructure framework for building reliable CLI tools and services: @@ -26,7 +29,7 @@ builder APIs throughout. The other LLM Works packages build on it. - :lucide-compass:{ .lw-card-icon } - **[Guides](guides/configuration-precedence.md)** + **[Guides](guides/configuration-precedence.md)**{ #guides } Configuration, logging, testing helpers and the development tooling. @@ -38,7 +41,7 @@ builder APIs throughout. The other LLM Works packages build on it. - :lucide-braces:{ .lw-card-icon } - **[API reference](reference/index.md)** + **[API reference](reference/index.md)**{ #api-reference } Every public module, class and function, generated from the source at the release tag. diff --git a/pages/assets/tree-toggle.js b/pages/assets/tree-toggle.js index 2535159..9ec536c 100644 --- a/pages/assets/tree-toggle.js +++ b/pages/assets/tree-toggle.js @@ -1,9 +1,9 @@ -// A click on a tree section's row, its title or its arrow, always opens the section's page (every -// section has one) and flips the section: open becomes closed, closed becomes open. +// A click on a tree section's arrow only flips the section, as the theme's arrow does. A click on +// the rest of the row, its title, opens the section's page (every section has one) and flips the +// section: open becomes closed, closed becomes open. // - its page already shown: flip it in place. // - another page shown: ask tree-open.js to give the next page's tree the flipped state, and -// let the title's link open the page. A click on the arrow follows the title's link too, -// instead of only flipping the section as the theme's arrow does. +// let the title's link open the page. (function () { var ROW = ".md-nav--primary .md-nav__container"; @@ -14,7 +14,8 @@ if (!row) return; var link = row.querySelector(":scope > a.md-nav__link[href]"); var toggle = row.parentElement.querySelector(":scope > .md-nav__toggle"); - if (!link || !toggle) return; + // The arrow: its label flips the section, and nothing else happens + if (!link || !toggle || e.target.closest("label")) return; var isOpen = !toggle.checked; if (link.href.split("#")[0] === location.href.split("#")[0]) { // Before the theme's instant navigation or the arrow's label sees the click. diff --git a/tests/conftest.py b/tests/conftest.py index 22f5cb9..28bfe82 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,11 +19,10 @@ def lg() -> Logger: def package_dict(**overrides: Any) -> dict[str, Any]: - """A valid `packages` entry, with fields replaced by `overrides`.""" + """A valid `packages` entry's settings, 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", + "ref": "v0.6.3", "docs": ["INTRO.md", "demo/demo.gif"], } pkg.update(overrides) @@ -43,14 +42,13 @@ 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", }, "brand": { "tokens_url": "https://www.llm-works.ai/partials/tokens.css", "nav_css_url": "https://www.llm-works.ai/partials/nav.css", }, - "packages": [package_dict()], + "packages": {"llm-saia": package_dict()}, } cfg.update(overrides) return cfg diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 7e02eff..da81447 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -33,7 +33,7 @@ def git(cwd: Path, *args: str) -> None: @pytest.fixture def package_repo(tmp_path: Path) -> Path: - """A repo with docs/ and a package committed and tagged TAG, plus a branch named `rel`.""" + """A repo with docs/ and a package committed on main and tagged TAG.""" repo = tmp_path / "pkg-repo" files = {f"docs/{rel}": text for rel, text in DOCS.items()} | SOURCE for rel, text in files.items(): @@ -44,5 +44,4 @@ def package_repo(tmp_path: Path) -> Path: 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 3c37643..1aa10d1 100644 --- a/tests/integration/test_cli.py +++ b/tests/integration/test_cli.py @@ -10,7 +10,7 @@ import pytest from docsite.cli import main -from tests.integration.conftest import TAG +from tests.integration.conftest import TAG, git NAV = """\