diff --git a/docsite/docstring_code.py b/docsite/docstring_code.py index a200507..d6f5180 100644 --- a/docsite/docstring_code.py +++ b/docsite/docstring_code.py @@ -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()) @@ -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. """ diff --git a/docsite/reexports.py b/docsite/reexports.py new file mode 100644 index 0000000..a5ffcf9 --- /dev/null +++ b/docsite/reexports.py @@ -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, + ) diff --git a/docsite/reference.py b/docsite/reference.py index f73f2eb..19cc9f2 100644 --- a/docsite/reference.py +++ b/docsite/reference.py @@ -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 @@ -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 /: an index, then one page per module.""" - pages = {f"{REFERENCE_DIR}/index.md": _index_page(pkg, modules)} + """Page text by path under /: 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 + .md or, with subpackages of its own, /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" ) diff --git a/etc/docsite.yaml b/etc/docsite.yaml index c1f54be..5a2492e 100644 --- a/etc/docsite.yaml +++ b/etc/docsite.yaml @@ -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 diff --git a/overrides/mkdocstrings/python/material/_import.html.jinja b/overrides/mkdocstrings/python/material/_import.html.jinja new file mode 100644 index 0000000..62eec54 --- /dev/null +++ b/overrides/mkdocstrings/python/material/_import.html.jinja @@ -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 %} + + {%- filter highlight(language="pycon", inline=True) %}>>> {{ line }}{% endfilter -%} + + +{% endif %} diff --git a/overrides/mkdocstrings/python/material/attribute.html.jinja b/overrides/mkdocstrings/python/material/attribute.html.jinja new file mode 100644 index 0000000..b05290a --- /dev/null +++ b/overrides/mkdocstrings/python/material/attribute.html.jinja @@ -0,0 +1,2 @@ +{% extends "_base/attribute.html.jinja" %} +{% block labels scoped %}{{ super() }}{% with obj = attribute %}{% include "_import.html.jinja" %}{% endwith %}{% endblock labels %} diff --git a/overrides/mkdocstrings/python/material/class.html.jinja b/overrides/mkdocstrings/python/material/class.html.jinja new file mode 100644 index 0000000..57a829b --- /dev/null +++ b/overrides/mkdocstrings/python/material/class.html.jinja @@ -0,0 +1,2 @@ +{% extends "_base/class.html.jinja" %} +{% block labels scoped %}{{ super() }}{% with obj = class %}{% include "_import.html.jinja" %}{% endwith %}{% endblock labels %} diff --git a/overrides/mkdocstrings/python/material/function.html.jinja b/overrides/mkdocstrings/python/material/function.html.jinja new file mode 100644 index 0000000..0e50a28 --- /dev/null +++ b/overrides/mkdocstrings/python/material/function.html.jinja @@ -0,0 +1,2 @@ +{% extends "_base/function.html.jinja" %} +{% block labels scoped %}{{ super() }}{% with obj = function %}{% include "_import.html.jinja" %}{% endwith %}{% endblock labels %} diff --git a/overrides/mkdocstrings/python/material/type_alias.html.jinja b/overrides/mkdocstrings/python/material/type_alias.html.jinja new file mode 100644 index 0000000..06de3bb --- /dev/null +++ b/overrides/mkdocstrings/python/material/type_alias.html.jinja @@ -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 %} diff --git a/pages/assets/extra.css b/pages/assets/extra.css index d0e81d3..ade9810 100644 --- a/pages/assets/extra.css +++ b/pages/assets/extra.css @@ -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; diff --git a/pages/index.md b/pages/index.md index bdb5261..43f6461 100644 --- a/pages/index.md +++ b/pages/index.md @@ -42,18 +42,17 @@ works on its own; together they take an agent from a first prototype to a servic
-- :lucide-layers:{ .lw-card-icon } +- :lucide-bot:{ .lw-card-icon } - **[appinfra](appinfra/index.md)** + **[llm-gent](llm-gent/index.md)** - Application foundation: configuration, logging, CLI tools, services and PostgreSQL. + Agents composed from traits, run standalone or behind an HTTP runtime. -- :lucide-cpu:{ .lw-card-icon } +- :lucide-brain:{ .lw-card-icon } - **[llm-infer](llm-infer/index.md)** + **[llm-kelt](llm-kelt/index.md)** - One client for OpenAI, Anthropic, Google and OpenAI-compatible servers, plus a server for - local models. + Knowledge and learning: facts, feedback and retrieval in Postgres, and fine-tuning from them. - :lucide-braces:{ .lw-card-icon } @@ -61,16 +60,17 @@ works on its own; together they take an agent from a first prototype to a servic Typed verbs for LLM calls: verify, critique, extract and more, each with a typed result. -- :lucide-brain:{ .lw-card-icon } +- :lucide-cpu:{ .lw-card-icon } - **[llm-kelt](llm-kelt/index.md)** + **[llm-infer](llm-infer/index.md)** - Knowledge and learning: facts, feedback and retrieval in Postgres, and fine-tuning from them. + One client for OpenAI, Anthropic, Google and OpenAI-compatible servers, plus a server for + local models. -- :lucide-bot:{ .lw-card-icon } +- :lucide-layers:{ .lw-card-icon } - **[llm-gent](llm-gent/index.md)** + **[appinfra](appinfra/index.md)** - Agents composed from traits, run standalone or behind an HTTP runtime. + Application foundation: configuration, logging, CLI tools, services and PostgreSQL.
diff --git a/pages/packages/index.md b/pages/packages/index.md index afbb237..2262738 100644 --- a/pages/packages/index.md +++ b/pages/packages/index.md @@ -10,18 +10,17 @@ documentation and its API reference, at its latest release.
-- :lucide-layers:{ .lw-card-icon } +- :lucide-bot:{ .lw-card-icon } - **[appinfra](../appinfra/index.md)** + **[llm-gent](../llm-gent/index.md)** - Application foundation: configuration, logging, CLI tools, services and PostgreSQL. + Agents composed from traits, run standalone or behind an HTTP runtime. -- :lucide-cpu:{ .lw-card-icon } +- :lucide-brain:{ .lw-card-icon } - **[llm-infer](../llm-infer/index.md)** + **[llm-kelt](../llm-kelt/index.md)** - One client for OpenAI, Anthropic, Google and OpenAI-compatible servers, plus a server for - local models. + Knowledge and learning: facts, feedback and retrieval in Postgres, and fine-tuning from them. - :lucide-braces:{ .lw-card-icon } @@ -29,16 +28,17 @@ documentation and its API reference, at its latest release. Typed verbs for LLM calls: verify, critique, extract and more, each with a typed result. -- :lucide-brain:{ .lw-card-icon } +- :lucide-cpu:{ .lw-card-icon } - **[llm-kelt](../llm-kelt/index.md)** + **[llm-infer](../llm-infer/index.md)** - Knowledge and learning: facts, feedback and retrieval in Postgres, and fine-tuning from them. + One client for OpenAI, Anthropic, Google and OpenAI-compatible servers, plus a server for + local models. -- :lucide-bot:{ .lw-card-icon } +- :lucide-layers:{ .lw-card-icon } - **[llm-gent](../llm-gent/index.md)** + **[appinfra](../appinfra/index.md)** - Agents composed from traits, run standalone or behind an HTTP runtime. + Application foundation: configuration, logging, CLI tools, services and PostgreSQL.
diff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.py index 1aa10d1..231a2c4 100644 --- a/tests/integration/test_cli.py +++ b/tests/integration/test_cli.py @@ -100,11 +100,13 @@ def test_build_runs_every_step( assert (docs / "pkg" / "intro.md").is_file() assert (docs / "pkg" / "demo" / "demo.gif").is_file() assert not (docs / "pkg" / "known-issues.md").exists() + # pkgmod has no subpackages: its API, core.py included, is on the reference's own page assert ( - (docs / "pkg" / "reference" / "core.md") + (docs / "pkg" / "reference" / "index.md") .read_text(encoding="utf-8") - .endswith("::: pkgmod.core\n") + .endswith("::: pkgmod\n") ) + assert not (docs / "pkg" / "reference" / "core.md").exists() assert ( (docs / "assets" / "brand" / "tokens.css").read_text(encoding="utf-8").startswith(":root") ) diff --git a/tests/integration/test_reexports.py b/tests/integration/test_reexports.py new file mode 100644 index 0000000..e28a7d6 --- /dev/null +++ b/tests/integration/test_reexports.py @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors + +"""Re-exports from other packages listed and linked, against a package on disk.""" + +from pathlib import Path + +import griffe + +from docsite.reexports import Exports + +FILES = { + "__init__.py": ( + "from .core import Own\n" + "from .sub import Thing, plain\n" + "from .sub.inner import Unexported\n" + '__all__ = ["Own", "Thing", "plain", "Unexported"]\n' + ), + "core.py": 'class Own:\n """Defined in a file of this package."""\n', + "sub/__init__.py": ( + "from ..core import Own\n" + "from .inner import Thing, plain\n" + '__all__ = ["Own", "Thing", "plain"]\n' + ), + "sub/inner.py": ( + 'class Thing:\n """A thing."""\n\n\nplain = 1\n\n\n' + 'class Unexported:\n """Not exported by sub."""\n' + ), +} + + +def test_reexports_from_other_packages_become_a_linked_table(tmp_path: Path) -> None: + """Own-file names stay; names another package exports move to the table, linked to it when + documented; a name its package does not export stays documented here.""" + for name, text in FILES.items(): + (tmp_path / "pkg" / name).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / "pkg" / name).write_text(text, encoding="utf-8") + loaded = griffe.load( + "pkg", search_paths=[tmp_path], extensions=griffe.load_extensions(Exports()) + ) + assert isinstance(loaded, griffe.Module) + assert {"Own", "Unexported"} <= set(loaded.members) + assert "Thing" not in loaded.members and "plain" not in loaded.members + assert loaded.docstring is not None + assert "| [`Thing`][pkg.sub.Thing] | `pkg.sub` |" in loaded.docstring.value + assert "| `plain` | `pkg.sub` |" in loaded.docstring.value + # A subpackage gets the same: its own files' names stay, its parent's go to the table + sub = loaded["sub"] + assert "Thing" in sub.members and "Own" not in sub.members + assert "| [`Own`][pkg.Own] | `pkg` |" in sub.docstring.value diff --git a/tests/integration/test_reference_modules.py b/tests/integration/test_reference_modules.py index ed6f494..016b7fa 100644 --- a/tests/integration/test_reference_modules.py +++ b/tests/integration/test_reference_modules.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: MIT # SPDX-FileCopyrightText: Copyright 2026 The llm-works-docs Authors -"""Finding a package's top-level modules for the generated reference.""" +"""Finding a package's subpackages, at every depth, for the generated reference.""" from pathlib import Path @@ -13,7 +13,16 @@ def _package(root: Path) -> Path: pkg = root / "src" / "mypkg" - for rel in ("__init__.py", "core.py", "_private.py", "__main__.py", "sub/__init__.py"): + for rel in ( + "__init__.py", + "core.py", + "_private.py", + "__main__.py", + "sub/__init__.py", + "sub/inner.py", + "sub/deep/__init__.py", + "_hidden/__init__.py", + ): (pkg / rel).parent.mkdir(parents=True, exist_ok=True) (pkg / rel).write_text("", encoding="utf-8") (pkg / "docs").mkdir() # a folder without __init__.py is not a module @@ -21,12 +30,13 @@ def _package(root: Path) -> Path: return pkg -def test_public_modules_and_subpackages_sorted(tmp_path: Path) -> None: - """Private modules, plain folders, other files and symlinks are left out.""" +def test_public_subpackages_at_every_depth(tmp_path: Path) -> None: + """Subpackages follow their package; a package's own .py files, private packages, plain + folders and symlinks are left out.""" pkg = _package(tmp_path) - (pkg / "linked.py").symlink_to(pkg / "core.py") + (pkg / "linked").symlink_to(pkg / "sub") ref = Reference(package="mypkg", source="src") - assert reference_modules(tmp_path, ref) == ["mypkg.core", "mypkg.sub"] + assert reference_modules(tmp_path, ref) == ["mypkg.sub", "mypkg.sub.deep"] def test_missing_package_fails(tmp_path: Path) -> None: diff --git a/tests/unit/test_docstring_code.py b/tests/unit/test_docstring_code.py index 0da8987..ad9bbec 100644 --- a/tests/unit/test_docstring_code.py +++ b/tests/unit/test_docstring_code.py @@ -15,17 +15,31 @@ def _doc(*lines: str) -> str: return "\n".join(lines) -def test_example_block_becomes_a_python_fence() -> None: - """Indented code under Example: keeps its lines, inside a python fence.""" - text = _doc("Summary.", "", "Example:", " app = App()", " # comment", " app.run()") - assert fence_code_blocks(text) == _doc( +def test_example_code_becomes_a_session() -> None: + """Indented code under Example: is fenced as a session: >>> opens each statement and + comment, ... continues a statement, decorators included.""" + text = _doc( "Summary.", "", "Example:", - " ```python", " app = App()", " # comment", - " app.run()", + " @app.tool()", + " def run():", + "", + " pass", + ) + assert fence_code_blocks(text) == _doc( + "Summary.", + "", + "Example:", + " ```pycon", + " >>> app = App()", + " >>> # comment", + " >>> @app.tool()", + " ... def run():", + " ...", + " ... pass", " ```", ) @@ -56,4 +70,4 @@ def test_extension_rewrites_the_object_docstring() -> None: """The griffe hook replaces the docstring text before it is parsed.""" obj = SimpleNamespace(docstring=SimpleNamespace(value=_doc("Example:", " x = 1"))) CodeBlocks().on_instance(obj=cast(Any, obj)) - assert "```python" in obj.docstring.value + assert "```pycon" in obj.docstring.value diff --git a/tests/unit/test_reference_pages.py b/tests/unit/test_reference_pages.py index d5bafcb..5741d26 100644 --- a/tests/unit/test_reference_pages.py +++ b/tests/unit/test_reference_pages.py @@ -5,34 +5,46 @@ from docsite.config import load_build_config from docsite.reference import NAV_TITLE, reference_nav, reference_pages -from tests.conftest import build_dict +from tests.conftest import build_dict, package_dict -MODULES = ["llm_saia.core", "llm_saia.verbs"] +MODULES = ["llm_saia.core", "llm_saia.verbs", "llm_saia.verbs.check"] +PACKAGES = {"llm-saia": package_dict(reference={"package": "llm_saia"})} -def test_one_page_per_module_rendered_by_mkdocstrings() -> None: - """Each module page titles the module and hands it to mkdocstrings.""" - pkg = load_build_config(build_dict()).packages[0] +def test_one_page_per_package_linking_its_subpackages() -> None: + """Each package has a page rendered by mkdocstrings; one with subpackages is its folder's + index and links them.""" + pkg = load_build_config(build_dict(packages=PACKAGES)).packages[0] pages = reference_pages(pkg, MODULES) + assert set(pages) == { + "reference/index.md", + "reference/core.md", + "reference/verbs/index.md", + "reference/verbs/check.md", + } assert pages["reference/core.md"] == "# llm_saia.core\n\n::: llm_saia.core\n" - assert set(pages) == {"reference/index.md", "reference/core.md", "reference/verbs.md"} + assert pages["reference/verbs/index.md"] == ( + "# llm_saia.verbs\n\nSubpackages: [`check`](check.md)\n\n::: llm_saia.verbs\n" + ) -def test_index_names_the_ref_and_links_every_module() -> None: - """The landing page says what the reference is generated from.""" - pkg = load_build_config(build_dict()).packages[0] +def test_own_page_names_the_ref_and_renders_the_top_level() -> None: + """The reference's page says what it is generated from, links the top-level modules and + renders the package itself.""" + pkg = load_build_config(build_dict(packages=PACKAGES)).packages[0] index = reference_pages(pkg, MODULES)["reference/index.md"] assert f"# {NAV_TITLE}" in index assert "llm-saia v0.6.3" in index - assert "[`llm_saia.verbs`](verbs.md)" in index + assert "Packages: [`core`](core.md), [`verbs`](verbs/index.md)" in index + assert index.endswith("::: llm_saia\n") -def test_nav_section_lists_modules_by_short_name() -> None: - """The section opens with the index, then one entry per module.""" +def test_nav_nests_subpackages_under_their_page() -> None: + """The section opens with its page; a subpackage is a section led by its own page.""" assert reference_nav(MODULES) == { NAV_TITLE: [ "reference/index.md", {"core": "reference/core.md"}, - {"verbs": "reference/verbs.md"}, + {"verbs": ["reference/verbs/index.md", {"check": "reference/verbs/check.md"}]}, ] } diff --git a/zensical.base.toml b/zensical.base.toml index df736e0..63eeeca 100644 --- a/zensical.base.toml +++ b/zensical.base.toml @@ -44,14 +44,15 @@ nav = [ ] }, # The section's own index page first: without one, navigation.indexes takes a package's # landing page as the section page and drops it from the tree. Then one entry per package, - # by its landing page in pages//index.md. + # by its landing page in pages//index.md, from the one closest to the user (agents) down + # to the foundation, the same order as the cards on the home and Packages pages. { "Packages" = [ "packages/index.md", - { "appinfra" = "appinfra/index.md" }, - { "llm-infer" = "llm-infer/index.md" }, - { "llm-saia" = "llm-saia/index.md" }, - { "llm-kelt" = "llm-kelt/index.md" }, { "llm-gent" = "llm-gent/index.md" }, + { "llm-kelt" = "llm-kelt/index.md" }, + { "llm-saia" = "llm-saia/index.md" }, + { "llm-infer" = "llm-infer/index.md" }, + { "appinfra" = "appinfra/index.md" }, ] }, ] @@ -94,12 +95,21 @@ link = "https://www.llm-works.ai/terms/" # Generated API reference. `python -m docsite config` adds handlers.python.paths: the checkouts of # the packages that have a reference. +[project.plugins.mkdocstrings] +# Template overrides: each package-level object's heading shows its import line +custom_templates = "overrides/mkdocstrings" + [project.plugins.mkdocstrings.handlers.python.options] # Fences the indented example code that docstrings put under titles like "Example:" -extensions = ["docsite/docstring_code.py:CodeBlocks"] +# and lists a package's re-exported names, linked, instead of documenting them a second time +extensions = ["docsite/docstring_code.py:CodeBlocks", "docsite/reexports.py:Exports"] docstring_style = "google" members_order = "source" -show_submodules = true +# Each package has its own page (docsite/reference.py), so a page holds only its own members +show_submodules = false +# Private and special (dunder) members stay out of the reference; merge_init_into_class keeps +# each class's constructor +filters = ["!^_"] show_root_heading = false show_source = false show_signature_annotations = true