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
27 changes: 24 additions & 3 deletions docsite/docstring_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,34 @@ def _is_code(title: str, block: list[str]) -> bool:


def _fenced(block: list[str]) -> list[str]:
"""The block as a fenced code block at its own indentation."""
"""The block as a fenced code block at its own indentation; Python code is shown as an
interactive session, like the examples written as doctests."""
body = _dedent(block)
language = _language(body)
if language == "python":
body, language = _session(body), "pycon"
pad = " " * min(_indent(line) for line in block if line.strip())
fence = [f"{pad}```{_language(body)}"]
fence = [f"{pad}```{language}"]
fence += [f"{pad}{line}" if line else "" for line in body]
return [*fence, f"{pad}```"]


def _session(body: list[str]) -> list[str]:
"""Python code as an interactive session: >>> opens each statement and each comment
between statements, ... continues a statement over its other lines."""
continued: set[int] = set()
for node in ast.parse("\n".join(body)).body:
first = min([node.lineno, *(d.lineno for d in getattr(node, "decorator_list", []))])
continued.update(range(first + 1, (node.end_lineno or node.lineno) + 1))
session = []
for number, line in enumerate(body, start=1):
if number in continued:
session.append(f"... {line}".rstrip())
else:
session.append(f">>> {line}" if line.strip() else "")
return session


def _indent(line: str) -> int:
"""The number of leading spaces."""
return len(line) - len(line.lstrip())
Expand All @@ -115,7 +135,8 @@ def _is_doctest(lines: list[str]) -> bool:


def _language(body: list[str]) -> str:
"""pycon for a doctest, python if it parses, yaml if every line looks like YAML, else text.
"""pycon for a doctest, python if it parses (_fenced shows it as a session), yaml if every
line looks like YAML, else text.

`key: value` lines also parse as Python annotations; a block of nothing else is YAML.
"""
Expand Down
120 changes: 120 additions & 0 deletions docsite/reexports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors

"""Griffe extension: a package's names from other packages listed and linked, not documented
twice.

The reference has a page per package (docsite/reference.py), and a package's API is what its
__init__ exports. What it exports from its own files is documented in full on its page. A name
it re-exports from another package (`from ..config import Config`, or from a subpackage) is
documented on that package's page when that package exports it too; this extension takes such a
name off the exporting package and adds an Exports table to its docstring instead, each name
linked to that page. Any other name stays documented in full where it is exported.
Loaded by mkdocstrings from zensical.base.toml as `docsite/reexports.py:Exports`.
"""

from collections.abc import Iterator
from typing import Any

from griffe import (
Alias,
AliasResolutionError,
CyclicAliasError,
Docstring,
Extension,
GriffeLoader,
Module,
Object,
)

_HEADER = (
"**Exports**, documented in the package that defines them:\n\n| Name | Package |\n|---|---|\n"
)


class Exports(Extension):
"""Replaces each package's re-exports from other packages with an Exports table."""

def on_package(self, *, pkg: Module, loader: GriffeLoader, **kwargs: Any) -> None:
"""Rewrite every package of the loaded package."""
for package in _packages(pkg):
rows = [_row(name, *place) for name, place in _take_exports(package)]
if rows:
_append(package, _HEADER + "\n".join(rows), loader)


def _packages(module: Module) -> Iterator[Module]:
"""The package and all its subpackages; plain modules have no pages. (griffe's is_package
holds only for the top-level package; every package is an __init__ module.)"""
yield module
for submodule in module.modules.values():
if isinstance(submodule, Module) and submodule.is_init_module:
yield from _packages(submodule)


def _take_exports(package: Module) -> list[tuple[str, tuple[Module, str, Object]]]:
"""Remove the package's public re-exports documented on another package's page; return each
name with that package, the name it has there, and the object."""
taken = []
for name, member in list(package.members.items()):
if isinstance(member, Alias) and member.is_public:
place = _documented_on(member, package)
if place is not None:
package.del_member(name)
taken.append((name, place))
return taken


def _documented_on(alias: Alias, package: Module) -> tuple[Module, str, Object] | None:
"""The other public package that defines and exports the alias's object, its name there,
and the object; None when the object is documented here (defined in this package, or not
exported where it is defined) or comes from outside."""
try:
target = alias.final_target
except (AliasResolutionError, CyclicAliasError):
return None # outside the loaded package
if isinstance(target, Alias) or target.is_module or target.package is not package.package:
return None
owner = target.module if target.module.is_init_module else target.module.parent
if not isinstance(owner, Module) or owner is package:
return None
if any(part.startswith("_") for part in owner.path.split(".")):
return None
name = _exported_name(owner, target)
return None if name is None else (owner, name, target)


def _exported_name(package: Module, target: Object) -> str | None:
"""The public name under which `package` exports `target`, or None."""
for name, member in package.members.items():
if not member.is_public:
continue
if member is target:
return name
if isinstance(member, Alias):
try:
if member.final_target is target:
return name
except (AliasResolutionError, CyclicAliasError):
continue
return None


def _row(name: str, owner: Module, owner_name: str, target: Object) -> str:
"""A table row: the name, linked to where it is documented when it has docstrings
(mkdocstrings skips an object without), and that package."""
shown = f"[`{name}`][{owner.path}.{owner_name}]" if target.has_docstrings else f"`{name}`"
return f"| {shown} | `{owner.path}` |"


def _append(module: Module, text: str, loader: GriffeLoader) -> None:
"""Append `text` to the module's docstring, creating one if it has none."""
if module.docstring is not None:
module.docstring.value = f"{module.docstring.value}\n\n{text}"
else:
module.docstring = Docstring(
text,
parent=module,
parser=loader.docstring_parser,
parser_options=loader.docstring_options,
)
111 changes: 86 additions & 25 deletions docsite/reference.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors

"""Generated API reference pages: one per top-level module, rendered by mkdocstrings."""
"""Generated API reference pages: one per package and subpackage, rendered by mkdocstrings.

A package's API is what its __init__ exports. The tree under API reference follows the
subpackages; a subpackage with subpackages of its own is a section led by its page. A page links
its subpackages, then mkdocstrings renders the package: its docstring, with the Exports table
docsite/reexports.py adds for names documented on another package's page, and in full what the
package defines and exports from its own files. The reference's own page does the same for the
package's top level.
"""

from pathlib import Path

Expand All @@ -16,47 +24,100 @@ class ReferenceSourceError(RuntimeError):


def reference_modules(checkout: Path, ref: Reference) -> list[str]:
"""The package's public top-level modules and subpackages, as dotted names, sorted."""
"""The package's public subpackages at every depth, as dotted names: siblings sorted, a
package before its subpackages. A package's own .py files have no pages: what it exports
from them is documented on the package's page."""
root = checkout / ref.source / ref.package
if not (root / "__init__.py").is_file() or root.is_symlink():
raise ReferenceSourceError(f"{root} is not a package directory")
modules = []
for entry in sorted(root.iterdir()):
name = entry.stem if entry.suffix == ".py" else entry.name
if name.startswith("_") or entry.is_symlink():
return _walk(root, ref.package)


def _walk(folder: Path, dotted: str) -> list[str]:
"""The public subpackages under `folder`, the package `dotted`, recursively."""
packages = []
for entry in sorted(folder.iterdir()):
if entry.name.startswith("_") or entry.is_symlink():
continue
is_module = entry.is_file() and entry.suffix == ".py"
if is_module or (entry / "__init__.py").is_file():
modules.append(f"{ref.package}.{name}")
return modules
if (entry / "__init__.py").is_file():
packages.append(f"{dotted}.{entry.name}")
packages += _walk(entry, f"{dotted}.{entry.name}")
return packages


def reference_pages(pkg: Package, modules: list[str]) -> dict[str, str]:
"""Page text by path under <name>/: an index, then one page per module."""
pages = {f"{REFERENCE_DIR}/index.md": _index_page(pkg, modules)}
"""Page text by path under <name>/: the reference's own page, then one page per
subpackage in `modules`."""
if pkg.reference is None:
return {}
parents = _parents(modules)
root = pkg.reference.package
pages = {f"{REFERENCE_DIR}/index.md": _index_page(pkg, root, modules, parents)}
for module in modules:
pages[_module_path(module)] = f"# {module}\n\n::: {module}\n"
page = f"# {module}\n\n{_subpackages(module, modules, parents)}::: {module}\n"
pages[_module_path(module, parents)] = page
return pages


def reference_nav(modules: list[str]) -> NavItem:
"""The API reference section: the index, then each module by its short name."""
entries: list[NavItem] = [f"{REFERENCE_DIR}/index.md"]
entries += [{module.split(".", 1)[1]: _module_path(module)} for module in modules]
return {NAV_TITLE: entries}
"""The API reference section: its own page, then the subpackage tree by short names."""
root = modules[0].split(".")[0] if modules else ""
entries = _nav_entries(root, modules, _parents(modules))
return {NAV_TITLE: [f"{REFERENCE_DIR}/index.md", *entries]}


def _nav_entries(parent: str, modules: list[str], parents: set[str]) -> list[NavItem]:
"""The nav entries of `parent`'s subpackages; one with subpackages of its own is a section
led by its page."""
entries: list[NavItem] = []
for module in _children(parent, modules):
short, page = module.rpartition(".")[2], _module_path(module, parents)
if module in parents:
entries.append({short: [page, *_nav_entries(module, modules, parents)]})
else:
entries.append({short: page})
return entries


def _parents(modules: list[str]) -> set[str]:
"""The packages that have subpackages."""
return {module.rpartition(".")[0] for module in modules}


def _module_path(module: str) -> str:
"""The page of a module, under reference/."""
return f"{REFERENCE_DIR}/{module.split('.', 1)[1]}.md"
def _children(parent: str, modules: list[str]) -> list[str]:
"""The direct subpackages of `parent`, in order."""
return [module for module in modules if module.rpartition(".")[0] == parent]


def _module_path(module: str, parents: set[str]) -> str:
"""The page of a package under reference/: one with subpackages gets a folder."""
rel = module.split(".", 1)[1].replace(".", "/")
return f"{REFERENCE_DIR}/{rel}/index.md" if module in parents else f"{REFERENCE_DIR}/{rel}.md"


def _subpackages(module: str, modules: list[str], parents: set[str]) -> str:
"""A line linking `module`'s subpackages from its page; empty if it has none."""
links = _links(module, modules, parents)
return f"Subpackages: {links}\n\n" if links else ""


def _links(parent: str, modules: list[str], parents: set[str]) -> str:
"""Links to `parent`'s subpackages from the folder of `parent`'s page, where each one is
<name>.md or, with subpackages of its own, <name>/index.md."""
return ", ".join(
f"[`{name}`]({name}/index.md)" if child in parents else f"[`{name}`]({name}.md)"
for child in _children(parent, modules)
for name in [child.rpartition(".")[2]]
)


def _index_page(pkg: Package, modules: list[str]) -> str:
"""The reference landing page: what it is generated from, and every module."""
links = "\n".join(f"- [`{m}`]({m.split('.', 1)[1]}.md)" for m in modules)
def _index_page(pkg: Package, root: str, modules: list[str], parents: set[str]) -> str:
"""The reference's own page: what it is generated from, the top-level subpackages, and the
package's top level rendered like a subpackage's page."""
links = _links(root, modules, parents)
return (
f"# {NAV_TITLE}\n\n"
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"
"one package: its subpackages, the names it re-exports from other packages, and its own "
"API in full.\n\n" + (f"Packages: {links}\n\n" if links else "") + f"::: {root}\n"
)
2 changes: 1 addition & 1 deletion etc/docsite.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ packages:
README.md: user-guide.md
# A plain-text file renamed to .md is published as a page, its text in a code block
LICENSE: license.md
# Generated from the docstrings at the ref: one page per top-level module of appinfra/
# Generated from the docstrings at the ref: one page per package and subpackage of appinfra/
reference:
package: appinfra
# Not listed: index.md, the `appinfra docs` CLI's navigation page (the landing page here is
Expand Down
12 changes: 12 additions & 0 deletions overrides/mkdocstrings/python/material/_import.html.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{#- The import line of a package-level object, at the right of its heading: shown as a console
line (>>>) like the docstrings' examples, highlighted, with the theme's copy button, which copies
the line without the prompt (its clipboard handler copies a button's data-clipboard-text). The page
documents the object under the package that exports it, so that package is where it is imported
from. Members of classes have none. -#}
{% if obj.parent and obj.parent.is_module %}
{% set line = "from " ~ obj.parent.path ~ " import " ~ obj.name %}
<span class="doc-import">
{%- filter highlight(language="pycon", inline=True) %}>>> {{ line }}{% endfilter -%}
<nav class="md-code__nav"><button class="md-code__button" title="Copy to clipboard" data-clipboard-text="{{ line }}" data-md-type="copy"></button></nav>
</span>
{% endif %}
2 changes: 2 additions & 0 deletions overrides/mkdocstrings/python/material/attribute.html.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{% extends "_base/attribute.html.jinja" %}
{% block labels scoped %}{{ super() }}{% with obj = attribute %}{% include "_import.html.jinja" %}{% endwith %}{% endblock labels %}
2 changes: 2 additions & 0 deletions overrides/mkdocstrings/python/material/class.html.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{% extends "_base/class.html.jinja" %}
{% block labels scoped %}{{ super() }}{% with obj = class %}{% include "_import.html.jinja" %}{% endwith %}{% endblock labels %}
2 changes: 2 additions & 0 deletions overrides/mkdocstrings/python/material/function.html.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{% extends "_base/function.html.jinja" %}
{% block labels scoped %}{{ super() }}{% with obj = function %}{% include "_import.html.jinja" %}{% endwith %}{% endblock labels %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{% extends "_base/type_alias.html.jinja" %}
{% block labels scoped %}{{ super() }}{% with obj = type_alias %}{% include "_import.html.jinja" %}{% endwith %}{% endblock labels %}
45 changes: 45 additions & 0 deletions pages/assets/extra.css
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,51 @@ html { font-size: 20px; }
vertical-align: top;
}

/* --- API reference: an object's import line at the right of its heading --- */
/* (overrides/mkdocstrings/python/material/_import.html.jinja). On a narrow page it wraps under
the name instead, kept inside the heading (flow-root contains the float). */
.md-typeset .doc-heading {
display: flow-root;
}

.md-typeset .doc-heading .doc-import {
position: relative;
float: right;
margin-left: 1em;
/* The code size (below): the copy button's em sizes follow it, as in the signature blocks */
font-size: 13.6px;
font-weight: normal;
line-height: 1.6;
}

/* A one-line code block: the copy button inside it on the right, as on the signature blocks */
.md-typeset .doc-import > code {
display: inline-block;
padding: 0.35em 2.8em 0.35em 0.9em;
}

.md-typeset .doc-import .md-code__nav {
top: 50%;
right: 0.25em;
transform: translateY(-50%);
}

/* Copying a session (>>> examples) copies only its code: the theme copies the block's innerText
while it carries data-md-copying, so prompts (.gp) and output (.go) hidden then are left out */
.highlight code[data-md-copying] :is(.gp, .go) {
display: none;
}

/* --- Code: one size everywhere, 13.6px (the theme's .85em of the 16px body text) --- */
/* The theme sizes code in em, so code in tables and in example boxes (both .64rem text) came out
at 10.9px next to 13.6px elsewhere. Code in a heading keeps scaling with it, except the
reference's labels and import lines; the symbol badges (c, f, m) keep the theme's size. */
.md-typeset pre,
.md-typeset code:not(.doc-symbol):not(:is(h1, h2, h3, h4, h5, h6) code),
.md-typeset .doc-heading :is(.doc-label code, .doc-import code) {
font-size: 13.6px;
}

/* --- Home lead and actions: the main site's .cta-primary button and .door-link text link --- */
.md-typeset .lw-lead {
font-size: 1.05em;
Expand Down
Loading