Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/user_guide/05-configuration.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 16 additions & 8 deletions great_docs/_apiref/introspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
13 changes: 8 additions & 5 deletions great_docs/_reference/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down
112 changes: 97 additions & 15 deletions great_docs/_reference/exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down Expand Up @@ -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 = [
Expand All @@ -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,
)
12 changes: 7 additions & 5 deletions great_docs/_reference/sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}.")
Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -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:
Expand Down
1 change: 1 addition & 0 deletions great_docs/assets/great-docs.default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
50 changes: 49 additions & 1 deletion great_docs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
"""
Expand Down
2 changes: 2 additions & 0 deletions tests/support.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
Loading
Loading