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
4 changes: 3 additions & 1 deletion great_docs/_apiref/api_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from ._extension_loading import _ExtensionSource
from ._rendering._renderers import Renderers
from ._settings import Settings, SourceLinks
from .content import Doc, Page
from .content import Doc, MemberPage, Page
from .inventory import create_inventory, write_inventory
from .resolve import ObjectNotFoundError, Resolver, StaticFallback
from .spec import SpecObject, SpecSection, unique_page_paths
Expand Down Expand Up @@ -382,5 +382,7 @@ def _member_children(node: Doc | Page) -> list[Doc | Page]:
The members, then any dataclass fields, or an empty list for an object that has
neither.
"""
if isinstance(node, MemberPage) and node.link_only:
return []
doc = node.contents[0] if isinstance(node, Page) else node
return [*getattr(doc, "members", []), *getattr(doc, "fields", [])]
53 changes: 41 additions & 12 deletions great_docs/_apiref/collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ def __init__(self, base_dir: str) -> None:
self.items: list[InventoryItem] = []
self.pages: list[Page] = []

def visit(self, el: object) -> object:
"""
Collect the objects and pages that the reference publishes
"""
if isinstance(el, MemberPage) and el.link_only:
return el
return super().visit(el)

def enclosing_page(self) -> Page:
"""
Find the nearest `Page` enclosing the current node
Expand Down Expand Up @@ -257,9 +265,9 @@ def remove_package_prefix(sections: list[Section], package: str) -> list[Section


class _MemberPagePathClaimer(NodeTransformer):
"""A node tree whose member pages have paths no other page shares case-insensitively"""
"""A tree whose member links and generated pages use their published paths"""

def __init__(self, claimed: dict[str, str]) -> None:
def __init__(self, claimed: dict[str, str], authored: dict[tuple[str, str], str]) -> None:
"""
Claim member page paths that do not clash with the paths already claimed

Expand All @@ -268,8 +276,23 @@ def __init__(self, claimed: dict[str, str]) -> None:
claimed
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.
"""
self.claimed = claimed
self.authored = authored

def enter(self, el: object) -> object:
"""
Replace a duplicated member page with a link before visiting its own members
"""
if isinstance(el, MemberPage):
doc = el.contents[0]
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)
return super().enter(el)

def exit(self, el: object) -> object:
"""
Expand All @@ -285,21 +308,20 @@ def exit(self, el: object) -> object:
:
The node, or a copy of a member page with a new path.
"""
if isinstance(el, MemberPage):
if isinstance(el, MemberPage) and not el.link_only:
path = claim_page_path(el.path, self.claimed, partial(get_label, el.obj))
return el if path == el.path else el.replace(path=path)
return super().exit(el)


def unique_member_page_paths(sections: list[Section]) -> list[Section]:
"""
Give every member page a path no other page shares case-insensitively
Resolve generated member links and page paths against the authored entries

Top-level pages already carry unique paths (see `spec.unique_page_paths()`)
and the sidebar and `llms.txt` link to them by those paths, so they are
claimed first and never move. A member page (from `members_on_same_page: false`)
that would share a file with another page on a case-insensitive filesystem
gets the member's label as a suffix instead (`Widget.Run-method`).
Authored pages already have unique paths and keep them. A parent links to
an authored page when it documents the same member under the same lookup path.
A generated page whose name differs from another page only by case gets the
member's label as a suffix (`Widget.Run-method`).

Parameters
----------
Expand All @@ -309,13 +331,20 @@ def unique_member_page_paths(sections: list[Section]) -> list[Section]:
Returns
-------
:
The sections with any clashing member page paths replaced.
The sections with member links and generated page paths resolved.
"""
claimed: dict[str, str] = {}
authored: dict[tuple[str, str], str] = {}
for section in sections:
for entry in section.contents:
if isinstance(entry, Page) and not isinstance(entry, MemberPage):
_ = claim_page_path(entry.path, claimed)

claimer = _MemberPagePathClaimer(claimed)
if len(entry.contents) == 1:
doc = entry.contents[0]
if doc.lookup_path is not None:
_ = authored.setdefault(
(doc.lookup_path, doc.obj.canonical_path), entry.path
)

claimer = _MemberPagePathClaimer(claimed, authored)
return claimer.visit(sections) # type: ignore[return-value]
9 changes: 9 additions & 0 deletions great_docs/_apiref/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class Doc(Walkable):
"""The object's anchor on its page"""
signature_name: DisplayNameFormat | None = None
"""The authored signature name format, or `None` for the renderer's default"""
lookup_path: str | None = field(default=None, kw_only=True)
"""The dotted path requested when resolving this object's documentation"""

@classmethod
def from_griffe(
Expand All @@ -42,6 +44,8 @@ def from_griffe(
anchor: str | None = None,
signature_name: DisplayNameFormat | None = None,
fields: list[DocAttribute] | None = None,
*,
lookup_path: str | None = None,
) -> DocFunction | DocAttribute | DocTypeAlias | DocClass | DocModule:
"""
Build a documentation node for a loaded object
Expand All @@ -66,6 +70,8 @@ def from_griffe(
fields
The attributes a dataclass node documents as constructor parameters, or
`None` for none.
lookup_path
The requested dotted path, or `None` for documentation built directly from a model.

Returns
-------
Expand All @@ -88,6 +94,7 @@ def from_griffe(
"obj": obj,
"anchor": anchor_val,
"signature_name": signature_name,
"lookup_path": lookup_path,
}

if kind == "function":
Expand Down Expand Up @@ -204,6 +211,8 @@ class MemberPage(Page):
"""A page produced automatically for a single class or module member"""

contents: list[Any] = field(default_factory=list[Any])
link_only: bool = False
"""Whether an authored page at this path already documents the member"""


@dataclass
Expand Down
5 changes: 4 additions & 1 deletion great_docs/_apiref/resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,7 @@ def _resolve_documented_object(
children,
signature_name=el.signature_name,
fields=fields,
lookup_path=path.replace(":", "."),
)

def _resolve_members(
Expand Down Expand Up @@ -813,7 +814,9 @@ def _resolve_members(

if same_page:
return list(children), fields
return [MemberPage(path=child.obj.path, contents=[child]) for child in children], fields
return [
MemberPage(path=f"{obj.path}.{child.name}", contents=[child]) for child in children
], fields

def _fetch_members(
self,
Expand Down
54 changes: 54 additions & 0 deletions tests/test_page_path_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,57 @@ def test_member_pages_get_their_label_as_a_suffix(monkeypatch: pytest.MonkeyPatc
"Widget.run",
"Widget.Run-method",
]


def test_member_links_use_the_case_disambiguated_authored_page(
monkeypatch: pytest.MonkeyPatch,
) -> None:
widget = _class("Widget", "run", "Run")
objects: dict[str, gf.Object | gf.Alias] = {
"mypkg:Widget": widget,
"mypkg:Widget.run": widget.members["run"],
"mypkg:Widget.Run": widget.members["Run"],
}
ref = _api_ref(
monkeypatch,
objects,
[
{"name": "Widget", "members_on_same_page": False, "members": ["run", "Run"]},
"Widget.run",
"Widget.Run",
],
)
try:
assert [page.path for page in ref.manifest.pages] == [
"Widget",
"Widget.run",
"Widget.Run-method",
]
widget_doc = ref.manifest.pages[0].contents[0]
assert [page.path for page in widget_doc.members] == ["Widget.run", "Widget.Run-method"]
finally:
ref.close()


def test_member_pages_preserve_a_differently_named_authored_alias(
monkeypatch: pytest.MonkeyPatch,
) -> None:
widget = _class("Widget", "run")
package = gf.Module("mypkg")
package.set_member("Widget", widget)
package.set_member("Machine", gf.Alias("Machine", widget, parent=package))
method = widget.members["run"]
alias = gf.Alias("run", method, parent=package.members["Machine"])
ref = _api_ref(
monkeypatch,
{"mypkg:Widget": widget, "mypkg:Widget.run": method, "mypkg:Machine.run": alias},
[{"name": "Widget", "members_on_same_page": False, "members": ["run"]}, "Machine.run"],
)
try:
assert {page.path for page in ref.manifest.pages} == {
"Widget",
"mypkg.Widget.run",
"Machine.run",
}
finally:
ref.close()
78 changes: 78 additions & 0 deletions tests/test_resolved_member_placement.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,3 +446,81 @@ def test_yaml_member_options_validate_nested_placement(replace: bool) -> None:
SpecObject(name="Widget").replace(**options)
else:
SpecObject(name="Widget", **options)


def test_declaration_and_runtime_member_pages_use_the_public_class_path(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
package = tmp_path / "public_members"
package.mkdir()
(package / "__init__.py").write_text("from .internal import Widget as Widget\n")
(package / "internal.py").write_text(
dedent(
'''
class Widget:
"""A widget"""

size: int
"""Attribute available on instances"""

def run(self):
"""Run the widget"""
'''
)
)
monkeypatch.syspath_prepend(str(tmp_path))
ref = reference_from_options(
{
"package": "public_members",
"dynamic": True,
"members_on_same_page": False,
"sections": [{"contents": ["Widget"]}],
}
)
try:
assert {page.path for page in ref.manifest.pages if isinstance(page, MemberPage)} == {
"public_members.Widget.run",
"public_members.Widget.size",
}
finally:
ref.close()


def test_an_explicit_member_page_owns_the_member_link_and_inventory(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
(tmp_path / "linked_members.py").write_text(dedent(_SOURCE))
monkeypatch.syspath_prepend(str(tmp_path))
ref = reference_from_options(
{
"package": "linked_members",
"dynamic": False,
"sections": [
{
"contents": [
{
"name": "Widget",
"members": ["run", "stop"],
"members_on_same_page": False,
},
"Widget.run",
],
}
],
}
)
try:
assert {page.path for page in ref.manifest.pages} == {
"Widget",
"Widget.run",
"linked_members.Widget.stop",
}
widget = next(page.contents[0] for page in ref.manifest.pages if page.path == "Widget")
[run, stop] = widget.members
assert run.path == "Widget.run"
assert stop.path == "linked_members.Widget.stop"
uris = [item.uri for item in ref.items if item.name == "linked_members.Widget.run"]
assert len(uris) == 1
assert uris[0] is not None and uris[0].startswith("reference/Widget.run.html")
finally:
ref.close()
Loading