From 0cc4c15dcd407b9a31036c0609a2b153903440d8 Mon Sep 17 00:00:00 2001 From: Hassan Kibirige Date: Fri, 4 Dec 2026 15:26:49 +0300 Subject: [PATCH] feat: group API objects on named reference pages Publish related objects at a chosen reference URL with one sidebar entry and a link to each object. Rebuild historical snapshot references from their own symbol lists. --- docs/user_guide/06-api-documentation.qmd | 27 +++ great_docs/_apiref/_rendering/api_pages.py | 28 ++- great_docs/_apiref/_rendering/members.py | 8 +- great_docs/_apiref/api_reference.py | 4 +- great_docs/_apiref/collect.py | 35 +++- great_docs/_apiref/content.py | 2 + great_docs/_apiref/resolve.py | 13 +- great_docs/_apiref/spec.py | 139 +++++++++++++-- great_docs/_cli/project.py | 3 +- great_docs/_mcp/tools.py | 4 +- great_docs/_reference/exports.py | 3 +- great_docs/_reference/sections.py | 48 ++++- great_docs/_versions/build.py | 38 +++- tests/test_great_docs.py | 11 +- tests/test_reference_group_pages.py | 195 +++++++++++++++++++++ 15 files changed, 494 insertions(+), 64 deletions(-) create mode 100644 tests/test_reference_group_pages.py diff --git a/docs/user_guide/06-api-documentation.qmd b/docs/user_guide/06-api-documentation.qmd index fe49662ed..f118491d0 100644 --- a/docs/user_guide/06-api-documentation.qmd +++ b/docs/user_guide/06-api-documentation.qmd @@ -299,6 +299,33 @@ exactly. A misspelled name, a name that was renamed or removed, or a name that a expected after a build, check that the name in your `reference` config matches what your package exports. +### Grouped Reference Pages + +Use a `kind: page` entry to document related objects on one page. Set `path` to the page's +path within the reference directory, omitting `.qmd` or `.html`. List the objects in `contents`, +using the same names and member options as for entries directly in a section. + +```{.yaml filename="docs/great-docs.yml"} +reference: + - title: Authentication + contents: + - kind: page + path: sessions + summary: + name: Login sessions + desc: Create and end login sessions. + contents: + - login + - logout +``` + +This publishes `reference/sessions.html` with a heading and link target for each object. +`summary.name` labels the page in the title, sidebar and reference index. If omitted, it +defaults to the filename stem. `summary.desc` adds a description to the reference index. + +Historical versions that use `api_snapshot` or `git_ref` reconstruct their reference from +individual symbols. Each symbol gets its own page in those versions. + ### Custom Title and Description You can customize the heading and introductory text of the API reference page using the `title` and diff --git a/great_docs/_apiref/_rendering/api_pages.py b/great_docs/_apiref/_rendering/api_pages.py index 9773bb38e..157101485 100644 --- a/great_docs/_apiref/_rendering/api_pages.py +++ b/great_docs/_apiref/_rendering/api_pages.py @@ -1,8 +1,7 @@ """ API pages, with their front matter, objects and summary rows -A page with one object renders it at the page's heading level; a page with several -renders each one level deeper. +A page with its own title renders object headings one level deeper. """ from __future__ import annotations @@ -46,10 +45,9 @@ class APIPageRenderer(PageRendererMixin, BaseRenderer): """ An API page that documents one or more prepared Python objects - The page title in the front matter comes from the first object. A page with one - object omits that object's heading, which would repeat the title; a page with - several keeps each object's heading, one level deeper. The page's summary rows - come from its authored summary or from its objects' own rows. + The page title comes from the authored summary or the first object. When an + object supplies the title of its own page, its heading is omitted. On other + pages each object has a separate heading. """ toc_depth: int = _DEFAULT_SITE_TOC_DEPTH @@ -69,23 +67,22 @@ def __post_init__(self) -> None: """The page's path relative to the output directory, which its objects' `context` reports""" @property - def _has_one_object(self) -> bool: - """Whether the page contains exactly one documented object""" - return len(self.page.contents) == 1 + def _has_object_title(self) -> bool: + """Whether the page title replaces its only object's heading""" + return len(self.page.contents) == 1 and self.page.summary is None @cached_property def object_renderers(self) -> list[ObjectRenderer]: """The renderers of the page's objects, which share the page's context""" - level = self.level if self._has_one_object else self.level + 1 + level = self.level if self._has_object_title else self.level + 1 return [ self.make_renderer(c, level, page_path=self.path, _purpose=_RenderingPurpose.API_PAGE) for c in self.page.contents ] def render_metadata(self) -> BlockContent: - # Derive the title of the page from the first (top-level) object """ - Render the page front matter from the first object's title and the page summary + Render the page front matter with its title and description The description comes from the authored summary, or else the first object's subject. The page raises `toc-depth` only when the site setting would hide @@ -97,7 +94,8 @@ def render_metadata(self) -> BlockContent: The front matter. """ obj = self.object_renderers[0] - title = obj.title_content + summary = self.page.summary + title = summary.name if summary else obj.title_content metadata: dict[str, object] = { "title": f"{title}", "body-classes": "doc-api-page doc-py-api-page", @@ -109,8 +107,8 @@ def render_metadata(self) -> BlockContent: # Add a page override only when the site depth excludes members. if self.toc_depth < _MIN_MEMBER_TOC_DEPTH: metadata["toc-depth"] = _MIN_MEMBER_TOC_DEPTH - summary = self.page.summary - if description := metadata_value(summary.desc if summary else obj.docstring_subject): + subject = summary.desc if summary and summary.desc else obj.docstring_subject + if description := metadata_value(subject): metadata["description-meta"] = description return Meta(metadata) diff --git a/great_docs/_apiref/_rendering/members.py b/great_docs/_apiref/_rendering/members.py index b9e83b833..89bb69f00 100644 --- a/great_docs/_apiref/_rendering/members.py +++ b/great_docs/_apiref/_rendering/members.py @@ -8,6 +8,7 @@ from __future__ import annotations +import posixpath from dataclasses import dataclass from functools import cached_property from typing import TYPE_CHECKING, cast @@ -352,9 +353,12 @@ def _render_member_pages_group( }[group] member_renderers = [ self.make_renderer( - Doc.from_griffe(page.obj.name, page.obj, anchor=""), + Doc.from_griffe(page.obj.name, page.obj, anchor=page.target_anchor), contained=False, - page_path=f"{page.path}.qmd", + page_path=posixpath.relpath( + f"{page.path}{self.settings.out_page_suffix}", + start=posixpath.dirname(self.page_path or "") or ".", + ), ) for page in pages ] diff --git a/great_docs/_apiref/api_reference.py b/great_docs/_apiref/api_reference.py index 220e28e86..747a0f012 100644 --- a/great_docs/_apiref/api_reference.py +++ b/great_docs/_apiref/api_reference.py @@ -112,7 +112,9 @@ def __init__( # Pages, the index, the sidebar and the text export share the same page paths. self.sections = unique_page_paths( - [SpecSection(**section) for section in spec.sections], self._entry_label + [SpecSection(**section) for section in spec.sections], + self._entry_label, + index_path=self.settings.out_index.removesuffix(self.settings.out_page_suffix), ) @property diff --git a/great_docs/_apiref/collect.py b/great_docs/_apiref/collect.py index 5ac1ef408..7793c7ea1 100644 --- a/great_docs/_apiref/collect.py +++ b/great_docs/_apiref/collect.py @@ -267,7 +267,12 @@ def remove_package_prefix(sections: list[Section], package: str) -> list[Section class _MemberPagePathClaimer(NodeTransformer): """A tree whose member links and generated pages use their published paths""" - def __init__(self, claimed: dict[str, str], authored: dict[tuple[str, str], str]) -> None: + def __init__( + self, + claimed: dict[str, str], + authored: dict[tuple[str, str], tuple[str, str]], + grouped_paths: set[str], + ) -> None: """ Claim member page paths that do not clash with the paths already claimed @@ -277,10 +282,13 @@ def __init__(self, claimed: dict[str, str], authored: dict[tuple[str, str], str] The paths already claimed, keyed by their casefolded form. Each claimed member page path is added to it. authored - The published page path for each authored lookup path and canonical object. + The page path and fragment for each authored lookup path and canonical object. + grouped_paths + Authored page paths reserved for groups of objects. """ self.claimed = claimed self.authored = authored + self.grouped_paths = grouped_paths def enter(self, el: object) -> object: """ @@ -291,7 +299,8 @@ def enter(self, el: object) -> object: if doc.lookup_path is not None: target = self.authored.get((doc.lookup_path, doc.obj.canonical_path)) if target is not None: - return el.replace(path=target, link_only=True) + path, anchor = target + return el.replace(path=path, target_anchor=anchor, link_only=True) return super().enter(el) def exit(self, el: object) -> object: @@ -309,7 +318,12 @@ def exit(self, el: object) -> object: The node, or a copy of a member page with a new path. """ if isinstance(el, MemberPage) and not el.link_only: - path = claim_page_path(el.path, self.claimed, partial(get_label, el.obj)) + path = claim_page_path( + el.path, + self.claimed, + partial(get_label, el.obj), + allow_same=el.path.casefold() not in self.grouped_paths, + ) return el if path == el.path else el.replace(path=path) return super().exit(el) @@ -334,17 +348,20 @@ def unique_member_page_paths(sections: list[Section]) -> list[Section]: The sections with member links and generated page paths resolved. """ claimed: dict[str, str] = {} - authored: dict[tuple[str, str], str] = {} + authored: dict[tuple[str, str], tuple[str, str]] = {} + grouped_paths: set[str] = set() for section in sections: for entry in section.contents: if isinstance(entry, Page) and not isinstance(entry, MemberPage): _ = claim_page_path(entry.path, claimed) - if len(entry.contents) == 1: - doc = entry.contents[0] + if entry.summary is not None: + grouped_paths.add(entry.path.casefold()) + for doc in entry.contents: if doc.lookup_path is not None: _ = authored.setdefault( - (doc.lookup_path, doc.obj.canonical_path), entry.path + (doc.lookup_path, doc.obj.canonical_path), + (entry.path, doc.anchor if entry.summary is not None else ""), ) - claimer = _MemberPagePathClaimer(claimed, authored) + claimer = _MemberPagePathClaimer(claimed, authored, grouped_paths) return claimer.visit(sections) # type: ignore[return-value] diff --git a/great_docs/_apiref/content.py b/great_docs/_apiref/content.py index 0a9d3ee18..abd68b489 100644 --- a/great_docs/_apiref/content.py +++ b/great_docs/_apiref/content.py @@ -213,6 +213,8 @@ class MemberPage(Page): contents: list[Any] = field(default_factory=list[Any]) link_only: bool = False """Whether an authored page at this path already documents the member""" + target_anchor: str = "" + """The member's fragment when its authored page documents several objects""" @dataclass diff --git a/great_docs/_apiref/resolve.py b/great_docs/_apiref/resolve.py index cad4dc37c..99e101721 100644 --- a/great_docs/_apiref/resolve.py +++ b/great_docs/_apiref/resolve.py @@ -30,7 +30,7 @@ from ._type_checks import is_enum from ._walkable import MISSING, MissingType, Walkable from .content import Doc, DocAttribute, MemberPage, Page, Section, Text -from .spec import SpecObject, SpecOptions, SpecSection, SpecText +from .spec import SpecObject, SpecOptions, SpecPage, SpecSection, SpecText # Dunder members inherited from `object`/`type` (or PyO3 metaclasses) that carry docstrings but are # never useful API documentation. Filtered out unconditionally so they do not pollute reference @@ -527,8 +527,8 @@ def _resolve_entry(self, el: SpecEntry) -> Page | Text | None: """ Rebuild a single section entry as its resolved `content` counterpart - A documented object becomes its own single-object `Page`; a free-text - block stays inline as a `Text`. + A named page retains its selected objects and summary. A standalone + object gets its own page, and a free-text block stays inline. Parameters ---------- @@ -543,13 +543,18 @@ def _resolve_entry(self, el: SpecEntry) -> Page | Text | None: Raises ------ TypeError - If `el` is neither an object nor a text block. + If the entry has no resolved content type. """ if isinstance(el, SpecObject): doc = self._resolve_object(el) if doc is None: return None return Page(contents=cast("list[Any]", [doc]), path=el.page_path) + if isinstance(el, SpecPage): + documents = [doc for entry in el.contents if (doc := self._resolve_object(entry))] + if not documents: + return None + return Page(path=el.path, contents=cast("list[Any]", documents), summary=el.summary) if isinstance(el, SpecText): return self._resolve_text(el) raise TypeError(f"Cannot resolve section entry of type: {type(el)}") diff --git a/great_docs/_apiref/spec.py b/great_docs/_apiref/spec.py index f5a18e5c3..e9ec85bb4 100644 --- a/great_docs/_apiref/spec.py +++ b/great_docs/_apiref/spec.py @@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Any, Final, Self, cast from ._walkable import MISSING, MissingType, Walkable +from .content import SummaryItem from .introspect import validate_dynamic if TYPE_CHECKING: @@ -275,6 +276,77 @@ class SpecText(Walkable): contents: str = "" +@dataclass(kw_only=True) +class SpecPage(Walkable): + """A reference page with an authored path and one or more named objects""" + + path: str + contents: list[SpecObject] + summary: SummaryItem = field(default_factory=SummaryItem) + kind: str = "page" + + @classmethod + def make(cls, raw: dict[str, Any]) -> SpecPage: + """Validate a page path, summary and list of object entries""" + path = raw.get("path") + if ( + not isinstance(path, str) + or path.casefold().endswith((".qmd", ".html")) + or not all( + re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", part) and not part.endswith(".") + for part in path.split("/") + ) + ): + raise ValueError( + f"Reference page path {path!r} must be relative to the reference directory " + "and omit the filename extension." + ) + + if unsupported := raw.keys() - {"kind", "path", "summary", "contents"}: + keys = ", ".join(sorted(map(str, unsupported))) + raise ValueError(f"Unsupported options for reference page `{path}`: {keys}.") + + contents = raw.get("contents") + if not isinstance(contents, list) or not contents: + raise ValueError( + f"Reference page `{path}` must list at least one object in `contents`." + ) + + entries: list[SpecObject] = [] + for value in cast("list[object]", contents): + if isinstance(value, SpecObject): + entries.append(value) + continue + if isinstance(value, str) and value.strip(): + entries.append(SpecObject(name=value)) + continue + if isinstance(value, dict): + item = cast("dict[str, Any]", value) + name = item.get("name") + if ( + item.get("kind", "object") == "object" + and isinstance(name, str) + and name.strip() + ): + entries.append(_coerce_spec_object(item)) + continue + raise ValueError(f"Each entry on reference page `{path}` must name a Python object.") + + summary = raw.get("summary", {}) + if not isinstance(summary, dict) or summary.keys() - {"name", "desc"}: + raise ValueError( + f"Reference page `{path}` `summary` must be a mapping of `name` and `desc`." + ) + summary = cast("dict[str, object]", summary) + name = summary.get("name", path.rsplit("/", 1)[-1]) + desc = summary.get("desc", "") + if not isinstance(name, str) or not name.strip() or not isinstance(desc, str): + raise ValueError( + f"Reference page `{path}` must have a non-empty name and a text description." + ) + return cls(path=path, contents=entries, summary=SummaryItem(name=name, desc=desc)) + + @dataclass class SpecSection(Walkable): """A section of the reference index page, as written in the config""" @@ -303,16 +375,20 @@ def __post_init__(self) -> None: raise ValueError("Section must specify a title, subtitle, or contents field") elif self.title is not None and self.subtitle is not None: raise ValueError("Section cannot specify both title and subtitle fields.") - # Raw YAML entries (strings/dicts) become `SpecObject`; already-built - # nodes pass through unchanged. raw_contents = cast("list[Any]", self.contents) - self.contents = cast( - "list[SpecEntry]", - [c if isinstance(c, Walkable) else _coerce_spec_object(c) for c in raw_contents], - ) + self.contents = [_coerce_spec_entry(c) for c in raw_contents] + + +SpecEntry = SpecSection | SpecObject | SpecPage | SpecText -SpecEntry = SpecSection | SpecObject | SpecText +def _coerce_spec_entry(value: SpecEntry | str | dict[str, Any]) -> SpecEntry: + """Turn a YAML entry into a single object or a named reference page""" + if isinstance(value, Walkable): + return value + if isinstance(value, dict) and value.get("kind") == "page": + return SpecPage.make(value) + return _coerce_spec_object(value) def _coerce_spec_object(value: str | dict[str, Any]) -> SpecObject: @@ -335,7 +411,11 @@ def _coerce_spec_object(value: str | dict[str, Any]) -> SpecObject: def claim_page_path( - path: str, claimed: dict[str, str], label: Callable[[], str | None] | None = None + path: str, + claimed: dict[str, str], + label: Callable[[], str | None] | None = None, + *, + allow_same: bool = True, ) -> str: """ Claim a reference page path that no other page shares on a case-insensitive filesystem @@ -346,7 +426,7 @@ def claim_page_path( claimed keeps its name. A later path that matches it case-insensitively is suffixed with the label shown on its page (`template-function`), then with a number if that is taken too (`FOO-class-2`). Claiming the exact same path - twice returns it unchanged. + twice returns it unchanged unless `allow_same` is false. Parameters ---------- @@ -358,6 +438,8 @@ def claim_page_path( Returns the label of the object documented on the page, or `None` when it cannot be determined. Only called when `path` collides, so no object is looked up for a page that keeps its name. + allow_same + Whether a previously claimed path can be reused with identical spelling. Returns ------- @@ -381,7 +463,7 @@ def is_free(candidate: str) -> bool: Whether `candidate` can be claimed without a clash. """ owner = claimed.get(candidate.casefold()) - return owner is None or owner == candidate + return owner is None or (allow_same and owner == candidate) candidate = path if not is_free(path): @@ -393,12 +475,15 @@ def is_free(candidate: str) -> bool: while not is_free(candidate): candidate = f"{base}-{n}" n += 1 - warnings.warn( - f"Reference page `{path}` differs from `{claimed[path.casefold()]}` only by " - f"case; writing it to `{candidate}` so both pages survive on " - "case-insensitive filesystems.", - stacklevel=2, - ) + owner = claimed[path.casefold()] + if owner == path: + message = f"Reference page `{path}` is already in use; writing it to `{candidate}`." + else: + message = ( + f"Reference page `{path}` differs from `{owner}` only by case; writing it to " + f"`{candidate}` so both pages survive on case-insensitive filesystems." + ) + warnings.warn(message, stacklevel=2) claimed[candidate.casefold()] = candidate return candidate @@ -406,6 +491,8 @@ def is_free(candidate: str) -> bool: def unique_page_paths( sections: list[SpecSection], label: Callable[[SpecSection, SpecObject], str | None] | None = None, + *, + index_path: str = "index", ) -> list[SpecSection]: """ Give every documented entry a page path no other entry shares case-insensitively @@ -421,6 +508,8 @@ def unique_page_paths( Returns the label of the object that an entry of a section documents, or `None` when it cannot be determined. Only called for an entry whose page path collides. + index_path + The reference index's path without its filename suffix. Returns ------- @@ -429,6 +518,8 @@ def unique_page_paths( Sections without a collision are returned as-is. """ claimed: dict[str, str] = {} + authored: dict[str, str] = {index_path.casefold(): index_path} + grouped: dict[str, str] = {} def visit(section: SpecSection) -> SpecSection: """ @@ -448,9 +539,25 @@ def visit(section: SpecSection) -> SpecSection: for entry in section.contents: if isinstance(entry, SpecSection): contents.append(visit(entry)) + elif isinstance(entry, SpecPage): + path = entry.path + key = path.casefold() + if key in authored or key in grouped: + raise ValueError( + f"Reference page `{path}` conflicts with another reference page." + ) + grouped[key] = path + contents.append(entry) elif isinstance(entry, SpecObject): entry_label = None if label is None else partial(label, section, entry) path = claim_page_path(entry.page_path, claimed, entry_label) + for candidate in (entry.page_path, path): + key = candidate.casefold() + if key in grouped: + raise ValueError( + f"Reference page `{grouped[key]}` conflicts with an object page." + ) + authored[key] = candidate contents.append(entry if path == entry.page_path else entry.with_page_path(path)) else: contents.append(entry) diff --git a/great_docs/_cli/project.py b/great_docs/_cli/project.py index bd59a64f8..d468552bd 100644 --- a/great_docs/_cli/project.py +++ b/great_docs/_cli/project.py @@ -16,6 +16,7 @@ from .._project.remote import HttpRemote from .._project.scaffold import update_gitignore from .._reference.exports import Exports +from .._reference.sections import configured_objects from .._website import changelog as changelog_page from .._website import quarto_yml, website_overlay from ..core import GreatDocs @@ -565,7 +566,7 @@ def scan( ref_classes_without_members = set() # Classes with members: false for section in reference_config: - for item in section.get("contents", []): + for item in configured_objects(section.get("contents", [])): if isinstance(item, str): ref_items.add(item) elif isinstance(item, dict): diff --git a/great_docs/_mcp/tools.py b/great_docs/_mcp/tools.py index bfaaa403c..764c9f180 100644 --- a/great_docs/_mcp/tools.py +++ b/great_docs/_mcp/tools.py @@ -451,11 +451,13 @@ async def _handle_scan(arguments: dict) -> list[TextContent]: # Build structured output lines = [f"Package: {importable_name}", f"Total exports: {len(exports)}", ""] + from .._reference.sections import configured_objects + # Reference config status reference_config = package_exports.config.reference ref_items = set() for section in reference_config: - for item in section.get("contents", []): + for item in configured_objects(section.get("contents", [])): if isinstance(item, str): ref_items.add(item) elif isinstance(item, dict): diff --git a/great_docs/_reference/exports.py b/great_docs/_reference/exports.py index 95afb8aef..ffd852ceb 100644 --- a/great_docs/_reference/exports.py +++ b/great_docs/_reference/exports.py @@ -289,7 +289,8 @@ def _configured_sections( section["package"] = scope by_scope: defaultdict[str | None, list[object]] = defaultdict(list) - for item in cast("list[object]", section.get("contents") or []): + contents = cast("list[object]", section.get("contents") or []) + for item in reference_sections.configured_objects(contents): entry_scope = scope if isinstance(item, dict): item = cast("dict[str, str | None]", item) diff --git a/great_docs/_reference/sections.py b/great_docs/_reference/sections.py index 5e63ae01e..cc87e4bcb 100644 --- a/great_docs/_reference/sections.py +++ b/great_docs/_reference/sections.py @@ -11,6 +11,8 @@ from .._contribution import Contribution, NavbarLink, Sidebar if TYPE_CHECKING: + from collections.abc import Iterator + from .._apiref.api_reference import APIReference from .._apiref.spec import ReferenceSpec from ..config import Config @@ -51,6 +53,34 @@ def _configured_entry(item: dict[str, Any]) -> str | dict[str, Any]: return entry if len(entry) > 1 else name +def configured_objects(contents: Sequence[object]) -> Iterator[object]: + """List object entries in a section, including those on its named pages""" + for entry in contents: + item = cast("dict[str, object]", entry) if isinstance(entry, dict) else {} + if item.get("kind") == "page": + items = item.get("contents") + if isinstance(items, list): + yield from cast("list[object]", items) + else: + yield entry + + +def _configured_page(page: dict[str, Any]) -> dict[str, Any]: + """Apply the normal object options to the entries on an authored page""" + contents = page.get("contents") + if not isinstance(contents, list): + return page + objects: list[object] = [] + for entry in cast("list[object]", contents): + value: object = entry + if isinstance(entry, dict): + item = cast("dict[str, Any]", entry) + if item.get("name") and item.get("kind", "object") == "object": + value = _configured_entry({key: val for key, val in item.items() if key != "kind"}) + objects.append(value) + return {**page, "contents": objects} + + def from_reference_config( reference_config: Sequence[object] | None, *, @@ -96,6 +126,9 @@ def from_reference_config( section_contents.extend(module_members.get(item, [item])) elif isinstance(item, dict): item = cast("dict[str, Any]", item) + if item.get("kind") == "page": + section_contents.append(_configured_page(item)) + continue name = item.get("name", "") if not name: continue @@ -308,6 +341,7 @@ def sidebar(config: Config, spec: ReferenceSpec) -> Sidebar: The sidebar, with `reference` as its `id`. """ from .._apiref import APIReference, SpecObject + from .._apiref.spec import SpecPage from .._translations import translate directory = config.reference_output @@ -319,11 +353,15 @@ def sidebar(config: Config, spec: ReferenceSpec) -> Sidebar: for section in sections: heading = section.title or section.subtitle or "" - links = [ - {"text": entry.name, "href": _page_href(directory, entry.page_path)} - for entry in section.contents - if isinstance(entry, SpecObject) - ] + links: list[dict[str, str]] = [] + for entry in section.contents: + if isinstance(entry, SpecObject): + label, path = entry.name, entry.page_path + elif isinstance(entry, SpecPage): + label, path = entry.summary.name, entry.path + else: + continue + links.append({"text": label, "href": _page_href(directory, path)}) if links: contents.append({"section": heading, "contents": links}) diff --git a/great_docs/_versions/build.py b/great_docs/_versions/build.py index 137254cef..20b44da4f 100644 --- a/great_docs/_versions/build.py +++ b/great_docs/_versions/build.py @@ -903,12 +903,23 @@ def _rebuild_api_from_snapshot( Relative paths of API pages, with `.html` extensions. """ from great_docs._api_evolution.model import ApiSnapshot + from great_docs._apiref.spec import SpecPage snap = ApiSnapshot.load(snapshot_path) directory = _reference_dir(config) ref_dir = dest_dir / directory snapshot_symbols = set(snap.symbols.keys()) + reference_config = quarto_config.get("api-reference") or {} + grouped_paths = { + SpecPage.make(item).path + for section in reference_config.get("sections") or () + for item in section.get("contents") or () + if isinstance(item, dict) and item.get("kind") == "page" + } + # The historical snapshot cannot establish every object on a live grouped page. + for path in grouped_paths: + (ref_dir / f"{path}.qmd").unlink(missing_ok=True) # --- Prune existing pages not in the snapshot --- if ref_dir.exists(): @@ -986,7 +997,7 @@ def _rebuild_api_from_snapshot( # classes like {.doc-label ...}) vs. a plain placeholder. Rich pages are preserved and pruned; # plain/missing pages are regenerated from the snapshot. _has_rich_index = False - if index_path.exists(): + if index_path.exists() and not grouped_paths: _idx_content = index_path.read_text(encoding="utf-8") _has_rich_index = "{.doc-" in _idx_content @@ -1024,7 +1035,12 @@ def _rebuild_api_from_snapshot( generated.append(f"{directory}/index.html") - _prune_quarto_sidebar(quarto_config, directory, snapshot_symbols) + _prune_quarto_sidebar( + quarto_config, + directory, + snapshot_symbols, + excluded_paths={f"{directory}/{path}.qmd" for path in grouped_paths - snapshot_symbols}, + ) if config is not None: _write_snapshot_inventory(dest_dir, snap, config) @@ -1428,7 +1444,11 @@ def _prune_reference_index(index_qmd: Path, valid_symbols: set[str]) -> None: def _prune_quarto_sidebar( - quarto_config: dict[str, Any], section: str, valid_symbols: set[str] + quarto_config: dict[str, Any], + section: str, + valid_symbols: set[str], + *, + excluded_paths: set[str] | None = None, ) -> None: """ Remove sidebar entries for section pages absent from the version @@ -1445,11 +1465,14 @@ def _prune_quarto_sidebar( Directory of the section's pages, such as `reference`. valid_symbols Names of the symbols the version has. + excluded_paths + Additional page paths relative to the Quarto project to remove from navigation. Returns ------- : """ + excluded_paths = excluded_paths or set() for sidebar in quarto_config.get("website", {}).get("sidebar", []): contents = sidebar.get("contents", []) if not contents: @@ -1460,6 +1483,9 @@ def _has_section_ref(items: list) -> bool: if isinstance(c, str) and c.startswith(f"{section}/"): return True if isinstance(c, dict): + href = c.get("href") + if isinstance(href, str) and href in excluded_paths: + return True sub = c.get("contents", []) if sub and _has_section_ref(sub): return True @@ -1473,6 +1499,12 @@ def _prune_contents(items: list) -> tuple[list, bool]: new_items: list = [] changed = False for item in items: + href = item.get("href") if isinstance(item, dict) else item + if isinstance(href, str) and href in excluded_paths: + changed = True + if not isinstance(item, dict) or not item.get("contents"): + continue + item = {key: value for key, value in item.items() if key != "href"} if isinstance(item, str) and item.startswith(f"{section}/"): if "/" in item.replace(f"{section}/", "", 1): # Keep entries in subdirectories such as `
/cli/`. diff --git a/tests/test_great_docs.py b/tests/test_great_docs.py index 19276a556..b5b6ec7f0 100644 --- a/tests/test_great_docs.py +++ b/tests/test_great_docs.py @@ -16444,8 +16444,8 @@ def test_render_api_page_post_init(): assert ap.path == "reference/my_func.qmd" -def test_render_api_page_has_one_object(): - """Recognise a single-object API page""" +def test_render_api_page_uses_standalone_object_title() -> None: + """Give a standalone object one heading through the page title""" func_obj = gf.Function(name="my_func", lineno=1) doc_obj = griffe_to_doc(func_obj) @@ -16453,7 +16453,9 @@ def test_render_api_page_has_one_object(): ap = APIPageRenderer(node=page, level=1) - assert ap._has_one_object is True + (renderer,) = ap.object_renderers + assert ap.render_metadata().table["title"] == str(renderer.title_content) + assert renderer.render_title() is None def test_render_api_page_metadata(): @@ -16730,9 +16732,6 @@ def test_render_api_page_full_lifecycle(): assert ap.page is page assert ap.path == "reference/my_func.qmd" - # Test _has_one_object - assert ap._has_one_object is True - # Test render_objs objs = ap.object_renderers assert len(objs) == 1 diff --git a/tests/test_reference_group_pages.py b/tests/test_reference_group_pages.py new file mode 100644 index 000000000..7bd0f80b8 --- /dev/null +++ b/tests/test_reference_group_pages.py @@ -0,0 +1,195 @@ +"""Named API reference pages and the objects they publish""" + +from __future__ import annotations + +import io +from pathlib import Path + +import pytest + +from great_docs import GreatDocs +from great_docs._api_evolution.model import ApiSnapshot, SymbolInfo +from great_docs._apiref.spec import SpecPage, SpecSection, unique_page_paths +from great_docs._build import reference +from great_docs._build.log import BuildLog +from great_docs._interlinks.sphinx_inventory import decode +from great_docs._reference import sections +from great_docs._versions.build import _rebuild_api_from_snapshot +from great_docs._versions.model import VersionEntry +from tests.support import StubRemote, make_run, prepare_build_directory, write_config + + +def test_group_page_build(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Publish grouped objects and retain working index, sidebar and member links""" + package = tmp_path / "grouped_api" + package.mkdir() + (package / "__init__.py").write_text( + '''\ +class Widget: + """Example widget.""" + + def run(self): + """Run the widget.""" + +def reset(): + """Reset the widget.""" + +def inspect(): + """Inspect the widget.""" +''', + encoding="utf-8", + ) + (tmp_path / "pyproject.toml").write_text('[project]\nname = "grouped_api"\nversion = "0.1"\n') + write_config( + tmp_path, + { + "dynamic": False, + "reference": { + "output": "api/python", + "sections": [ + { + "title": "Widgets", + "contents": [ + {"name": "Widget", "members": ["run"], "members_on_same_page": False}, + { + "kind": "page", + "path": "tools/actions", + "summary": {"name": "Widget actions", "desc": "Run or reset."}, + "contents": ["Widget.run", {"name": "reset", "members": False}], + }, + {"kind": "page", "path": "inspection", "contents": ["inspect"]}, + ], + }, + ], + }, + }, + ) + monkeypatch.chdir(tmp_path) + monkeypatch.syspath_prepend(str(tmp_path)) + docs = GreatDocs(project_path=str(tmp_path)) + docs._remote = StubRemote() + run = make_run(docs) + prepare_build_directory(docs, run) + assert run.api_spec is not None + sidebar = sections.sidebar(docs._config, run.api_spec) + assert sidebar.contents[1]["contents"] == [ + {"text": "Widget", "href": "api/python/Widget.qmd"}, + {"text": "Widget actions", "href": "api/python/tools/actions.qmd"}, + {"text": "inspection", "href": "api/python/inspection.qmd"}, + ] + + monkeypatch.chdir(docs.layout.build_dir) + outcome, ref = reference.api(run, docs._config, docs.layout, BuildLog(stream=io.StringIO())) + assert outcome == "API reference generated" + assert ref is not None + try: + directory = docs.layout.build_dir / "api/python" + assert {page.path for page in ref.manifest.pages} == { + "Widget", + "tools/actions", + "inspection", + } + actions = (directory / "tools/actions.qmd").read_text(encoding="utf-8") + assert "title: Widget actions" in actions + assert "Run the widget." in actions + assert "Reset the widget." in actions + assert "#grouped_api.Widget.run" in actions + assert "#grouped_api.reset" in actions + inspection = (directory / "inspection.qmd").read_text(encoding="utf-8") + assert "title: inspection" in inspection + assert "#grouped_api.inspect" in inspection + assert "[Widget actions](tools/actions.qmd)" in (directory / "index.qmd").read_text() + assert "tools/actions.qmd#grouped_api.Widget.run" in (directory / "Widget.qmd").read_text() + + inventory = decode((docs.layout.build_dir / "objects.inv").read_bytes()) + assert {entry.name: entry.uri for entry in inventory.entries} == { + "grouped_api.Widget": "api/python/Widget.html#grouped_api.Widget", + "grouped_api.Widget.run": "api/python/tools/actions.html#grouped_api.Widget.run", + "grouped_api.reset": "api/python/tools/actions.html#grouped_api.reset", + "grouped_api.inspect": "api/python/inspection.html#grouped_api.inspect", + } + finally: + ref.close() + + +@pytest.mark.parametrize("path", ["../actions", "/actions", "", "actions.qmd", "tools//actions"]) +def test_group_page_validates_path(path: str) -> None: + """Require a safe path within the reference directory""" + with pytest.raises(ValueError, match="must be relative to the reference directory"): + SpecPage.make({"kind": "page", "path": path, "contents": ["run"]}) + + +@pytest.mark.parametrize("contents", [[], "run", [{"kind": "page", "path": "nested"}]]) +def test_group_page_requires_named_objects(contents: object) -> None: + """Reject empty groups and groups with non-object entries""" + with pytest.raises(ValueError, match="Reference page|Each entry"): + SpecPage.make({"kind": "page", "path": "actions", "contents": contents}) + + +@pytest.mark.parametrize( + "other", ["actions", "ACTIONS", {"kind": "page", "path": "actions", "contents": ["reset"]}] +) +def test_group_page_requires_unique_path(other: object) -> None: + """Report a name collision before writing either reference page""" + group = SpecPage.make({"kind": "page", "path": "actions", "contents": ["run"]}) + for contents in ([other, group], [group, other]): + with pytest.raises(ValueError, match="Reference page `actions` conflicts"): + unique_page_paths([SpecSection(title="API", contents=contents)]) + + +def test_group_page_cannot_replace_index() -> None: + """Reserve the reference index when validating a grouped page's path""" + group = SpecPage.make({"kind": "page", "path": "index", "contents": ["run"]}) + with pytest.raises(ValueError, match="Reference page `index` conflicts"): + unique_page_paths([SpecSection(title="API", contents=[group])]) + + +def test_historical_reference_replaces_live_group_pages(tmp_path: Path) -> None: + """Rebuild a reference from historical symbols without publishing live groups""" + destination = tmp_path / "site" + ref_dir = destination / "reference" + (ref_dir / "tools").mkdir(parents=True) + (ref_dir / "tools/actions.qmd").write_text("Live group", encoding="utf-8") + (ref_dir / "run.qmd").write_text("# Newer symbols {.doc-heading}", encoding="utf-8") + (ref_dir / "index.qmd").write_text( + "[Actions](tools/actions.qmd){.doc-label}\n", encoding="utf-8" + ) + snapshot = tmp_path / "snapshot.json" + ApiSnapshot( + version="1.0", + package_name="widgets", + symbols={"run": SymbolInfo(name="run", kind="function")}, + ).save(snapshot) + quarto_config = { + "api-reference": { + "sections": [ + { + "title": "Widgets", + "contents": [ + {"kind": "page", "path": "tools/actions", "contents": ["run", "reset"]}, + {"kind": "page", "path": "run", "contents": ["preview"]}, + ], + } + ] + }, + "website": { + "sidebar": [ + { + "contents": [ + {"text": "API Index", "href": "reference/index.qmd"}, + {"text": "Actions", "href": "reference/tools/actions.qmd"}, + ] + }, + ] + }, + } + pages = _rebuild_api_from_snapshot( + destination, snapshot, VersionEntry(tag="1.0", label="1.0"), quarto_config=quarto_config + ) + assert set(pages) == {"reference/index.html", "reference/run.html"} + assert not (ref_dir / "tools/actions.qmd").exists() + assert "Newer symbols" not in (ref_dir / "run.qmd").read_text() + assert "[run](run.qmd)" in (ref_dir / "index.qmd").read_text() + assert quarto_config["website"]["sidebar"][0]["contents"] == [ + {"text": "API Index", "href": "reference/index.qmd"} + ]