Skip to content

livery.extensions.docs._packages_page

livery.extensions.docs._packages_page

The site's Packages section: where each package sits, in what order, and its page.

Every package sits under one entry, Packages, in a tree its contract decides. A package whose code other packages reference by import path sits at the shallowest of those paths, less the namespace every such package shares: livery.toolroom.bench sits at toolroom, then bench. A package no import path reaches sits at its folder under packages/. A package's [docs] name, a dotted path whose last part is its label, places it anywhere, inside another package's entry included. Siblings come in the order the release wave publishes in, every dependency before its dependents, and a group sorts with its earliest member. The landing page lists the same tree, each package with its contract's description.

Classes:

Name Description
Node

One place in the Packages tree: a package's, a group's, or both.

Functions:

Name Description
declared_place

The place package's [docs] name gives it, or None without one.

imported_place

The shallowest import path package's code is referenced by, split at its dots.

places

Each package's place in the Packages tree, by its path.

package_tree

The Packages tree of packages; read it through Node.ordered.

write_packages_page

Write the Packages landing page into the mount; its path, None without packages.

Attributes:

Name Type Description
MOUNT
LANDING

MOUNT module-attribute

MOUNT = 'docs/packages'

LANDING module-attribute

LANDING = 'index.md'

Node dataclass

Node(label: str, package: Package | None = None, children: dict[str, Node] = dict[str, 'Node'](), rank: int = 0)

One place in the Packages tree: a package's, a group's, or both.

Attributes:

Name Type Description
label str

The place's last part, the nav's label for it.

package Package | None

The package at this place, or None for a group.

children dict[str, Node]

The places below it, by label.

rank int

Where the place sorts among its siblings: its earliest package's position in the dependency order.

Methods:

Name Description
ordered

The places below, dependencies first, then by label.

label instance-attribute

label: str

package class-attribute instance-attribute

package: Package | None = None

children class-attribute instance-attribute

children: dict[str, Node] = field(default_factory=dict[str, 'Node'])

rank class-attribute instance-attribute

rank: int = 0

ordered

ordered() -> list[Node]

The places below, dependencies first, then by label.

Source code in packages/extensions/docs/src/livery/extensions/docs/_packages_page.py
def ordered(self) -> list[Node]:
    """The places below, dependencies first, then by label."""
    return sorted(
        self.children.values(), key=lambda child: (child.rank, child.label)
    )

declared_place

declared_place(package: Package) -> tuple[str, ...] | None

The place package's [docs] name gives it, or None without one.

Raises:

Type Description
Failed

when the name is not a dotted path, naming the file.

Source code in packages/extensions/docs/src/livery/extensions/docs/_packages_page.py
def declared_place(package: Package) -> tuple[str, ...] | None:
    """The place *package*'s ``[docs] name`` gives it, or None without one.

    Raises:
        Failed: when the name is not a dotted path, naming the file.
    """
    table = read_contract(package.directory).get("docs") or {}
    name = table.get("name") if isinstance(table, dict) else None
    if name is None:
        return None
    if not isinstance(name, str) or not _NAME.fullmatch(name):
        fail(
            f"{package.directory / 'workshop.toml'}: [docs] name {name!r} is not a"
            " dotted path, such as 'workshop.extensions.ruff'"
        )
    return tuple(name.split("."))

imported_place

imported_place(package: Package) -> tuple[str, ...] | None

The shallowest import path package's code is referenced by, split at its dots.

Read from its module roots, which the package's extensions answer. The path with the fewest parts wins; of two with as many, the one answered first. None for a package no import path reaches.

Source code in packages/extensions/docs/src/livery/extensions/docs/_packages_page.py
def imported_place(package: Package) -> tuple[str, ...] | None:
    """The shallowest import path *package*'s code is referenced by, split at its dots.

    Read from its module roots, which the package's extensions answer.
    The path with the fewest parts
    wins; of two with as many, the one answered first. None for a
    package no import path reaches.
    """
    roots = answer(package, MODULE_ROOTS)
    if not roots:
        return None
    return tuple(min(roots, key=lambda root: root.count(".")).split("."))

places

places(packages: tuple[Package, ...]) -> dict[str, tuple[str, ...]]

Each package's place in the Packages tree, by its path.

Its [docs] name when it declares one; else its shallowest import path (imported_place), less the first part when every such path shares it; else its folder under packages/.

Source code in packages/extensions/docs/src/livery/extensions/docs/_packages_page.py
def places(packages: tuple[Package, ...]) -> dict[str, tuple[str, ...]]:
    """Each package's place in the Packages tree, by its path.

    Its ``[docs] name`` when it declares one; else its shallowest import
    path (`imported_place`), less the first part when every such path
    shares it; else its folder under ``packages/``.
    """
    declared = {package.path: declared_place(package) for package in packages}
    imported: dict[str, tuple[str, ...]] = {}
    for package in packages:
        if declared[package.path] is not None:
            continue
        place = imported_place(package)
        if place is not None:
            imported[package.path] = place
    heads = {parts[0] for parts in imported.values()}
    shared = (
        heads.pop()
        if len(heads) == 1 and all(len(parts) > 1 for parts in imported.values())
        else ""
    )
    found: dict[str, tuple[str, ...]] = {}
    for package in packages:
        place = declared[package.path]
        if place is None and package.path in imported:
            parts = imported[package.path]
            place = parts[1:] if shared else parts
        found[package.path] = place or tuple(package.member.split("/"))
    return found

package_tree

package_tree(packages: tuple[Package, ...]) -> Node

The Packages tree of packages; read it through Node.ordered.

Raises:

Type Description
Failed

when two packages sit at one place, naming both.

Source code in packages/extensions/docs/src/livery/extensions/docs/_packages_page.py
def package_tree(packages: tuple[Package, ...]) -> Node:
    """The Packages tree of *packages*; read it through `Node.ordered`.

    Raises:
        Failed: when two packages sit at one place, naming both.
    """
    # Read here, not at import: the module that serves it registers the
    # base's graph verbs, which the extension's plugin, loaded alone,
    # would otherwise carry.
    from livery.workshop import order_topologically

    order = order_topologically(tuple(sorted(packages, key=lambda p: p.path)))
    found = places(order)
    root = Node("Packages")
    taken: dict[tuple[str, ...], Package] = {}
    for rank, package in enumerate(order):
        place = found[package.path]
        if place in taken:
            fail(
                f"{taken[place].path} and {package.path} both sit at"
                f" {'.'.join(place)} in the Packages tree: give one a [docs] name"
                " of its own"
            )
        taken[place] = package
        node = root
        for part in place:
            # The dependency order visits the earliest member first, so
            # a group keeps the rank its first package gave it.
            node = node.children.setdefault(part, Node(part, rank=rank))
        node.package = package
    return root

write_packages_page

write_packages_page(root: Path) -> Path | None

Write the Packages landing page into the mount; its path, None without packages.

Runs after the mount, so each package links to the page its section opens on. Rebuilt on every docs verb, as the mount is.

Source code in packages/extensions/docs/src/livery/extensions/docs/_packages_page.py
def write_packages_page(root: Path) -> Path | None:
    """Write the Packages landing page into the mount; its path, None without packages.

    Runs after the mount, so each package links to the page its
    section opens on. Rebuilt on every docs verb, as the mount is.
    """
    packages = discover_packages(root)
    if not packages:
        return None
    base = root / MOUNT
    lines = [
        "# Packages",
        "",
        "Every package of the workspace, each after the packages it depends on.",
        "",
    ]

    def walk(node: Node, depth: int) -> None:
        for child in node.ordered():
            pad = "    " * depth
            package = child.package
            if package is None:
                lines.append(f"{pad}- {child.label}")
            else:
                link = _landing_link(base, package)
                label = f"[{child.label}]({link})" if link else child.label
                description = str(
                    read_contract(package.directory).get("description", "")
                )
                lines.append(
                    f"{pad}- {label}" + (f": {description}" if description else "")
                )
            walk(child, depth + 1)

    walk(package_tree(packages), 0)
    path = base / LANDING
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    return path