Skip to content

livery.workshop._contract_keys

livery.workshop._contract_keys

Which keys a contract may hold, who owns each, and the judge that refuses the rest.

Every key of a workshop.toml is declared by its owner: the base declares its own in contract.toml beside this module, the tool store declares the [toolroom] table in the fragment it ships (livery.toolroom.store.SCHEMA_FRAGMENT), and an extension declares the keys it reads under [contract.<contract>.<table>] in its extension.toml, read without importing the extension. The base's file declares the keys of extension.toml itself as well, the extension contract.

livery.workshop._contract.load_contract judges every contract it reads against the JSON Schema the declarations compose (livery.workshop._schema.composed): a key no owner declares, a key whose owner the root's [workspace] extensions does not list, a value of the wrong type and a value outside its allowed set each refuse, naming the file, the key, what the table takes, and the nearest match.

A path is dotted. * stands for any one name in a table whose keys are the user's (toolroom.modes.*); [] stands for the entries of a list (ci.schedule[].every). A key the user names may hold a dot itself (".vscode/settings.json"): the judge walks a contract's keys one table at a time, so such a key is one name.

Classes:

Name Description
Declared

One key a contract may hold.

Functions:

Name Description
base_contract

The base's contract file, BASE_FILE, parsed once per process.

base_keys

The base's keys, read from its contract.toml, in every contract.

toolroom_keys

The [toolroom] keys the tool store's fragment declares, in every contract.

extension_keys

The keys of extension.toml: the base's and the tool store's alone.

declarations

Every installed owner's declarations, by contract and path.

shown

path dotted, a name holding a dot quoted, as a reader writes it.

judge

The refusals data earns as a contract; empty when it is sound.

listed_extensions

The extensions a root contract lists, by name, the base always among them.

Attributes:

Name Type Description
ContractKind
Type
TYPES tuple[str, ...]
BASE
TOOLROOM
ALWAYS tuple[str, ...]
BASE_FILE

ContractKind module-attribute

ContractKind = Literal['root', 'package', 'extension']

Type module-attribute

Type = Literal['str', 'int', 'number', 'bool', 'strs', 'list', 'table', 'any']

TYPES module-attribute

TYPES: tuple[str, ...] = get_args(Type)

BASE module-attribute

BASE = 'livery.workshop'

TOOLROOM module-attribute

TOOLROOM = 'livery.toolroom.store'

ALWAYS module-attribute

ALWAYS: tuple[str, ...] = (BASE, TOOLROOM)

BASE_FILE module-attribute

BASE_FILE = Path(__file__).with_name('contract.toml')

Declared dataclass

Declared(contract: ContractKind, path: str, types: tuple[Type, ...], values: tuple[str, ...] = (), doc: str = '')

One key a contract may hold.

Attributes:

Name Type Description
contract ContractKind

The contract it belongs in, root, package or extension.

path str

The dotted path, with * and [] as above.

types tuple[Type, ...]

The value types it takes, any one of them.

values tuple[str, ...]

The values it takes, when it takes only some.

doc str

One line saying what the key changes.

contract instance-attribute

contract: ContractKind

path instance-attribute

path: str

types instance-attribute

types: tuple[Type, ...]

values class-attribute instance-attribute

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

doc class-attribute instance-attribute

doc: str = ''

base_contract

base_contract() -> dict[str, Any]

The base's contract file, BASE_FILE, parsed once per process.

The file ships with the workshop and does not change while it runs, so its readers share one parse: the base's keys, phases, queries, tools and templates. The parse is kept by the file's path, so a BASE_FILE that names another file is read afresh. A reader copies what it changes: the parse it gets is the one every reader gets.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
def base_contract() -> dict[str, Any]:
    """The base's contract file, `BASE_FILE`, parsed once per process.

    The file ships with the workshop and does not change while it runs,
    so its readers share one parse: the base's keys, phases, queries,
    tools and templates. The parse is kept by the file's path, so a
    `BASE_FILE` that names another file is read afresh. A reader
    copies what it changes: the parse it gets is the one every reader
    gets.
    """
    return _parsed(BASE_FILE)

base_keys cached

base_keys() -> tuple[Declared, ...]

The base's keys, read from its contract.toml, in every contract.

[for.<target>] in an extension.toml takes every table of the file's top level again but [extension], [for], [contract], [templates] and [env], so the file declares each key once and they are repeated here under for.*.

Raises:

Type Description
DeclarationError

when the file declares a key off the shape an extension's [contract] table has.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
@functools.cache
def base_keys() -> tuple[Declared, ...]:
    """The base's keys, read from its ``contract.toml``, in every contract.

    ``[for.<target>]`` in an ``extension.toml`` takes every table of
    the file's top level again but ``[extension]``, ``[for]``,
    ``[contract]``, ``[templates]`` and ``[env]``, so the file declares
    each key once and they are repeated here under ``for.*``.

    Raises:
        DeclarationError: when the file declares a key off the shape an
            extension's ``[contract]`` table has.
    """
    from livery.workshop._declaration import contract_keys_of

    found = contract_keys_of(
        base_contract(), BASE_FILE, contracts=("root", "package", "extension")
    )
    return found + _mirrored(found)

toolroom_keys cached

toolroom_keys() -> tuple[Declared, ...]

The [toolroom] keys the tool store's fragment declares, in every contract.

extension.toml takes them under for.* again, as it takes the base's: a [for.<target>] table's [toolroom] requires names the tools required while that table applies.

Raises:

Type Description
DeclarationError

when the fragment declares a key off the shape an extension's [contract] table has.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
@functools.cache
def toolroom_keys() -> tuple[Declared, ...]:
    """The ``[toolroom]`` keys the tool store's fragment declares, in every contract.

    ``extension.toml`` takes them under ``for.*`` again, as it takes
    the base's: a ``[for.<target>]`` table's ``[toolroom] requires``
    names the tools required while that table applies.

    Raises:
        DeclarationError: when the fragment declares a key off the shape
            an extension's ``[contract]`` table has.
    """
    import tomllib

    from livery.toolroom.store import SCHEMA_FRAGMENT
    from livery.workshop._declaration import contract_keys_of

    found = contract_keys_of(
        tomllib.loads(SCHEMA_FRAGMENT.read_text("utf-8")),
        SCHEMA_FRAGMENT,
        contracts=("root", "package", "extension"),
    )
    return found + _mirrored(found)

extension_keys cached

extension_keys() -> tuple[Declared, ...]

The keys of extension.toml: the base's and the tool store's alone.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
@functools.cache
def extension_keys() -> tuple[Declared, ...]:
    """The keys of ``extension.toml``: the base's and the tool store's alone."""
    return tuple(
        item
        for item in (*base_keys(), *toolroom_keys())
        if item.contract == "extension"
    )

declarations cached

declarations() -> dict[tuple[ContractKind, str], _Owned]

Every installed owner's declarations, by contract and path.

The base's come from this module and the readers it names, the tool store's from its fragment; every extension's from the [contract] tables of its declaration file, installed or not listed alike, so a key of an unlisted extension is named as that extension's. Two owners declaring one path refuse, naming both.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
@functools.cache
def declarations() -> dict[tuple[ContractKind, str], _Owned]:
    """Every installed owner's declarations, by contract and path.

    The base's come from this module and the readers it names, the
    tool store's from its fragment; every
    extension's from the ``[contract]`` tables of its declaration file,
    installed or not listed alike, so a key of an unlisted extension is
    named as that extension's. Two owners declaring one path refuse,
    naming both.
    """
    from livery.footman import installed_entry_points
    from livery.workshop._declaration import contract_keys

    found: dict[tuple[ContractKind, str], _Owned] = {}

    def take(owner: str, items: tuple[Declared, ...]) -> None:
        for item in items:
            key = (item.contract, item.path)
            if key in found and found[key].owner != owner:
                fail(
                    f"the {item.contract} contract key {item.path} is declared by"
                    f" both {found[key].owner} and {owner}; one owner declares a key"
                )
            found[key] = _Owned(item, owner)

    take(BASE, base_keys())
    take(TOOLROOM, toolroom_keys())
    for entry in installed_entry_points("workshop.extensions"):
        take(entry.name, contract_keys(entry.value))
    return found

shown

shown(path: tuple[str, ...]) -> str

path dotted, a name holding a dot quoted, as a reader writes it.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
def shown(path: tuple[str, ...]) -> str:
    """*path* dotted, a name holding a dot quoted, as a reader writes it."""
    return ".".join(f'"{part}"' if "." in part else part for part in path)

judge

judge(data: dict[str, Any], *, contract: ContractKind, where: str, listed: frozenset[str] | None) -> list[str]

The refusals data earns as a contract; empty when it is sound.

Judged against the contract's composed schema (livery.workshop._schema.composed), the one fm sync writes for the editor, in the judge's words (livery.workshop._schema.problems).

A set that holds an extension no installed distribution declares is judged as None: what that extension requires is unknown until it is installed, so no installed owner's key can be called unlisted. A key no installed owner declares still refuses. The mount names the extension, and fm sync installs it, or refuses naming it, before it renders anything.

Parameters:

Name Type Description Default
data dict[str, Any]

The parsed contract.

required
contract ContractKind

Which contract it is.

required
where str

The file, for the caller's message.

required
listed frozenset[str] | None

The extensions the contract's lists and what they require hold, the base among them; None takes every installed owner as listed.

required

Returns:

Type Description
list[str]

One line per problem, in the contract's order.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
def judge(
    data: dict[str, Any],
    *,
    contract: ContractKind,
    where: str,
    listed: frozenset[str] | None,
) -> list[str]:
    """The refusals *data* earns as a *contract*; empty when it is sound.

    Judged against the contract's composed schema
    ([livery.workshop._schema.composed][]), the one `fm sync` writes
    for the editor, in the judge's words
    ([livery.workshop._schema.problems][]).

    A set that holds an extension no installed distribution declares
    is judged as ``None``: what that extension requires is unknown
    until it is installed, so no installed owner's key can be called
    unlisted. A key no installed owner declares still refuses. The
    mount names the extension, and `fm sync` installs it, or refuses
    naming it, before it renders anything.

    Args:
        data: The parsed contract.
        contract: Which contract it is.
        where: The file, for the caller's message.
        listed: The extensions the contract's lists and what they
            require hold, the base among them; ``None`` takes every
            installed owner as listed.

    Returns:
        One line per problem, in the contract's order.
    """
    from livery.workshop._schema import composed, problems

    del where
    if listed is not None and _not_installed(listed):
        listed = None
    return problems(composed(contract, listed), data)

listed_extensions

listed_extensions(root_data: dict[str, Any]) -> frozenset[str]

The extensions a root contract lists, by name, the base always among them.

An entry is read as livery.workshop._extensions.listing reads it: its name, whatever else the entry carries.

Source code in packages/workshop/src/livery/workshop/_contract_keys.py
def listed_extensions(root_data: dict[str, Any]) -> frozenset[str]:
    """The extensions a root contract lists, by name, the base always among them.

    An entry is read as [livery.workshop._extensions.listing][] reads
    it: its name, whatever else the entry carries.
    """
    names = {BASE}
    workspace = root_data.get("workspace")
    extensions = workspace.get("extensions", []) if isinstance(workspace, dict) else []  # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
    from livery.workshop._extensions import listing

    for entry in extensions if isinstance(extensions, list) else []:  # pyright: ignore[reportUnknownVariableType]
        if isinstance(entry, str):
            names.add(listing(entry).name)
        elif isinstance(entry, dict) and isinstance(entry.get("name"), str):  # pyright: ignore[reportUnknownMemberType]
            names.add(listing(entry["name"]).name)  # pyright: ignore[reportUnknownArgumentType]
    return frozenset(names)