diff --git a/docs/user_guide/05-configuration.qmd b/docs/user_guide/05-configuration.qmd index e45ac61e..11722058 100644 --- a/docs/user_guide/05-configuration.qmd +++ b/docs/user_guide/05-configuration.qmd @@ -1191,6 +1191,32 @@ reference: If no `reference` config is provided, Great Docs auto-generates sections from discovered exports. +### Package Scopes + +By default, Great Docs looks up each name relative to the documented package. Set +`reference.package`, a section's `package`, or a named entry's `package` to look up names +in a different package, module or class. Install other distributions in the build +environment before documenting their objects. + +An entry inherits its section's scope, and a section inherits the reference's scope. +Use `package: null` at any of these levels to write fully qualified names. Great Docs uses +each object's written name for its page URL. + +```{.yaml filename="docs/great-docs.yml"} +reference: + package: example.tools + sections: + - title: Tools + contents: + - read_file + - name: open_dataset + package: another_package.io + - title: Fit Methods + package: example.models.Estimator + contents: + - fit +``` + ### Entry Options Set `reference.include_empty` to `true` to document members without docstrings. It defaults diff --git a/great_docs/_apiref/introspect.py b/great_docs/_apiref/introspect.py index f7dcb2d3..b16a567d 100644 --- a/great_docs/_apiref/introspect.py +++ b/great_docs/_apiref/introspect.py @@ -215,23 +215,31 @@ def get_object( def _dynamic_path(path: str, loader: gf.GriffeLoader) -> str: """ - Split a dotted path at the longest module that the loader has loaded + Find the module to import before resolving a reference name Parameters ---------- - path : - A dotted path, or a `module:object` path, which is returned unchanged. - loader : + path + A dotted path or an explicit `module:object` path. A class scope can also + precede the separator, as in `package.models.Class:method`. + loader The loader whose modules mark where the module part ends. Returns ------- : - The path in `module:object` form, the module path alone when the whole path - names a module, or the path unchanged when no loaded module begins it. + The path in `module:object` form, a module path, or the original path + when the loader has no matching module. """ - if ":" in path: - return path + scope, separator, name = path.partition(":") + if separator: + try: + class_scope = loader.modules_collection[scope].is_class + except (KeyError, gf.AliasResolutionError, gf.CyclicAliasError): + return path + if not class_scope: + return path + path = f"{scope}.{name}" parts = path.split(".") for length in range(len(parts), 0, -1): module_path = ".".join(parts[:length]) diff --git a/great_docs/_reference/discovery.py b/great_docs/_reference/discovery.py index a01d2f41..053942e7 100644 --- a/great_docs/_reference/discovery.py +++ b/great_docs/_reference/discovery.py @@ -878,7 +878,7 @@ def _found_statically(path: str) -> bool: def categorise_references( - package: gf.Module, + package: gf.Object | gf.Alias, reference: Iterable[object], *, runtime_function: Callable[[str], gf.Object | gf.Alias | None] | None = None, @@ -928,12 +928,15 @@ def categorise_references( categories = empty_categories() missing: list[str] = [] prefix = f"{package.path}." - for name in sorted({name.removeprefix(prefix).split(".", 1)[0] for name in listed}): - if name not in package.members: + members = package.all_members if package.kind is gf.Kind.CLASS else package.members + for name in sorted( + {name.replace(":", ".").removeprefix(prefix).split(".", 1)[0] for name in listed} + ): + if name not in members: missing.append(name) continue try: - obj = _export_binding(package.members[name], runtime_function) + obj = _export_binding(members[name], runtime_function) kind = obj.kind except _ALIAS_ERRORS: categories["other"].append(name) @@ -951,7 +954,7 @@ def categorise_references( _add_flat(name, obj, categories) if missing: - package_version = _installed_version(package.path) + package_version = _installed_version(package.path.partition(".")[0]) if package_version is None: # Without an installed distribution the names may be about to exist, as when a # package documents itself during development. diff --git a/great_docs/_reference/exports.py b/great_docs/_reference/exports.py index 26df1efd..95afb8ae 100644 --- a/great_docs/_reference/exports.py +++ b/great_docs/_reference/exports.py @@ -5,6 +5,7 @@ from __future__ import annotations import sys +from collections import defaultdict from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, cast @@ -17,6 +18,8 @@ from . import sections as reference_sections if TYPE_CHECKING: + from collections.abc import Sequence + from .._project.layout import Layout from .discovery import Categories @@ -249,22 +252,12 @@ def sections(self, name: str) -> list[dict[str, Any]] | None: if reference_config: print("Using explicit reference configuration from great-docs.yml") try: - package = self.package(name) - except USER_CODE_ERRORS: - categories = discovery.empty_categories() - else: - try: - check = probe.RendererCheck(package.path, report=print) - categories = discovery.categorise_references( - package, - reference_config, - runtime_function=check.exported_function if self.config.dynamic else None, - ) - except BuildError as error: - print(f"ERROR: {error}", file=sys.stderr) - raise - configured = reference_sections.from_explicit_config(reference_config, categories) + configured = self._configured_sections(name, reference_config) + except BuildError as error: + print(f"ERROR: {error}", file=sys.stderr) + raise if configured: + print(f"Generated {len(configured)} section(s) from reference config") return configured exports = [ @@ -274,3 +267,92 @@ def sections(self, name: str) -> list[dict[str, Any]] | None: return None print(f"Found {len(exports)} exported names to document") return reference_sections.from_categories(self.config, self.categorise(name, exports)) + + def _configured_sections( + self, name: str, reference_config: Sequence[object] + ) -> list[dict[str, Any]]: + """ + Validate entries in their configured scopes and expand listed modules + + Group entries from each section by their lookup scope. Keep explicit + entry scopes on named entries and use the section scope to expand its + bare module names. + """ + site_scope = self.config.reference_package(name) + sections: list[dict[str, Any]] = [] + for raw in reference_config: + if not isinstance(raw, dict): + continue + section = cast("dict[str, Any]", raw).copy() + scope = cast("str | None", section.get("package", site_scope)) + if scope != name: + section["package"] = scope + + by_scope: defaultdict[str | None, list[object]] = defaultdict(list) + for item in cast("list[object]", section.get("contents") or []): + entry_scope = scope + if isinstance(item, dict): + item = cast("dict[str, str | None]", item) + entry_scope = item.get("package", scope) + by_scope[entry_scope].append(item) + + categories = discovery.empty_categories() + for entry_scope, contents in by_scope.items(): + found = self._reference_categories(name, entry_scope, contents) + if entry_scope == scope: + categories = found + sections.extend(reference_sections.from_explicit_config([section], categories) or ()) + return sections + + def _reference_categories( + self, name: str, scope: str | None, contents: list[object] + ) -> Categories: + """ + Check the listed objects against their package, module or class + + Entries with no scope carry their own package prefix. A fully qualified + path already names the page's subject, so only scoped module names + contribute names for expansion. + """ + if scope is not None: + return self._categorise_in_scope(name, scope, contents) + + by_parent: defaultdict[str, list[object]] = defaultdict(list) + for item in contents: + entry = cast("dict[str, object]", item).get("name") if isinstance(item, dict) else item + if not isinstance(entry, str) or not entry: + continue + parent, separator, member = entry.replace(":", ".").rpartition(".") + if separator: + by_parent[parent].append(member) + else: + _ = self._categorise_in_scope(name, entry, []) + for parent, members in by_parent.items(): + _ = self._categorise_in_scope(name, parent, members) + return discovery.empty_categories() + + def _categorise_in_scope(self, name: str, scope: str, contents: list[object]) -> Categories: + """ + Check names relative to a particular scope + + The documented package may be unavailable when configuration is + generated ahead of installation. Explicitly named scopes must exist. + """ + try: + root = scope if scope == name else scope.partition(".")[0] + package: gf.Object | gf.Alias = self.package(root) + if root != scope: + package = package.modules_collection[scope] + except (KeyError, *USER_CODE_ERRORS) as error: + if scope == name: + return discovery.empty_categories() + raise BuildError( + f"Could not load configured reference package `{scope}`: {error}" + ) from error + + check = probe.RendererCheck(scope, report=print) + return discovery.categorise_references( + package, + [{"contents": contents}], + runtime_function=check.exported_function if self.config.dynamic else None, + ) diff --git a/great_docs/_reference/sections.py b/great_docs/_reference/sections.py index 26e2491a..5e63ae01 100644 --- a/great_docs/_reference/sections.py +++ b/great_docs/_reference/sections.py @@ -32,7 +32,7 @@ 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") + options = ("members_on_same_page", "include_empty", "dynamic", "signature_name", "package") 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}.") @@ -111,6 +111,11 @@ def from_reference_config( if subtitle is not None else {"title": title or "Untitled"} ), + **( + {"package": section_config["package"]} + if "package" in section_config + else {} + ), "desc": desc, "contents": section_contents, } @@ -279,10 +284,7 @@ def from_explicit_config( mod_prefix = qualified.split(".")[0] module_members.setdefault(mod_prefix, []).append(qualified) - sections = from_reference_config(reference_config, module_members=module_members) - if sections: - print(f"Generated {len(sections)} section(s) from reference config") - return sections + return from_reference_config(reference_config, module_members=module_members) def sidebar(config: Config, spec: ReferenceSpec) -> Sidebar: diff --git a/great_docs/assets/great-docs.default.yml b/great_docs/assets/great-docs.default.yml index 36612e98..fe2c200c 100644 --- a/great_docs/assets/great-docs.default.yml +++ b/great_docs/assets/great-docs.default.yml @@ -457,6 +457,7 @@ csl: null # # 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 +# package: example.core # Default scope for the names in the sections # 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 4ff47bf7..36de2a8e 100644 --- a/great_docs/config.py +++ b/great_docs/config.py @@ -176,7 +176,8 @@ def _load_config(self) -> ConfigDict: f"{self.config_path}: max_members_on_same_page: {maximum!r} " "must be a non-negative integer." ) - reference = config["reference"] + reference: object = config["reference"] + self._validate_reference_packages(reference) if isinstance(reference, dict): options = cast("ConfigDict", reference) for key in ("show_bases", "sidebar", "include_empty"): @@ -207,6 +208,41 @@ def _load_config(self) -> ConfigDict: ) return config + def _validate_reference_packages(self, reference: object) -> None: + """Require dotted Python names or null for reference package scopes""" + + def validate(options: ConfigDict, key: str) -> None: + if (package := options.get("package")) is None: + return + if not isinstance(package, str) or not all( + part.isidentifier() for part in package.split(".") + ): + raise ConfigError( + f"{self.config_path}: {key}.package must be a dotted Python name or null." + ) + + sections = reference + if isinstance(reference, dict): + options = cast("ConfigDict", reference) + validate(options, "reference") + sections = options.get("sections") + if not isinstance(sections, list): + return + + for index, section in enumerate(cast("list[object]", sections), 1): + if not isinstance(section, dict): + continue + section_options = cast("ConfigDict", section) + label = f"reference section {index}" + validate(section_options, label) + contents = section_options.get("contents") + if not isinstance(contents, list): + continue + for entry in cast("list[object]", contents): + if isinstance(entry, dict): + entry_options = cast("ConfigDict", entry) + validate(entry_options, f"{label}, entry {entry_options.get('name')!r}") + def _validate_repository(self, config: ConfigDict) -> None: """ Validate repository settings while allowing URLs on unknown hosts @@ -1515,6 +1551,18 @@ def reference(self) -> list[ConfigDict]: return cast("list[ConfigDict]", sections) return [] + def reference_package(self, default: str) -> str | None: + """ + Look up the package scope for authored reference entries + + Use `default` when the setting is absent. An explicit `None` means that + entry names are fully qualified. + """ + reference = self["reference"] + if isinstance(reference, dict): + return cast("ConfigDict", reference).get("package", default) + return default + @property def reference_output(self) -> str: """ diff --git a/tests/support.py b/tests/support.py index d15d7b58..d4693ad2 100644 --- a/tests/support.py +++ b/tests/support.py @@ -145,6 +145,8 @@ def mock_config(**values: object) -> NonCallableMagicMock: ) if "reference_output" not in values: config.reference_output = "reference" + if "reference_package" not in values: + config.reference_package.side_effect = lambda default: default return config diff --git a/tests/test_reference_package_scopes.py b/tests/test_reference_package_scopes.py new file mode 100644 index 00000000..5c298b94 --- /dev/null +++ b/tests/test_reference_package_scopes.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import io +import sys +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from great_docs import GreatDocs +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 documented +from great_docs.config import ConfigError +from tests.support import ( + StubRemote, + make_exports, + make_project, + make_run, + prepare_build_directory, + write_config, + write_pyproject, +) + + +@pytest.fixture +def scoped_project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]: + """Provide a package with a nested class and a separately installed distribution""" + write_pyproject(tmp_path, "scope-demo") + package = tmp_path / "scope_demo" + package.mkdir() + (package / "__init__.py").write_text("", encoding="utf-8") + (package / "models.py").write_text( + 'def one():\n "Use the reference scope"\n\n' + 'class Example:\n "A scope for methods"\n\n' + ' def method(self):\n "Static method summary"\n\n' + ' method.__doc__ = "Runtime " + "method summary"\n', + encoding="utf-8", + ) + tools = package / "tools" + tools.mkdir() + (tools / "__init__.py").write_text("", encoding="utf-8") + (tools / "helpers.py").write_text( + '__all__ = ["fetch"]\n\ndef fetch():\n "A public tool"\n', + encoding="utf-8", + ) + other_site_packages = tmp_path / "installed" + other_package = other_site_packages / "scope_extra" + other_package.mkdir(parents=True) + (other_package / "__init__.py").write_text( + 'def two():\n "Use the entry scope"\n\ndef plugin():\n "Use an absolute path"\n', + encoding="utf-8", + ) + metadata = other_site_packages / "scope_extra-1.0.dist-info" + metadata.mkdir() + (metadata / "METADATA").write_text("Name: scope-extra\nVersion: 1.0\n", encoding="utf-8") + + monkeypatch.syspath_prepend(str(other_site_packages)) + monkeypatch.syspath_prepend(str(tmp_path)) + monkeypatch.chdir(tmp_path) + yield tmp_path + for name in list(sys.modules): + if name.split(".", 1)[0] in {"scope_demo", "scope_extra"}: + sys.modules.pop(name, None) + + +def test_package_scopes_preserve_written_reference_paths( + scoped_project: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Resolve reference, section and entry names in their configured scopes""" + write_config( + scoped_project, + { + "module": "scope_demo", + "reference": { + "package": "scope_demo.models", + "sections": [ + { + "title": "API", + "contents": [ + "one", + {"name": "two", "package": "scope_extra"}, + {"name": "scope_extra.plugin", "package": None}, + ], + }, + { + "title": "Methods", + "package": "scope_demo.models.Example", + "contents": ["method"], + }, + { + "title": "Tools", + "package": "scope_demo.tools", + "contents": ["helpers"], + }, + ], + }, + }, + ) + docs = GreatDocs(project_path=str(scoped_project)) + docs._remote = StubRemote() + expected = { + "scope_demo.models.one": "one", + "scope_extra.two": "two", + "scope_extra.plugin": "scope_extra.plugin", + "scope_demo.models.Example.method": "method", + "scope_demo.tools.helpers.fetch": "helpers.fetch", + } + + run = make_run(docs) + try: + prepare_build_directory(docs, run) + sidebar_paths = { + link["href"] + for group in run.contributions[0].sidebars[0].contents[1:] + for link in group["contents"] + } + 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 + assert not ref.static_fallbacks + assert ref.package == "scope_demo" + assert sidebar_paths == {f"reference/{page}.qmd" for page in expected.values()} + for page in expected.values(): + assert (docs.layout.build_dir / f"reference/{page}.qmd").is_file() + method = docs.layout.build_dir / "reference/method.qmd" + assert "Runtime method summary" in method.read_text(encoding="utf-8") + inventory = decode((docs.layout.build_dir / "objects.inv").read_bytes()) + assert {entry.name: entry.uri.split("#")[0] for entry in inventory.entries} == { + name: f"reference/{page}.html" for name, page in expected.items() + } + finally: + run.close() + + monkeypatch.chdir(scoped_project) + assert documented.symbol_names( + docs._config, + importable_name="scope_demo", + search_paths=make_project(docs).search_paths(), + create_sections=make_exports(docs).sections, + ) == list(expected.values()) + + +def test_null_reference_package_accepts_qualified_names(scoped_project: Path) -> None: + """Resolve fully qualified names when the site has no default scope""" + write_config( + scoped_project, + { + "reference": { + "package": None, + "sections": [{"title": "Plugins", "contents": ["scope_extra.plugin"]}], + }, + }, + ) + docs = GreatDocs(project_path=str(scoped_project)) + + assert documented.symbol_names( + docs._config, + importable_name="scope_demo", + search_paths=make_project(docs).search_paths(), + create_sections=make_exports(docs).sections, + ) == ["scope_extra.plugin"] + + +@pytest.mark.parametrize( + "settings", + [ + {"package": False}, + {"sections": [{"title": "API", "package": "two names", "contents": ["one"]}]}, + {"sections": [{"title": "API", "contents": [{"name": "one", "package": []}]}]}, + ], +) +def test_reference_packages_require_dotted_names_or_null( + scoped_project: Path, settings: dict[str, object] +) -> None: + """Identify malformed package scopes before reference discovery""" + with pytest.raises(ConfigError, match=r"package must be a dotted Python name or null"): + write_config(scoped_project, {"reference": settings})