Skip to content

livery.workshop._declaration

livery.workshop._declaration

Read an extension's declaration file, extension.toml, without importing it.

An extension declares itself in one extension.toml, beside the package its workshop.extensions entry point names: what it does, the workshop API version it is written for, its plugin, the extensions it requires, the phases it declares and the steps it adds to a package's lifecycle phases and to the gate's phases, the queries it declares and the ones it answers, the tools it runs, its CI jobs, the contract keys it owns, what it adds to another extension while that one is listed, and the shipped files of the base and of the extensions it requires that it replaces or deletes. The file is a contract, read as workshop.toml is: kebab-case keys, every key judged, every refusal naming the file. Every extension is one kind: the root's [workspace] extensions and a package's extensions both list any of them, so the file says nothing about where it is listed.

A [phases.<phase>] table declares the phase when it carries level, gated, after, verb or keys (livery.workshop._phases.PhaseSpec), in the grammar the base's own contract file declares its phases in; a phase no declaration names refuses naming the declared ones. Beside those keys the table holds the phase's steps, and nothing else.

A [queries.<name>] table declares the query when it carries combine, level, default or values (livery.workshop._queries.QuerySpec), in the grammar the base's own contract file declares its queries in; a table carrying value is a literal answer, and <name> = "module:function" under [queries] answers by a function. An answer to a query no declaration names refuses naming the declared ones. A [for.<target>.queries] table answers in the same grammar, asked while the target is listed, and declares no query. A [for.<target>.fragments] table writes its files while the target is listed, and so are the files the extension ships under content/for/<target>/; a directory there for a target the file declares no [for.<target>] table for refuses, naming both. A [for.<target>.toolroom] table's requires names the tools the workspace requires while the table applies.

A [templates.<name>] table declares a template, which fm new.package.<name> creates a package from: its doc, the extensions such a package lists, extends, the template whose files come first, its creation options under [templates.<name>.options.<option>] (TemplateOption), and fixes, the answers it gives options of the templates it extends (DeclaredTemplate). The base declares its own in the same grammar, and a [for.<target>] table declares none: a template names the extensions it needs in its own extensions, and a workspace offers it while its installed set holds the extension that declares it.

[extension] dormant-until names, as a verb, what another extension does for this one by declaring a [for.<this>] table: until a listed extension does, this one is dormant (livery.workshop._extensions.dormancy).

An [env.<NAME>] table declares an environment variable the extension needs (DeclaredVariable): its value, always, and its doc. A [for.<target>] table declares none, since a variable an extension needs does not depend on what else is listed.

A step table's deletes names the steps of other extensions that never run for a package whose set holds this one, each <owner>:<phase>.<step> to the reason: the base's, or those of an extension this one requires, or, in a [for.<target>] table, the target's, which the mount judges. A deletion naming no step an installed extension or the base declares, one naming a step that runs once over the workspace, and one without a reason refuse here.

A step is declared at [phases.<phase>.<step>] and reads into one record whatever its phase's level (livery.workshop._steps.StepRecord): a workspace-level phase's steps register at mount, and a package-level phase's run over each package whose set holds the extension. fm check runs the tree side, so of a gated package-level phase, the build, a step serving the tree side registers at mount as well, and one serving the isolated side alone registers nothing. A step whose verdict is its tool's exit code is its tool's words (main as a template, with fix, safe-fix, env and matrix), which the engine runs (livery.workshop._words.Command). Other behaviour is a reference, "module:function", imported when it runs. The read imports nothing. A reference whose module is not in the extension's package, or whose module does not define the name at its top level, refuses here, read from the module's source.

Classes:

Name Description
DeclarationError

An extension's declaration file says something the workshop cannot take.

Reference

A function a declaration names, "module:function", imported when it runs.

CodedFix

A step's rewrite in code with a safe mode of its own, run as the record's fix.

Additions

What a declaration adds while it is mounted.

DeclaredValue

A literal answer to a query: [queries.<name>] value = ....

DeclaredOutput

A file an extension's code writes: a [fragments."<target>"] table.

DeclaredVariable

An environment variable an extension needs: an [env.<NAME>] table.

Declaration

An extension's declaration file, read and judged.

TemplateOption

A creation option: a [templates.<name>.options.<option>] table.

DeclaredTemplate

A template a declaration file declares under [templates.<name>].

Functions:

Name Description
directory

Where package lives, found without importing it; None when it is absent.

declaration_file

package's declaration file; None when the package or its file is absent.

read

extension's declaration, from the file beside package; None without one.

phase_specs_of

The phases data's [phases.<phase>] tables declare, judged, by name.

phase_declarations

The phases the declaration beside package declares, for extension.

query_specs_of

The queries data's [queries.<name>] tables declare, judged, by name.

query_declarations

The queries the declaration beside package declares, for extension.

template_specs_of

The templates data's [templates.<name>] tables declare, judged, by name.

template_declarations

The templates the declaration beside package declares, for extension.

installed_steps

Every installed step, <owner>:<phase>.<step>, to the scope it runs at.

top_level_names

The names path's module defines at its top level, read from its source.

defined_tasks

The tasks the modules under directory define, <group>.<task>, read by AST.

task_docs

Each task the modules under directory define to its doc line, read by AST.

contract_keys

The contract keys the declaration beside package owns; empty without one.

contract_keys_of

The contract keys data's [contract] tables declare, judged.

Attributes:

Name Type Description
FILE
API_VERSION
CONTRACTS
OPTION_TYPES dict[str, type]
Answer

The answer to a template's option: a string, an integer or a boolean.

FILE module-attribute

FILE = 'extension.toml'

API_VERSION module-attribute

API_VERSION = 1

CONTRACTS module-attribute

CONTRACTS = ('root', 'package')

OPTION_TYPES module-attribute

OPTION_TYPES: dict[str, type] = {'str': str, 'int': int, 'bool': bool}

Answer module-attribute

Answer = str | int | bool

The answer to a template's option: a string, an integer or a boolean.

DeclarationError

Bases: RuntimeError

An extension's declaration file says something the workshop cannot take.

The extension's own mistake, which no sync repairs: the message names the file, the key, and what it takes.

Reference dataclass

Reference(module: str, name: str)

A function a declaration names, "module:function", imported when it runs.

Attributes:

Name Type Description
module str

The module that defines it, in the extension's package.

name str

The name the module defines it under, at its top level.

Methods:

Name Description
resolve

The object the reference names, its module imported now.

__call__

Call the named function with args and kwargs, importing it first.

__str__

The reference as the declaration spells it.

module instance-attribute

module: str

name instance-attribute

name: str

resolve

resolve() -> Any

The object the reference names, its module imported now.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def resolve(self) -> Any:
    """The object the reference names, its module imported now."""
    return getattr(importlib.import_module(self.module), self.name)

__call__

__call__(*args: Any, **kwargs: Any) -> Any

Call the named function with args and kwargs, importing it first.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def __call__(self, *args: Any, **kwargs: Any) -> Any:
    """Call the named function with *args* and *kwargs*, importing it first."""
    return self.resolve()(*args, **kwargs)

__str__

__str__() -> str

The reference as the declaration spells it.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def __str__(self) -> str:
    """The reference as the declaration spells it."""
    return f"{self.module}:{self.name}"

CodedFix dataclass

CodedFix(fix: Reference, safe_fix: Reference)

A step's rewrite in code with a safe mode of its own, run as the record's fix.

Attributes:

Name Type Description
fix Reference

The function run under --fix.

safe_fix Reference

The function run under --safe-fix instead, which removes no code.

Methods:

Name Description
__call__

Run the mode the run asks for: the safe one under --safe-fix.

__str__

Both references, as the declaration spells them.

fix instance-attribute

fix: Reference

safe_fix instance-attribute

safe_fix: Reference

__call__

__call__(ctx: PhaseContext) -> None

Run the mode the run asks for: the safe one under --safe-fix.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def __call__(self, ctx: PhaseContext) -> None:
    """Run the mode the run asks for: the safe one under ``--safe-fix``."""
    (self.safe_fix if ctx.safe else self.fix)(ctx)

__str__

__str__() -> str

Both references, as the declaration spells them.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def __str__(self) -> str:
    """Both references, as the declaration spells them."""
    return f"{self.fix} (safe-fix: {self.safe_fix})"

Additions dataclass

Additions(steps: tuple[StepRecord, ...] = (), jobs: tuple[JobContribution, ...] = ())

What a declaration adds while it is mounted.

Attributes:

Name Type Description
steps tuple[StepRecord, ...]

The steps of the [phases.<phase>.<step>] tables the mount registers, as records under the extension's name: those of the workspace-level phases and those of the gated package-level phases, less each that serves the isolated side alone.

jobs tuple[JobContribution, ...]

The CI jobs it adds to the builtin points, with their entries.

steps class-attribute instance-attribute

steps: tuple[StepRecord, ...] = ()

jobs class-attribute instance-attribute

jobs: tuple[JobContribution, ...] = ()

DeclaredValue dataclass

DeclaredValue(value: object)

A literal answer to a query: [queries.<name>] value = ....

Attributes:

Name Type Description
value object

The answer, as the file spells it.

value instance-attribute

value: object

DeclaredOutput dataclass

DeclaredOutput(target: str, render: Reference, local: bool = False)

A file an extension's code writes: a [fragments."<target>"] table.

The file is written while the workspace's installed set holds the extension, the root's list or a package's set, and withdrawn when none does.

Attributes:

Name Type Description
target str

The file's path from the workspace root; a path ending in / is a directory whose files the render names.

render Reference

The function the workshop calls with the workspace root. For a file it answers the text, or nothing for no file; for a directory, each file's path under it to its text, or to the shipped file or directory the file links to.

local bool

Whether the files belong to this checkout alone and are never committed.

target instance-attribute

target: str

render instance-attribute

render: Reference

local class-attribute instance-attribute

local: bool = False

DeclaredVariable dataclass

DeclaredVariable(name: str, value: str, doc: str, always: bool = False, extension: str = '')

An environment variable an extension needs: an [env.<NAME>] table.

The workshop sets it for every fm run, in a CI job's entry, in a pass of the loop and in the scale fixture.

Attributes:

Name Type Description
name str

The variable's name.

value str

Its value, as the file spells it. {place} in it stands for a directory of the variable's own, which each place the variable is set in names; no other brace form is taken.

doc str

What the variable is for.

always bool

Whether the value beats one the environment already carries where an environment is formed for what runs inside it: a CI job's, by its entry, a loop pass's and the scale fixture's. Everywhere else, and without it, the environment's value wins.

extension str

The extension that declares it.

Methods:

Name Description
render

The value with place where {place} stands.

name instance-attribute

name: str

value instance-attribute

value: str

doc instance-attribute

doc: str

always class-attribute instance-attribute

always: bool = False

extension class-attribute instance-attribute

extension: str = ''

placed property

placed: bool

Whether the value names {place}, so it is set only where one is named.

render

render(place: str) -> str

The value with place where {place} stands.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def render(self, place: str) -> str:
    """The value with *place* where ``{place}`` stands."""
    from livery.workshop._variables import PLACE_WORD

    return self.value.replace(PLACE_WORD, place)

Declaration dataclass

Declaration(extension: str, package: str, path: Path, description: str = '', api_version: int = API_VERSION, plugin: str = '', requires: tuple[str, ...] = (), dormant_until: str = '', tools: tuple[str, ...] = (), additions: Additions = Additions(), targets: dict[str, Additions] = dict[str, Additions](), target_tables: dict[str, dict[str, Any]] = dict[str, dict[str, Any]](), tables: dict[str, Any] = dict[str, Any](), replaces: dict[str, str] = dict[str, str](), deletes: dict[str, str] = dict[str, str](), fragments: tuple[DeclaredOutput, ...] = (), target_fragments: dict[str, tuple[DeclaredOutput, ...]] = dict[str, tuple[DeclaredOutput, ...]](), target_tools: dict[str, tuple[str, ...]] = dict[str, tuple[str, ...]](), phase_specs: dict[str, PhaseSpec] = dict[str, 'PhaseSpec'](), phases: dict[str, tuple[StepRecord, ...]] = dict[str, tuple['StepRecord', ...]](), query_specs: dict[str, QuerySpec] = dict[str, 'QuerySpec'](), queries: dict[str, Reference | DeclaredValue] = dict[str, 'Reference | DeclaredValue'](), target_queries: dict[str, dict[str, Reference | DeclaredValue]] = dict[str, 'dict[str, Reference | DeclaredValue]'](), categories: tuple[tuple[str, tuple[str, ...]], ...] = (), templates: dict[str, DeclaredTemplate] = dict[str, 'DeclaredTemplate'](), env: tuple[DeclaredVariable, ...] = ())

An extension's declaration file, read and judged.

Attributes:

Name Type Description
extension str

The name the extension is listed by.

package str

The package its entry point names, where its references live.

path Path

The declaration file.

description str

What the extension does, in a sentence or two, which the agent's guidance and the site's development pages open its block with; empty for none.

api_version int

The workshop API version it is written for.

plugin str

The footman plugin carrying its verbs; empty for none.

requires tuple[str, ...]

The extensions it cannot work without.

dormant_until str

What another extension does for this one by declaring a [for.<this>] table, a verb; empty for an extension that is never dormant.

tools tuple[str, ...]

The tools it runs, its verbs' and its steps', as requirement strings.

additions Additions

What it adds whenever it is mounted.

targets dict[str, Additions]

What it adds to each target while the target is listed.

target_tables dict[str, dict[str, Any]]

Each [for.<target>] table as the file holds it.

tables dict[str, Any]

The file's top-level tables but [extension] and [for], as the file holds them.

replaces dict[str, str]

Each shipped file of the base or of an extension it requires, <owner>:<name>, its own file of that name replaces, to the reason.

deletes dict[str, str]

Each shipped file of the base or of an extension it requires that it deletes, to the reason.

fragments tuple[DeclaredOutput, ...]

The files its code writes, by target.

target_fragments dict[str, tuple[DeclaredOutput, ...]]

The files each [for.<target>] table's code writes, by target; a target whose table writes none is left out.

target_tools dict[str, tuple[str, ...]]

The tools each [for.<target>] table requires under [toolroom] requires, by target, as requirement strings; a target whose table requires none is left out.

phase_specs dict[str, PhaseSpec]

The phases it declares, by name.

phases dict[str, tuple[StepRecord, ...]]

The steps its top-level [phases.<phase>.<step>] tables add, by phase, each the one step record whatever the phase's level: a package-level phase's run through the walk of a package's phase (livery.workshop._phases.walk_steps), and those the mount registers are among additions too.

query_specs dict[str, QuerySpec]

The queries it declares, by name.

queries dict[str, Reference | DeclaredValue]

The queries it answers, each query's name to the function that answers it or to its literal answer.

target_queries dict[str, dict[str, Reference | DeclaredValue]]

The queries each [for.<target>] table answers, by target, in the shape of queries; a target whose table answers none is left out.

categories tuple[tuple[str, tuple[str, ...]], ...]

The categories it gives its packages' paths, each category to the patterns it takes, relative to the package.

templates dict[str, DeclaredTemplate]

The templates it declares, by name, in the file's order.

env tuple[DeclaredVariable, ...]

The environment variables it needs, in the file's order.

extension instance-attribute

extension: str

package instance-attribute

package: str

path instance-attribute

path: Path

description class-attribute instance-attribute

description: str = ''

api_version class-attribute instance-attribute

api_version: int = API_VERSION

plugin class-attribute instance-attribute

plugin: str = ''

requires class-attribute instance-attribute

requires: tuple[str, ...] = ()

dormant_until class-attribute instance-attribute

dormant_until: str = ''

tools class-attribute instance-attribute

tools: tuple[str, ...] = ()

additions class-attribute instance-attribute

additions: Additions = Additions()

targets class-attribute instance-attribute

targets: dict[str, Additions] = field(default_factory=dict[str, Additions])

target_tables class-attribute instance-attribute

target_tables: dict[str, dict[str, Any]] = field(default_factory=dict[str, dict[str, Any]])

tables class-attribute instance-attribute

tables: dict[str, Any] = field(default_factory=dict[str, Any])

replaces class-attribute instance-attribute

replaces: dict[str, str] = field(default_factory=dict[str, str])

deletes class-attribute instance-attribute

deletes: dict[str, str] = field(default_factory=dict[str, str])

fragments class-attribute instance-attribute

fragments: tuple[DeclaredOutput, ...] = ()

target_fragments class-attribute instance-attribute

target_fragments: dict[str, tuple[DeclaredOutput, ...]] = field(default_factory=dict[str, tuple[DeclaredOutput, ...]])

target_tools class-attribute instance-attribute

target_tools: dict[str, tuple[str, ...]] = field(default_factory=dict[str, tuple[str, ...]])

phase_specs class-attribute instance-attribute

phase_specs: dict[str, PhaseSpec] = field(default_factory=dict[str, 'PhaseSpec'])

phases class-attribute instance-attribute

phases: dict[str, tuple[StepRecord, ...]] = field(default_factory=dict[str, tuple['StepRecord', ...]])

query_specs class-attribute instance-attribute

query_specs: dict[str, QuerySpec] = field(default_factory=dict[str, 'QuerySpec'])

queries class-attribute instance-attribute

queries: dict[str, Reference | DeclaredValue] = field(default_factory=dict[str, 'Reference | DeclaredValue'])

target_queries class-attribute instance-attribute

target_queries: dict[str, dict[str, Reference | DeclaredValue]] = field(default_factory=dict[str, 'dict[str, Reference | DeclaredValue]'])

categories class-attribute instance-attribute

categories: tuple[tuple[str, tuple[str, ...]], ...] = ()

templates class-attribute instance-attribute

templates: dict[str, DeclaredTemplate] = field(default_factory=dict[str, 'DeclaredTemplate'])

env class-attribute instance-attribute

env: tuple[DeclaredVariable, ...] = ()

TemplateOption dataclass

TemplateOption(name: str, doc: str, choices: tuple[str, ...], type: str, default: Answer | None)

A creation option: a [templates.<name>.options.<option>] table.

fm new.package.<template> <name> --<option>=<answer> answers it, and the answer renders the template's files as the variable variable. A template that extends this one's template takes the option too, unless it fixes the answer under fixes.

Attributes:

Name Type Description
name str

The option's name on the command line, in kebab-case.

doc str

One line saying what the answer decides.

choices tuple[str, ...]

The answers it takes; empty for an option with a type.

type str

The type of its answer, str, int or bool; str for an option with choices.

default Answer | None

The answer when the command line gives none; None for a required option.

Methods:

Name Description
refusal

Why answer does not answer this option; empty when it does.

name instance-attribute

name: str

doc instance-attribute

doc: str

choices instance-attribute

choices: tuple[str, ...]

type instance-attribute

type: str

default instance-attribute

default: Answer | None

variable property

variable: str

The template variable the answer renders as: the name, snake-cased.

required property

required: bool

Whether a birth needs an answer: an option without a default does.

refusal

refusal(answer: object) -> str

Why answer does not answer this option; empty when it does.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def refusal(self, answer: object) -> str:
    """Why *answer* does not answer this option; empty when it does."""
    if self.choices:
        if answer in self.choices:
            return ""
        return (
            f"--{self.name} is {answer!r}, which is not one of its choices:"
            f" {', '.join(self.choices)}"
        )
    wanted = OPTION_TYPES[self.type]
    if isinstance(answer, wanted) and (wanted is bool or type(answer) is not bool):
        return ""
    return f"--{self.name} is {answer!r}, which is no {self.type}"

DeclaredTemplate dataclass

DeclaredTemplate(name: str, extension: str, doc: str, extensions: tuple[str, ...], extends: str, path: Path, options: tuple[TemplateOption, ...] = (), fixes: tuple[tuple[str, Answer], ...] = ())

A template a declaration file declares under [templates.<name>].

fm new.package.<name> <package> creates a package from it: the files of the template it extends first, then its own, which live under content/templates/<name>/ beside the file that declares it.

Attributes:

Name Type Description
name str

The template's name, the last word of its verb.

extension str

The extension that declares it, or the base.

doc str

One line saying what a package born from it is.

extensions tuple[str, ...]

The extensions a package born from it lists.

extends str

The template whose files a birth writes first; empty for none.

path Path

The file that declares it.

options tuple[TemplateOption, ...]

The creation options it declares beside those of the templates it extends.

fixes tuple[tuple[str, Answer], ...]

Each option of a template it extends to the answer it gives it, in declaration order: a birth from this template takes no answer for it.

name instance-attribute

name: str

extension instance-attribute

extension: str

doc instance-attribute

doc: str

extensions instance-attribute

extensions: tuple[str, ...]

extends instance-attribute

extends: str

path instance-attribute

path: Path

options class-attribute instance-attribute

options: tuple[TemplateOption, ...] = ()

fixes class-attribute instance-attribute

fixes: tuple[tuple[str, Answer], ...] = ()

directory

directory(package: str) -> Path | None

Where package lives, found without importing it; None when it is absent.

The directory that carries the declaration file when several hold the package's parts, as a namespace's portions do. Found once per import path, since a mount asks for each extension's several times; an absence is never kept, so a package installed later is found.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def directory(package: str) -> Path | None:
    """Where *package* lives, found without importing it; None when it is absent.

    The directory that carries the declaration file when several hold
    the package's parts, as a namespace's portions do. Found once per
    import path, since a mount asks for each extension's several times;
    an absence is never kept, so a package installed later is found.
    """
    key = (package, tuple(sys.path))
    if key in _LOCATED:
        return _LOCATED[key]
    found = _locate(package)
    if found is not None:
        _LOCATED[key] = found
    return found

declaration_file

declaration_file(package: str) -> Path | None

package's declaration file; None when the package or its file is absent.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def declaration_file(package: str) -> Path | None:
    """*package*'s declaration file; None when the package or its file is absent."""
    found = directory(package)
    if found is None or not (found / FILE).is_file():
        return None
    return found / FILE

read

read(extension: str, package: str) -> Declaration | None

extension's declaration, from the file beside package; None without one.

A [for.<target>] table is read while an installed distribution ships the target's declaration, since its steps and answers name what the target declares; until then it adds nothing. Judged once per content and per set of targets read: the result is kept by the file's text and those targets.

Raises:

Type Description
DeclarationError

when the file does not parse, a key is unknown or of the wrong type, or a reference does not resolve.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def read(extension: str, package: str) -> Declaration | None:
    """*extension*'s declaration, from the file beside *package*; None without one.

    A ``[for.<target>]`` table is read while an installed distribution
    ships the target's declaration, since its steps and answers name
    what the target declares; until then it adds nothing. Judged once
    per content and per set of targets read: the result is kept by the
    file's text and those targets.

    Raises:
        DeclarationError: when the file does not parse, a key is unknown
            or of the wrong type, or a reference does not resolve.
    """
    from livery.workshop._extensions import ships_declaration

    path = declaration_file(package)
    if path is None:
        return None
    text = path.read_text("utf-8")
    readable = frozenset(
        str(target)
        for target in _parsed(path, text).get("for", {})
        if ships_declaration(str(target))
    )
    key = (extension, package, path, text, readable)
    found = _CACHE.get(key)
    if found is None:
        found = _read(extension, package, path, text, readable)
        _CACHE[key] = found
    return found

phase_specs_of

phase_specs_of(data: dict[str, Any], path: Path, *, extension: str) -> dict[str, PhaseSpec]

The phases data's [phases.<phase>] tables declare, judged, by name.

A table declares its phase when it carries level, gated, after, verb or keys; one that adds steps alone declares nothing. The same reader serves the base's contract file and an extension's declaration file, extension naming the declarer.

Raises:

Type Description
DeclarationError

when a declaration is off its shape: a level that is not package or workspace, a key of a type no context value has, or a value of the wrong type.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def phase_specs_of(
    data: dict[str, Any], path: Path, *, extension: str
) -> dict[str, PhaseSpec]:
    """The phases *data*'s ``[phases.<phase>]`` tables declare, judged, by name.

    A table declares its phase when it carries ``level``, ``gated``,
    ``after``, ``verb`` or ``keys``; one that adds steps alone declares
    nothing. The same reader serves the base's contract file and an
    extension's declaration file, *extension* naming the declarer.

    Raises:
        DeclarationError: when a declaration is off its shape: a level
            that is not ``package`` or ``workspace``, a key of a type
            no context value has, or a value of the wrong type.
    """
    from livery.workshop._contract_keys import shown
    from livery.workshop._phases import LEVELS, PACKAGE_LEVEL, TYPES, PhaseSpec

    def refuse(where: tuple[str, ...], text: str) -> DeclarationError:
        return DeclarationError(f"{path}: {shown(where)} {text}")

    found: dict[str, PhaseSpec] = {}
    phases = data.get("phases")
    if not isinstance(phases, dict):
        return found
    for name, table in cast("dict[str, Any]", phases).items():
        if not isinstance(table, dict):
            continue
        entry = cast("dict[str, Any]", table)
        if not any(key in entry for key in _DECLARATION_KEYS):
            continue
        where = ("phases", name)
        level = entry.get("level", PACKAGE_LEVEL)
        if level not in LEVELS:
            raise refuse(
                (*where, "level"),
                f"is {level!r}; a phase runs at one of {', '.join(LEVELS)}",
            )
        for key in ("gated", "verb"):
            if not isinstance(entry.get(key, False), bool):
                raise refuse((*where, key), "is true or false")
        after = entry.get("after", [])
        if not isinstance(after, list) or not all(
            isinstance(item, str) for item in cast("list[object]", after)
        ):
            raise refuse((*where, "after"), "is a list of the phases this one follows")
        keys = entry.get("keys", {})
        if not isinstance(keys, dict):
            raise refuse(
                (*where, "keys"), "is a table of the engine's keys, each to its type"
            )
        typed = cast("dict[str, Any]", keys)
        for key, kind in typed.items():
            if kind not in TYPES:
                raise refuse(
                    (*where, "keys", key),
                    f"is {kind!r}; a key's type is one of {', '.join(TYPES)}",
                )
        found[name] = PhaseSpec(
            name,
            keys={key: str(kind) for key, kind in typed.items()},
            level=str(level),
            gated=bool(entry.get("gated", False)),
            after=tuple(str(item) for item in cast("list[object]", after)),
            verb=bool(entry.get("verb", False)),
            extension=extension,
        )
    return found

phase_declarations

phase_declarations(extension: str, package: str) -> tuple[PhaseSpec, ...]

The phases the declaration beside package declares, for extension.

Empty without a declaration file. Read without judging the rest of the file, and without importing anything, so every installed extension's phases are known before any declaration is judged.

Raises:

Type Description
DeclarationError

when the file does not parse or a phase's declaration is off its shape.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def phase_declarations(extension: str, package: str) -> tuple[PhaseSpec, ...]:
    """The phases the declaration beside *package* declares, for *extension*.

    Empty without a declaration file. Read without judging the rest of
    the file, and without importing anything, so every installed
    extension's phases are known before any declaration is judged.

    Raises:
        DeclarationError: when the file does not parse or a phase's
            declaration is off its shape.
    """
    path = declaration_file(package)
    if path is None:
        return ()
    data = _parsed(path, path.read_text("utf-8"))
    return tuple(phase_specs_of(data, path, extension=extension).values())

query_specs_of

query_specs_of(data: dict[str, Any], path: Path, *, extension: str, package: str) -> dict[str, QuerySpec]

The queries data's [queries.<name>] tables declare, judged, by name.

A table declares its query when it carries combine, level, default or values; one carrying value answers a query instead. The same reader serves the base's contract file and an extension's declaration file, extension naming the declarer and package the package a combine function lives in.

Raises:

Type Description
DeclarationError

when a declaration is off its shape: a combine that is no rule and no reference, a level that is not package or workspace, values that are no list, or a table that declares and answers at once.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def query_specs_of(
    data: dict[str, Any], path: Path, *, extension: str, package: str
) -> dict[str, QuerySpec]:
    """The queries *data*'s ``[queries.<name>]`` tables declare, judged, by name.

    A table declares its query when it carries ``combine``, ``level``,
    ``default`` or ``values``; one carrying ``value`` answers a query
    instead. The same reader serves the base's contract file and an
    extension's declaration file, *extension* naming the declarer and
    *package* the package a ``combine`` function lives in.

    Raises:
        DeclarationError: when a declaration is off its shape: a
            ``combine`` that is no rule and no reference, a level that
            is not ``package`` or ``workspace``, ``values`` that are no
            list, or a table that declares and answers at once.
    """
    from livery.workshop._queries import LEVELS, PACKAGE_LEVEL, RULES, UNION, QuerySpec

    reader = _Reader(extension, package, path)
    found: dict[str, QuerySpec] = {}
    queries = data.get("queries")
    if not isinstance(queries, dict):
        return found
    for name, table in cast("dict[str, Any]", queries).items():
        if not _declares_query(table):
            continue
        entry = cast("dict[str, Any]", table)
        where = ("queries", name)
        if "value" in entry:
            raise reader.refuse(
                where,
                "declares the query and answers it in one table; a declaration"
                " takes default for the answer while nobody answers",
            )
        rule = entry.get("combine", UNION)
        if isinstance(rule, str) and rule in RULES:
            combine: str | Reference = rule
        elif isinstance(rule, str) and ":" in rule:
            combine = reader.reference(rule, (*where, "combine"))
        else:
            rules = ", ".join(repr(known) for known in RULES)
            raise reader.refuse(
                (*where, "combine"),
                f"is {rule!r}; a query combines its answers by {rules}, or a"
                " function 'module:name'",
            )
        level = entry.get("level", PACKAGE_LEVEL)
        if level not in LEVELS:
            raise reader.refuse(
                (*where, "level"),
                f"is {level!r}; a query is asked at one of {', '.join(LEVELS)}",
            )
        values = entry.get("values")
        if values is not None and not isinstance(values, list):
            raise reader.refuse(
                (*where, "values"), "is a list of the answers the query takes"
            )
        found[name] = QuerySpec(
            name,
            combine,
            level=str(level),
            default=entry.get("default"),
            values=tuple(cast("list[object]", values)) if values is not None else None,
            extension=extension,
        )
    return found

query_declarations

query_declarations(extension: str, package: str) -> tuple[QuerySpec, ...]

The queries the declaration beside package declares, for extension.

Empty without a declaration file. Read without judging the rest of the file, and without importing anything, so every installed extension's queries are known before any declaration is judged.

Raises:

Type Description
DeclarationError

when the file does not parse or a query's declaration is off its shape.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def query_declarations(extension: str, package: str) -> tuple[QuerySpec, ...]:
    """The queries the declaration beside *package* declares, for *extension*.

    Empty without a declaration file. Read without judging the rest of
    the file, and without importing anything, so every installed
    extension's queries are known before any declaration is judged.

    Raises:
        DeclarationError: when the file does not parse or a query's
            declaration is off its shape.
    """
    path = declaration_file(package)
    if path is None:
        return ()
    data = _parsed(path, path.read_text("utf-8"))
    return tuple(
        query_specs_of(data, path, extension=extension, package=package).values()
    )

template_specs_of

template_specs_of(data: dict[str, Any], path: Path, *, extension: str) -> dict[str, DeclaredTemplate]

The templates data's [templates.<name>] tables declare, judged, by name.

The same reader serves the base's contract file and an extension's declaration file, extension naming the declarer. doc and extensions are required; extends, options and fixes are optional, and a table takes nothing else.

Raises:

Type Description
DeclarationError

when a template is off its shape: a name that is not lower-case letters, digits and hyphens, a key it does not take, a missing doc or extensions, a value of the wrong type, or an option or a fixed answer off its shape.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def template_specs_of(
    data: dict[str, Any], path: Path, *, extension: str
) -> dict[str, DeclaredTemplate]:
    """The templates *data*'s ``[templates.<name>]`` tables declare, judged, by name.

    The same reader serves the base's contract file and an extension's
    declaration file, *extension* naming the declarer. ``doc`` and
    ``extensions`` are required; ``extends``, ``options`` and ``fixes``
    are optional, and a table takes nothing else.

    Raises:
        DeclarationError: when a template is off its shape: a name that
            is not lower-case letters, digits and hyphens, a key it does
            not take, a missing ``doc`` or ``extensions``, a value of the
            wrong type, or an option or a fixed answer off its shape.
    """
    reader = _Reader(extension, extension, path)
    found: dict[str, DeclaredTemplate] = {}
    templates = data.get("templates")
    if templates is None:
        return found
    if not isinstance(templates, dict):
        raise reader.refuse(
            ("templates",), "is a table of templates, each [templates.<name>]"
        )
    for name, table in cast("dict[str, Any]", templates).items():
        where = ("templates", name)
        if not _TEMPLATE_NAME.fullmatch(name):
            raise reader.refuse(
                where,
                "is no template name: lower-case letters, digits and hyphens,"
                " starting with a letter, as fm new.package.<template> spells it",
            )
        if not isinstance(table, dict):
            raise reader.refuse(
                where, "is a table: doc, extensions, extends, options and fixes"
            )
        entry = cast("dict[str, Any]", table)
        for key in entry:
            if key not in _TEMPLATE_KEYS:
                raise reader.refuse(
                    (*where, key),
                    "is not a key of a template: it takes doc, extensions,"
                    " extends, options and fixes",
                )
        doc = entry.get("doc")
        if doc is None:
            raise reader.refuse(
                (*where, "doc"),
                "is missing: one line saying what a package born from the"
                " template is, which the template's verb shows as its help",
            )
        if not isinstance(doc, str) or not doc.strip():
            raise reader.refuse(
                (*where, "doc"),
                "is one line of text saying what a package born from the template is",
            )
        listed = entry.get("extensions")
        if listed is None:
            raise reader.refuse(
                (*where, "extensions"),
                "is missing: the extensions a package born from the template"
                " lists, [] for none",
            )
        if not isinstance(listed, list) or not all(
            isinstance(item, str) for item in cast("list[object]", listed)
        ):
            raise reader.refuse((*where, "extensions"), "is a list of extensions")
        extends = entry.get("extends", "")
        if not isinstance(extends, str):
            raise reader.refuse((*where, "extends"), "is a template's name")
        found[name] = DeclaredTemplate(
            name,
            extension,
            doc.strip(),
            tuple(cast("list[str]", listed)),
            extends,
            path,
            _option_specs(reader, where, entry.get("options")),
            _fix_specs(reader, where, entry.get("fixes")),
        )
    return found

template_declarations

template_declarations(extension: str, package: str) -> tuple[DeclaredTemplate, ...]

The templates the declaration beside package declares, for extension.

Empty without a declaration file. Read without judging the rest of the file, and without importing anything, so an installed extension's templates are known whether a workspace lists it or not.

Raises:

Type Description
DeclarationError

when the file does not parse or a template is off its shape.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def template_declarations(extension: str, package: str) -> tuple[DeclaredTemplate, ...]:
    """The templates the declaration beside *package* declares, for *extension*.

    Empty without a declaration file. Read without judging the rest of
    the file, and without importing anything, so an installed
    extension's templates are known whether a workspace lists it or not.

    Raises:
        DeclarationError: when the file does not parse or a template is
            off its shape.
    """
    path = declaration_file(package)
    if path is None:
        return ()
    data = _parsed(path, path.read_text("utf-8"))
    return tuple(template_specs_of(data, path, extension=extension).values())

installed_steps

installed_steps() -> dict[str, str]

Every installed step, <owner>:<phase>.<step>, to the scope it runs at.

The base's own steps, then each installed extension's [phases.<phase>.<step>] tables, its [for.<target>] tables' among them, read without judging the rest of the file and without importing anything. A step of a package-level phase runs once per package; a step of a workspace-level phase at the scope its table names, the workspace when it names none.

Raises:

Type Description
DeclarationError

when a declaration file does not parse.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def installed_steps() -> dict[str, str]:
    """Every installed step, ``<owner>:<phase>.<step>``, to the scope it runs at.

    The base's own steps, then each installed extension's
    ``[phases.<phase>.<step>]`` tables, its ``[for.<target>]`` tables'
    among them, read without judging the rest of the file and without
    importing anything. A step of a package-level phase runs once per
    package; a step of a workspace-level phase at the scope its table
    names, the workspace when it names none.

    Raises:
        DeclarationError: when a declaration file does not parse.
    """
    from livery.footman import installed_entry_points
    from livery.workshop._phases import PACKAGE_LEVEL, declared_phases
    from livery.workshop._steps import PACKAGE, WORKSPACE, snapshot

    builtin = snapshot(initial=True)
    found = {
        f"{record.extension}:{record.name}": record.scope for record in builtin.values()
    }
    phases = declared_phases()
    for entry in installed_entry_points("workshop.extensions"):
        path = declaration_file(entry.value.partition(":")[0])
        if path is None:
            continue
        data = _parsed(path, path.read_text("utf-8"))
        targets = data.get("for", {})
        tables = [data]
        if isinstance(targets, dict):
            tables += [
                cast("dict[str, Any]", table)
                for table in cast("dict[str, Any]", targets).values()
                if isinstance(table, dict)
            ]
        for table in tables:
            held = table.get("phases", {})
            if not isinstance(held, dict):
                continue
            for phase, steps in cast("dict[str, Any]", held).items():
                if not isinstance(steps, dict):
                    continue
                spec = phases.get(phase)
                per_package = spec is not None and spec.level == PACKAGE_LEVEL
                for step, declared in _step_tables(
                    cast("dict[str, Any]", steps)
                ).items():
                    scope = (
                        PACKAGE
                        if per_package
                        else str(declared.get("scope", WORKSPACE))
                    )
                    found[f"{entry.name}:{phase}.{step}"] = scope
    return found

top_level_names

top_level_names(path: Path) -> frozenset[str]

The names path's module defines at its top level, read from its source.

Its functions, classes, assignments and imports, those inside a top-level if or try among them. Parsed once per content.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def top_level_names(path: Path) -> frozenset[str]:
    """The names *path*'s module defines at its top level, read from its source.

    Its functions, classes, assignments and imports, those inside a
    top-level ``if`` or ``try`` among them. Parsed once per content.
    """
    text = path.read_text("utf-8")
    key = (path, text)
    found = _DEFINED.get(key)
    if found is None:
        tree = ast.parse(text, filename=str(path))
        found = frozenset(_defined(tree.body))
        _DEFINED[key] = found
    return found

defined_tasks

defined_tasks(directory: Path) -> frozenset[str]

The tasks the modules under directory define, <group>.<task>, read by AST.

The names task_docs reads, without their doc lines.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def defined_tasks(directory: Path) -> frozenset[str]:
    """The tasks the modules under *directory* define, ``<group>.<task>``, read by AST.

    The names `task_docs` reads, without their doc lines.
    """
    return frozenset(task_docs(directory))

task_docs

task_docs(directory: Path) -> dict[str, str]

Each task the modules under directory define to its doc line, read by AST.

A task is named <group>.<task>. Its doc line is the first line of the function's docstring, which footman shows as the verb's help; empty for a function without one. A module-level <name> = group("<group>") defines a group, and <name> = <parent>.group("<sub>") one beneath another. A function decorated @<name>.task defines a task in that group, named by the decorator's name= or else as footman names it: the function's name, a trailing underscore dropped, underscores as dashes. A group another module defines is followed through from ... import. Nothing is imported.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def task_docs(directory: Path) -> dict[str, str]:
    """Each task the modules under *directory* define to its doc line, read by AST.

    A task is named ``<group>.<task>``. Its doc line is the first line
    of the function's docstring, which footman shows as the verb's
    help; empty for a function without one. A module-level
    ``<name> = group("<group>")`` defines a group, and
    ``<name> = <parent>.group("<sub>")`` one beneath another. A function
    decorated ``@<name>.task`` defines a task in that group, named by
    the decorator's ``name=`` or else as footman names it: the
    function's name, a trailing underscore dropped, underscores as
    dashes. A group another module defines is followed through
    ``from ... import``. Nothing is imported.
    """
    package = ".".join(directory.parts[-1:])
    modules: dict[str, ast.Module] = {}
    for path in sorted(directory.rglob("*.py")):
        relative = path.relative_to(directory).with_suffix("")
        dotted = ".".join(part for part in relative.parts if part != "__init__")
        modules[dotted] = ast.parse(path.read_text("utf-8"), filename=str(path))
    groups: dict[tuple[str, str], str] = {}
    for _round in range(2):
        for dotted, tree in modules.items():
            for node in tree.body:
                found = _group_assigned(node, dotted, groups)
                if found is not None:
                    groups[(dotted, found[0])] = found[1]
    for dotted, tree in modules.items():
        for node in tree.body:
            if isinstance(node, ast.ImportFrom) and node.module is not None:
                source = node.module.rpartition(f"{package}.")[2]
                for alias in node.names:
                    group = groups.get((source, alias.name))
                    if group is not None:
                        groups.setdefault((dotted, alias.asname or alias.name), group)
    tasks: dict[str, str] = {}
    for dotted, tree in modules.items():
        for node in tree.body:
            if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
                continue
            for decorator in node.decorator_list:
                call = decorator if isinstance(decorator, ast.Call) else None
                target = call.func if call is not None else decorator
                if not (
                    isinstance(target, ast.Attribute)
                    and target.attr == "task"
                    and isinstance(target.value, ast.Name)
                ):
                    continue
                group = groups.get((dotted, target.value.id))
                if group is None:
                    continue
                named = next(
                    (
                        keyword.value.value
                        for keyword in (call.keywords if call is not None else ())
                        if keyword.arg == "name"
                        and isinstance(keyword.value, ast.Constant)
                        and isinstance(keyword.value.value, str)
                    ),
                    node.name.rstrip("_").replace("_", "-"),
                )
                doc = (ast.get_docstring(node) or "").strip()
                tasks[f"{group}.{named}"] = doc.splitlines()[0] if doc else ""
    return tasks

contract_keys

contract_keys(package: str) -> tuple[Declared, ...]

The contract keys the declaration beside package owns; empty without one.

Read without judging the rest of the file, and without importing anything: the contract judge asks every installed extension.

Raises:

Type Description
DeclarationError

when the file does not parse or a key's declaration is malformed.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def contract_keys(package: str) -> tuple[Declared, ...]:
    """The contract keys the declaration beside *package* owns; empty without one.

    Read without judging the rest of the file, and without importing
    anything: the contract judge asks every installed extension.

    Raises:
        DeclarationError: when the file does not parse or a key's
            declaration is malformed.
    """
    path = declaration_file(package)
    if path is None:
        return ()
    return contract_keys_of(_parsed(path, path.read_text("utf-8")), path)

contract_keys_of

contract_keys_of(data: dict[str, Any], path: Path, *, contracts: tuple[str, ...] = CONTRACTS) -> tuple[Declared, ...]

The contract keys data's [contract] tables declare, judged.

contracts are the contracts the file may declare keys in: a workspace's for an extension; the base's own file declares the keys of extension.toml as well.

Source code in packages/workshop/src/livery/workshop/_declaration.py
def contract_keys_of(
    data: dict[str, Any], path: Path, *, contracts: tuple[str, ...] = CONTRACTS
) -> tuple[Declared, ...]:
    """The contract keys *data*'s ``[contract]`` tables declare, judged.

    *contracts* are the contracts the file may declare keys in: a
    workspace's for an extension; the base's own file declares the keys
    of ``extension.toml`` as well.
    """
    found: list[Declared] = []
    for contract, table in data.get("contract", {}).items():
        if contract not in contracts:
            raise DeclarationError(
                f"{path}: [contract.{contract}] names no contract; an extension"
                f" declares keys in {', '.join(contracts)}"
            )
        found += _keys(cast("ContractKind", contract), table, (), path)
    return tuple(found)