Skip to content

livery.extensions.docs._taskref

livery.extensions.docs._taskref

The per-package task reference: footman's renderer, one mechanism.

The docs phase's task-reference step renders it (task_reference_run), declared off until the root contract turns it on. Every package that advertises footman.tasks entry points gets its tasks documented in its own site section, and the section documents the package's whole offering: each advertised provider renders in isolation (a one-line tasks file mounting only that provider, no cascade, no base), so no workspace composition, shadowing, disabling, or exclude= mount can change what a package's docs say. Hidden tasks stay out by the package's own flags. Pages render with livery.footman.markdown.render_site over the isolated tree, into the owner's gitignored docs/_generated/tasks/ tree, and the tasks nav block is emitted beside them as nav.tasks.toml; the owner's nav.toml places it with a marker pair and commits nothing the tree changes. A providing package whose nav.toml lacks the pair refuses, since the section would have no home.

Footman links every task name through one URL template, so a generated alias tree at the uniform tasks/<slug>/ address redirects each task to its page in the owning package's section; task_links is that template under the site's address.

Functions:

Name Description
task_page

The page the task at address publishes on, relative to the site's root.

task_links

The URL template that links a task's name to its page under site_url.

advertised_providers

The footman.tasks entry-point names package advertises.

provider_tree

The provider's advertised tree, rendered in isolation.

task_nav_block

The tasks nav block for trees, one provider's tree each, unindented.

committed_nav_block

The lines inside the name block markers of the nav.toml at path.

generate_task_reference

Render every advertising package's task reference; the packages.

task_reference_run

Render every providing package's task reference: the docs phase's step.

Attributes:

Name Type Description
NAV_BLOCK
ALIASES
PAGES
TASK_REFERENCE

NAV_BLOCK module-attribute

NAV_BLOCK = 'tasks'

ALIASES module-attribute

ALIASES = 'tasks'

PAGES module-attribute

PAGES = 'tasks'

TASK_REFERENCE module-attribute

TASK_REFERENCE = 'docs.task-reference'

task_page

task_page(owner: str, address: str) -> str

The page the task at address publishes on, relative to the site's root.

A task's page sits in the section of owner, the member that advertises its provider, one directory per group of its address: the workshop's coverage.leg is packages/workshop/tasks/coverage/leg.md.

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def task_page(owner: str, address: str) -> str:
    """The page the task at *address* publishes on, relative to the site's root.

    A task's page sits in the section of *owner*, the member that
    advertises its provider, one directory per group of its address:
    the workshop's ``coverage.leg`` is
    ``packages/workshop/tasks/coverage/leg.md``.
    """
    return f"packages/{owner}/{PAGES}/{'/'.join(address.split('.'))}.md"
task_links(site_url: str) -> str

The URL template that links a task's name to its page under site_url.

Each task's alias page redirects to its page in the owning package's section, so the one template serves every package.

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def task_links(site_url: str) -> str:
    """The URL template that links a task's name to its page under *site_url*.

    Each task's alias page redirects to its page in the owning package's
    section, so the one template serves every package.
    """
    return f"{site_url.rstrip('/')}/{ALIASES}/{{slug}}/"

advertised_providers

advertised_providers(package: Package) -> list[str]

The footman.tasks entry-point names package advertises.

Read from the package's own committed pyproject.toml, so the enumeration is offline and deterministic; a package without the table provides no tasks and gets no section.

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def advertised_providers(package: Package) -> list[str]:
    """The ``footman.tasks`` entry-point names *package* advertises.

    Read from the package's own committed ``pyproject.toml``, so the
    enumeration is offline and deterministic; a package without the
    table provides no tasks and gets no section.
    """
    pyproject = package.directory / "pyproject.toml"
    if not pyproject.is_file():
        return []
    parsed = tomllib.loads(pyproject.read_text("utf-8"))
    project = parsed.get("project")
    points = project.get("entry-points") if isinstance(project, dict) else None
    table = points.get("footman.tasks") if isinstance(points, dict) else None
    if not isinstance(table, dict):
        return []
    return sorted(str(name) for name in table)

provider_tree

provider_tree(root: Path, identity: str) -> dict[str, object]

The provider's advertised tree, rendered in isolation.

A one-line tasks file mounts only identity (--tasks-file means one file, no cascade, no base), so the answer is the package's whole offering regardless of how any workspace composes it.

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def provider_tree(root: Path, identity: str) -> dict[str, object]:
    """The provider's advertised tree, rendered in isolation.

    A one-line tasks file mounts only *identity* (``--tasks-file``
    means one file, no cascade, no base), so the answer is the
    package's whole offering regardless of how any workspace
    composes it.
    """
    import shutil as _shutil

    import livery.footman as footman

    runner = _shutil.which(footman.prog())
    if not runner:
        fail(
            f"{footman.prog()} is not on PATH, so the task reference"
            " cannot read the advertised trees; enter the environment"
            " (source setup.sh) first"
        )
    with tempfile.TemporaryDirectory() as scratch:
        probe = Path(scratch) / "only.py"
        probe.write_text(
            f'from livery.footman import plugin\n\nplugin("{identity}")\n',
            encoding="utf-8",
        )
        result = footman.run(
            [runner, f"--tasks-file={probe}", "--json", "--list"],
            cwd=root,
            nofail=True,
            recorded=False,
        )
    if int(result) != 0:
        fail(
            f"{footman.prog()} --tasks-file --json --list for"
            f" {identity!r} exited {int(result)}"
        )
    return cast("dict[str, object]", json.loads(result.stdout)["tree"])

task_nav_block

task_nav_block(trees: list[dict[str, object]], prog: str) -> list[str]

The tasks nav block for trees, one provider's tree each, unindented.

An overview, then each group in name order with its overview and a page per task (dotted for a nested group), then each top-level task. The lines are what generate_task_reference writes between the markers, so a committed block compares against them.

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def task_nav_block(trees: list[dict[str, object]], prog: str) -> list[str]:
    """The ``tasks`` nav block for *trees*, one provider's tree each, unindented.

    An overview, then each group in name order with its overview and
    a page per task (dotted for a nested group), then each top-level
    task. The lines are what `generate_task_reference` writes between
    the markers, so a committed block compares against them.
    """
    block: list[str] = [
        '{ "Tasks" = [',
        '    { "Overview" = "_generated/tasks/index.md" },',
    ]
    for tree in trees:
        groups = tree.get("groups")
        top_tasks = tree.get("tasks")
        if isinstance(groups, dict):
            for head in sorted(groups):
                block.append(f'    {{ "{head}" = [')
                block.append(
                    f'        {{ "Overview" = "_generated/tasks/{head}/index.md" }},'
                )
                for relative in sorted(_group_pages(tree, head, prog)):
                    if relative.rsplit("/", 1)[-1] == "index.md":
                        continue
                    dotted = relative.removesuffix(".md").replace("/", ".")
                    page = f"_generated/tasks/{head}/{relative}"
                    block.append(f'        {{ "{dotted}" = "{page}" }},')
                block.append("    ] },")
        if isinstance(top_tasks, dict):
            for head in sorted(top_tasks):
                block.append(f'    {{ "{head}" = "_generated/tasks/{head}.md" }},')
    block.append("] },")
    return block

committed_nav_block

committed_nav_block(path: Path, name: str) -> list[str] | None

The lines inside the name block markers of the nav.toml at path.

Dedented to the begin marker's indentation, so they compare with what a generator produces. None when the file is missing or the marker pair is not there exactly once.

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def committed_nav_block(path: Path, name: str) -> list[str] | None:
    """The lines inside the *name* block markers of the ``nav.toml`` at *path*.

    Dedented to the begin marker's indentation, so they compare with
    what a generator produces. None when the file is missing or the
    marker pair is not there exactly once.
    """
    begin, end = nav_block_markers(name)
    if not path.is_file():
        return None
    lines = path.read_text("utf-8").splitlines()
    starts = [i for i, line in enumerate(lines) if line.strip() == begin]
    ends = [i for i, line in enumerate(lines) if line.strip() == end]
    if len(starts) != 1 or len(ends) != 1 or ends[0] < starts[0]:
        return None
    marker = lines[starts[0]]
    indent = marker[: len(marker) - len(marker.lstrip())]
    return [
        line[len(indent) :] if line.startswith(indent) else line.strip()
        for line in lines[starts[0] + 1 : ends[0]]
    ]

generate_task_reference

generate_task_reference(root: Path) -> list[str]

Render every advertising package's task reference; the packages.

An index per group and a page per task of each provider's isolated tree, into the owner's docs/_generated/tasks/ tree; the tasks nav block emitted beside them; the site-root alias tree refreshed. A providing package whose nav.toml lacks the marker pair refuses naming the file: where the section sits in the tree is the author's decision.

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def generate_task_reference(root: Path) -> list[str]:
    """Render every advertising package's task reference; the packages.

    An index per group and a page per task of each provider's
    isolated tree, into the owner's ``docs/_generated/tasks/`` tree;
    the ``tasks`` nav block emitted beside them; the site-root alias
    tree refreshed. A providing package whose ``nav.toml`` lacks the
    marker pair refuses naming the file: where the section sits in
    the tree is the author's decision.
    """
    import livery.footman as footman
    from livery.footman import markdown

    prog = footman.prog()
    providing = _providing(root)
    if not providing and not any(
        advertised_providers(package) for package in discover_packages(root)
    ):
        return []
    aliases = root / "docs" / ALIASES
    shutil.rmtree(aliases, ignore_errors=True)
    aliases.mkdir(parents=True)
    rendered: list[str] = []
    for package, trees in providing:
        owner = package.member
        out = package.directory / "docs" / GENERATED_DIR / PAGES
        shutil.rmtree(out, ignore_errors=True)
        out.mkdir(parents=True)
        index = ["# Task reference", ""]
        addresses: list[str] = []
        for tree in trees:
            addresses += _addresses(tree)
            groups = tree.get("groups")
            top_tasks = tree.get("tasks")
            if isinstance(groups, dict):
                for head in sorted(groups):
                    for relative, content in _group_pages(tree, head, prog).items():
                        target = out / head / relative
                        target.parent.mkdir(parents=True, exist_ok=True)
                        target.write_text(content, encoding="utf-8")
                    index.append(f"- [{head}]({head}/index.md)")
            if isinstance(top_tasks, dict):
                for head in sorted(top_tasks):
                    page = markdown.render_page(
                        tree, path=(head,), heading=1, flavor="material", prog=prog
                    )
                    (out / f"{head}.md").write_text(page, encoding="utf-8")
                    index.append(f"- [{head}]({head}.md)")
        (out / "index.md").write_text("\n".join(index) + "\n", encoding="utf-8")
        nav = package.directory / "docs" / "nav.toml"
        if committed_nav_block(nav, NAV_BLOCK) is None:
            begin, end = nav_block_markers(NAV_BLOCK)
            fail(
                f"{nav} does not carry the {NAV_BLOCK!r} block markers ({begin!r}"
                f" then {end!r}, once each): add them where the section belongs"
            )
        write_nav_block(out.parent, NAV_BLOCK, task_nav_block(trees, prog))
        for address in sorted(addresses):
            published = task_page(owner, address).removesuffix(".md")
            destination = f"../../{published}/"
            (aliases / f"{address.replace('.', '-')}.md").write_text(
                _alias_page(destination, address), encoding="utf-8"
            )
        rendered.append(owner)
    return sorted(rendered)

task_reference_run

task_reference_run(ctx: PhaseContext) -> None

Render every providing package's task reference: the docs phase's step.

An index per group and a page per public task into each owner's generated tree, the owner's tasks nav block emitted beside them, and the alias tree the runner's task links go through refreshed (generate_task_reference).

Source code in packages/extensions/docs/src/livery/extensions/docs/_taskref.py
def task_reference_run(ctx: PhaseContext) -> None:
    """Render every providing package's task reference: the docs phase's step.

    An index per group and a page per public task into each owner's
    generated tree, the owner's ``tasks`` nav block emitted beside
    them, and the alias tree the runner's task links go through
    refreshed (`generate_task_reference`).
    """
    rendered = generate_task_reference(ctx.root)
    if rendered:
        print(f"  task reference for {', '.join(rendered)}")
    else:
        print("  no workspace package provides tasks")