diff --git a/docs/user_guide/05-configuration.qmd b/docs/user_guide/05-configuration.qmd index d398beb6..e45ac61e 100644 --- a/docs/user_guide/05-configuration.qmd +++ b/docs/user_guide/05-configuration.qmd @@ -1191,6 +1191,29 @@ reference: If no `reference` config is provided, Great Docs auto-generates sections from discovered exports. +### Entry Options + +Set `reference.include_empty` to `true` to document members without docstrings. It defaults +to `false`. An entry can set its own `include_empty` value. An explicit `members` list includes +the named members regardless of their docstrings. + +Use `signature_name: short` on a callable entry to show only its final name in the signature. +Set `dynamic: false` on an entry to read its definition using static analysis. Entries without +their own `dynamic` value follow the site setting. + +```{.yaml filename="docs/great-docs.yml"} +reference: + include_empty: true + sections: + - title: Data Tools + contents: + - name: tools.Loader + include_empty: false + - name: tools.read_file + signature_name: short + dynamic: false +``` + ### Reference Sidebar Set `reference.sidebar` to `false` to build the API reference without an automatic sidebar. diff --git a/great_docs/_apiref/_rendering/objects.py b/great_docs/_apiref/_rendering/objects.py index b560b3ac..9ad54786 100644 --- a/great_docs/_apiref/_rendering/objects.py +++ b/great_docs/_apiref/_rendering/objects.py @@ -125,7 +125,7 @@ class ObjectRenderer(BaseRenderer): """Format for the display name""" signature_name_format: DisplayNameFormat = "doc" - """Format for the signature name""" + """Default format for the signature name""" def __post_init__(self) -> None: """Expose the documentation node as `doc` and its prepared Python object as `obj`""" @@ -211,8 +211,9 @@ def display_name(self) -> str: @cached_property def signature_name(self) -> str: - """The name shown in the signature, formatted by `signature_name_format`""" - return format_name(self.doc, self.signature_name_format) + """The name shown in the signature in the entry's or renderer's format""" + name_format = self.doc.signature_name or self.signature_name_format + return format_name(self.doc, name_format) def render_description(self) -> BlockContent: """ diff --git a/great_docs/_apiref/_settings.py b/great_docs/_apiref/_settings.py index 3df8d144..5e352945 100644 --- a/great_docs/_apiref/_settings.py +++ b/great_docs/_apiref/_settings.py @@ -73,6 +73,10 @@ class Settings: """How callable signatures are written and wrapped""" dynamic: bool | None = None """Whether to load objects by importing the package, or `None` for the default""" + force_static: bool = False + """Whether an explicitly static build uses source analysis for every entry""" + include_empty: bool = False + """Whether to select undocumented members by default""" members_on_same_page: bool | None = None """Same-page override for top-level entries, or `None` to use the member limit""" max_members_on_same_page: int = 5 @@ -132,6 +136,7 @@ def make( The project's documentation configuration. dynamic The introspection mode for this attempt, or `None` to use the site setting. + An explicit `False` selects static analysis for all entries. source_links The destinations for source links, or `None` to disable them. @@ -147,6 +152,8 @@ def make( wrap=config.callable_signatures_wrap, ), dynamic=config.dynamic if dynamic is None else dynamic, + force_static=dynamic is False, + include_empty=config.reference_include_empty, members_on_same_page=config.members_on_same_page, max_members_on_same_page=config.max_members_on_same_page, dir=config.reference_output, diff --git a/great_docs/_apiref/api_reference.py b/great_docs/_apiref/api_reference.py index c77173a7..4b462c07 100644 --- a/great_docs/_apiref/api_reference.py +++ b/great_docs/_apiref/api_reference.py @@ -88,6 +88,7 @@ def __init__( lets the resolver discover the sections. dynamic The introspection mode for this attempt, or `None` to use the site setting. + An explicit `False` selects static analysis for all entries. source_links The source-link destinations, or `None` to disable source links. extension_source diff --git a/great_docs/_apiref/content.py b/great_docs/_apiref/content.py index c167257a..9b29db93 100644 --- a/great_docs/_apiref/content.py +++ b/great_docs/_apiref/content.py @@ -17,6 +17,8 @@ if TYPE_CHECKING: import griffe as gf + from .typing import DisplayNameFormat + @dataclass class Doc(Walkable): @@ -28,8 +30,8 @@ class Doc(Walkable): """The name the object is documented under, which the `doc` name format shows""" anchor: str = "" """The object's anchor on its page""" - signature_name: str = "relative" - """How a callable's name is written in its signature""" + signature_name: DisplayNameFormat | None = None + """The authored signature name format, or `None` for the renderer's default""" @classmethod def from_griffe( @@ -38,7 +40,7 @@ def from_griffe( obj: gf.Object | gf.Alias, members: list[Any] | None = None, anchor: str | None = None, - signature_name: str = "relative", + signature_name: DisplayNameFormat | None = None, fields: list[DocAttribute] | None = None, ) -> DocFunction | DocAttribute | DocTypeAlias | DocClass | DocModule: """ @@ -60,7 +62,7 @@ def from_griffe( anchor The anchor, or `None` to use the object's qualified path. signature_name - How a callable's name is written in its signature. + The authored signature name format, or `None` for the renderer's default. fields The attributes a dataclass node documents as constructor parameters, or `None` for none. diff --git a/great_docs/_apiref/resolve.py b/great_docs/_apiref/resolve.py index a4e11671..6989194d 100644 --- a/great_docs/_apiref/resolve.py +++ b/great_docs/_apiref/resolve.py @@ -672,7 +672,7 @@ def _locate(self, el: SpecObject) -> tuple[str, SpecObject, bool]: el = el.with_defaults(self.options) dynamic = el.dynamic if el.dynamic is not None else self.dynamic - return path, el, dynamic + return path, el, dynamic and not self.settings.force_static def _resolve_documented_object( self, el: SpecObject, static_node: gf.Object | gf.Alias | None = None @@ -914,7 +914,8 @@ def _fetch_members( # The remaining filters read the prepared documentation. Enum members are always # shown: their names and values document them even without a docstring. - if not el.include_empty and not is_enum(obj): + include_empty = el.specified_options().get("include_empty", self.settings.include_empty) + if not include_empty and not is_enum(obj): candidates = {k: v for k, v in candidates.items() if v.docstring is not None} if not el.include_attributes: diff --git a/great_docs/_apiref/spec.py b/great_docs/_apiref/spec.py index d44d752d..f5a18e5c 100644 --- a/great_docs/_apiref/spec.py +++ b/great_docs/_apiref/spec.py @@ -15,11 +15,14 @@ from dataclasses import dataclass, field from dataclasses import fields as dc_fields from functools import partial -from typing import Any, Final, Self, cast +from typing import TYPE_CHECKING, Any, Final, Self, cast from ._walkable import MISSING, MissingType, Walkable from .introspect import validate_dynamic +if TYPE_CHECKING: + from .typing import DisplayNameFormat + @dataclass(frozen=True) class ReferenceSpec: @@ -59,7 +62,7 @@ def _validate_members(members: list[str] | None, owner: object) -> None: class SpecOptions(Walkable): """Documentation options that apply to a `SpecObject` element and, optionally, its members""" - signature_name: str = "relative" + signature_name: DisplayNameFormat | None = None members: list[str] | None = None include_private: bool = False include_imports: bool = False diff --git a/great_docs/_reference/block.py b/great_docs/_reference/block.py index 9af3c420..5b31be53 100644 --- a/great_docs/_reference/block.py +++ b/great_docs/_reference/block.py @@ -106,6 +106,8 @@ def configure(config: Config, quarto_config: dict[str, Any], spec: ReferenceSpec api_ref_config["desc"] = config.reference_desc if config.reference_show_bases: api_ref_config["show_bases"] = True + if config.reference_include_empty: + api_ref_config["include_empty"] = True if config.members_on_same_page is not None: api_ref_config["members_on_same_page"] = config.members_on_same_page api_ref_config["max_members_on_same_page"] = config.max_members_on_same_page diff --git a/great_docs/_reference/sections.py b/great_docs/_reference/sections.py index 1e47ffd9..26e2491a 100644 --- a/great_docs/_reference/sections.py +++ b/great_docs/_reference/sections.py @@ -19,7 +19,7 @@ def _configured_entry(item: dict[str, Any]) -> str | dict[str, Any]: """ - Preserve member selection and page placement for a reference entry + Translate an authored entry to the reference options it supplies """ if "inline_methods" in item: raise ValueError( @@ -32,6 +32,10 @@ def _configured_entry(item: dict[str, Any]) -> str | dict[str, Any]: "to give each member a page, or use `members` to select which members to document." ) name = item["name"] + options = ("members_on_same_page", "include_empty", "dynamic", "signature_name") + if unsupported := item.keys() - {"name", "members", "include_inherited", *options}: + keys = ", ".join(sorted(map(str, unsupported))) + raise ValueError(f"Unsupported options for reference entry `{name}`: {keys}.") members = item.get("members", True) entry: dict[str, Any] = {"name": name} if members is False: @@ -40,10 +44,10 @@ def _configured_entry(item: dict[str, Any]) -> str | dict[str, Any]: entry["members"] = members if members is not False and item.get("include_inherited") is not None: entry["include_inherited"] = item["include_inherited"] - if "members_on_same_page" in item: - if not isinstance(item["members_on_same_page"], bool): - raise ValueError("Per-entry `members_on_same_page` must be true or false.") - entry["members_on_same_page"] = item["members_on_same_page"] + for key in ("members_on_same_page", "include_empty"): + if key in item and not isinstance(item[key], bool): + raise ValueError(f"Per-entry `{key}` must be true or false.") + entry.update({key: item[key] for key in options if key in item}) return entry if len(entry) > 1 else name diff --git a/great_docs/assets/great-docs.default.yml b/great_docs/assets/great-docs.default.yml index 9b2491bc..36612e98 100644 --- a/great_docs/assets/great-docs.default.yml +++ b/great_docs/assets/great-docs.default.yml @@ -456,6 +456,7 @@ csl: null # output: reference # URL path of the API, CLI and MCP references. Use a # # relative path such as `api` or `pkg/python`. # show_bases: false # Show each class's direct base classes +# include_empty: false # Include members without docstrings # sections: # The sections, written as in the list form above # - title: "Core Classes" # contents: diff --git a/great_docs/config.py b/great_docs/config.py index 4c6882c1..4ff47bf7 100644 --- a/great_docs/config.py +++ b/great_docs/config.py @@ -179,7 +179,7 @@ def _load_config(self) -> ConfigDict: reference = config["reference"] if isinstance(reference, dict): options = cast("ConfigDict", reference) - for key in ("show_bases", "sidebar"): + for key in ("show_bases", "sidebar", "include_empty"): if key in options and not isinstance(options[key], bool): raise ConfigError(f"{self.config_path}: reference.{key} must be true or false.") self._validate_reference_output(options.get("output"), self.config_path) @@ -1579,6 +1579,15 @@ def reference_show_bases(self) -> bool: isinstance(reference, dict) and cast("ConfigDict", reference).get("show_bases") is True ) + @property + def reference_include_empty(self) -> bool: + """Whether the reference includes members without docstrings by default""" + reference = self["reference"] + return ( + isinstance(reference, dict) + and cast("ConfigDict", reference).get("include_empty") is True + ) + @property def members_on_same_page(self) -> bool | None: """ diff --git a/tests/test_build_reference.py b/tests/test_build_reference.py index f596597a..21f9dc9a 100644 --- a/tests/test_build_reference.py +++ b/tests/test_build_reference.py @@ -172,6 +172,98 @@ def test_reference_index_keeps_description_only_sections( ) +@pytest.mark.parametrize("site_include_empty", [None, True]) +def test_authored_entries_control_member_selection_and_signatures( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, site_include_empty: bool | None +) -> None: + """ + Apply entry options when building the reference pages and inventory + """ + name = "reference_entry_options" + monkeypatch.delitem(sys.modules, name, raising=False) + monkeypatch.delitem(sys.modules, f"{name}.tools", raising=False) + write_pyproject(tmp_path, name) + package = tmp_path / name + package.mkdir() + (package / "__init__.py").write_text("", encoding="utf-8") + (package / "tools.py").write_text( + dedent(""" + class Inherit: + "A class that uses the site's member selection" + + def silent(self): + pass + + class Include(Inherit): + "A class that opts in" + + def silent(self): + pass + + class Exclude(Inherit): + "A class that opts out" + + def silent(self): + pass + + def static_example(source): + "The source signature" + + def dynamic_example(live): + "The runtime signature" + + globals()["static_example"] = dynamic_example + """), + encoding="utf-8", + ) + reference_config: dict[str, Any] = { + "sections": [ + { + "title": "API", + "contents": [ + "tools.Inherit", + {"name": "tools.Include", "include_empty": True}, + {"name": "tools.Exclude", "include_empty": False}, + {"name": "tools.static_example", "signature_name": "short", "dynamic": False}, + "tools.dynamic_example", + ], + } + ] + } + if site_include_empty is not None: + reference_config["include_empty"] = site_include_empty + write_config(tmp_path, {"reference": reference_config}) + docs = GreatDocs(project_path=str(tmp_path)) + docs._remote = StubRemote() + monkeypatch.chdir(tmp_path) + run = make_run(docs) + prepare_build_directory(docs, run) + 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 + reference_dir = docs.layout.build_dir / "reference" + static_page = (reference_dir / "tools.static_example.qmd").read_text(encoding="utf-8") + dynamic_page = (reference_dir / "tools.dynamic_example.qmd").read_text(encoding="utf-8") + assert "static_example(source)" in static_page + assert "tools.static_example(source)" not in static_page + assert "tools.dynamic_example(live)" in dynamic_page + + entries = decode((docs.layout.build_dir / "objects.inv").read_bytes()).entries + names = {entry.name for entry in entries} + assert f"{name}.tools.Include.silent" in names + assert f"{name}.tools.Exclude.silent" not in names + assert (f"{name}.tools.Inherit.silent" in names) is bool(site_include_empty) + + +def test_reference_entry_reports_unknown_keys() -> None: + """Identify unsupported options and the entry that supplies them""" + configured = [{"title": "API", "contents": [{"name": "Widget", "signature_names": "short"}]}] + with pytest.raises(ValueError, match="Widget.*signature_names"): + reference_sections.from_reference_config(configured) + + def _source_linked_project(root: Path, name: str, branch: str) -> GreatDocs: """ Create a project whose API reference links to a branch of its GitHub repository