Skip to content

livery.workshop._contract

livery.workshop._contract

Read a workshop contract; its keys are kebab-case, and the read enforces it.

workshop.toml is the workspace contract at the root and a package's contract in its directory. Every reader parses one through livery.workshop._contract.load_contract, or livery.workshop._contract.parse_contract for text already in hand, and a key spelled with an underscore refuses at any depth, naming the key, its kebab-case spelling, and the file to fix. There is no rewrite: a wrong spelling is one edit where the refusal points.

Functions:

Name Description
toml_string

value as a TOML basic string, quotes and escapes included.

kebab

key with every underscore replaced by a hyphen.

underscore_keys

The dotted paths of every key under table spelled with an underscore.

parse_contract

Parse contract text; refuse a key spelled with an underscore.

spelled_list

names as a contract spells a list of them: ["cmake", "conan"].

forget_contracts

Drop every contract this process loaded, so the next load parses again.

unjudged

Load contracts inside the block without judging their keys.

load_contract

Parse the contract at path and judge its keys; a refusal names the file.

read_contract

The contract in directory, its keys judged: the workspace's or a package's.

contract_paths

The root contract and every member's, the ones that exist.

Attributes:

Name Type Description
CONTRACT

CONTRACT module-attribute

CONTRACT = 'workshop.toml'

toml_string

toml_string(value: str) -> str

value as a TOML basic string, quotes and escapes included.

A Windows path carries backslashes, which a basic string must escape; JSON's string syntax is the subset of TOML's that a path or a URL needs, so the JSON encoder is the writer.

Source code in packages/workshop/src/livery/workshop/_contract.py
def toml_string(value: str) -> str:
    """*value* as a TOML basic string, quotes and escapes included.

    A Windows path carries backslashes, which a basic string must
    escape; JSON's string syntax is the subset of TOML's that a
    path or a URL needs, so the JSON encoder is the writer.
    """
    return json.dumps(value)

kebab

kebab(key: str) -> str

key with every underscore replaced by a hyphen.

Source code in packages/workshop/src/livery/workshop/_contract.py
def kebab(key: str) -> str:
    """*key* with every underscore replaced by a hyphen."""
    return key.replace("_", "-")

underscore_keys

underscore_keys(table: dict[str, Any], *, prefix: str = '') -> list[str]

The dotted paths of every key under table spelled with an underscore.

Walks nested tables and arrays of tables, so [[depends]] entries and inline tables are judged like the top level.

Source code in packages/workshop/src/livery/workshop/_contract.py
def underscore_keys(table: dict[str, Any], *, prefix: str = "") -> list[str]:
    """The dotted paths of every key under *table* spelled with an underscore.

    Walks nested tables and arrays of tables, so ``[[depends]]``
    entries and inline tables are judged like the top level.
    """
    found: list[str] = []
    for key, value in table.items():
        path = f"{prefix}{key}"
        if "_" in key:
            found.append(path)
        if isinstance(value, dict):
            found += underscore_keys(value, prefix=f"{path}.")
        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
                    found += underscore_keys(item, prefix=f"{path}.")
    return found

parse_contract

parse_contract(text: str, *, where: str) -> dict[str, Any]

Parse contract text; refuse a key spelled with an underscore.

Parameters:

Name Type Description Default
text str

The contract's TOML.

required
where str

How a refusal names the contract: its path, or the git ref it was read at.

required

Returns:

Type Description
dict[str, Any]

The parsed tables.

Raises:

Type Description
Failed

when text is not TOML, or a key is spelled with an underscore, naming where.

Source code in packages/workshop/src/livery/workshop/_contract.py
def parse_contract(text: str, *, where: str) -> dict[str, Any]:
    """Parse contract *text*; refuse a key spelled with an underscore.

    Args:
        text: The contract's TOML.
        where: How a refusal names the contract: its path, or the git
            ref it was read at.

    Returns:
        The parsed tables.

    Raises:
        Failed: when *text* is not TOML, or a key is spelled with an
            underscore, naming *where*.
    """
    try:
        data = tomllib.loads(text)
    except tomllib.TOMLDecodeError as error:
        fail(f"{where}: not valid TOML: {error}")
    wrong = underscore_keys(data)
    if wrong:
        listed = ", ".join(
            f"{key} (spell it {kebab(key.split('.')[-1])})" for key in wrong
        )
        fail(
            f"{where}: contract keys are kebab-case; found {listed}."
            f" Rename each key in {where}."
        )
    return data

spelled_list

spelled_list(names: tuple[str, ...] | list[str]) -> str

names as a contract spells a list of them: ["cmake", "conan"].

Source code in packages/workshop/src/livery/workshop/_contract.py
def spelled_list(names: tuple[str, ...] | list[str]) -> str:
    """*names* as a contract spells a list of them: ``["cmake", "conan"]``."""
    return "[" + ", ".join(toml_string(name) for name in names) + "]"

forget_contracts

forget_contracts() -> None

Drop every contract this process loaded, so the next load parses again.

Source code in packages/workshop/src/livery/workshop/_contract.py
def forget_contracts() -> None:
    """Drop every contract this process loaded, so the next load parses again."""
    _CONTRACTS.clear()

unjudged

unjudged() -> Generator[None]

Load contracts inside the block without judging their keys.

The sync opens it while it installs the extensions the lists name and no installed distribution declares yet: a key of such an extension has no declaration to be judged by until the install, and the judgement would refuse the very sync that installs it. A load inside the block still refuses a file that is not TOML and a key spelled with an underscore, and keeps nothing for a later load, which judges as usual.

Source code in packages/workshop/src/livery/workshop/_contract.py
@contextmanager
def unjudged() -> Generator[None]:
    """Load contracts inside the block without judging their keys.

    The sync opens it while it installs the extensions the lists name
    and no installed distribution declares yet: a key of such an
    extension has no declaration to be judged by until the install, and
    the judgement would refuse the very sync that installs it. A load
    inside the block still refuses a file that is not TOML and a key
    spelled with an underscore, and keeps nothing for a later load,
    which judges as usual.
    """
    _UNJUDGED[0] += 1
    try:
        yield
    finally:
        _UNJUDGED[0] -= 1

load_contract

load_contract(path: Path) -> dict[str, Any]

Parse the contract at path and judge its keys; a refusal names the file.

A contract is parsed and judged once per process; a later load answers from the first until the file, or one the judgement read, changes. The caller gets its own copy.

A contract under packages/<name>/ or packages/<group>/<name>/ is a package's, judged against the root's set, the extensions its workspace's root contract lists and those they require, and the package's own set, the extensions it lists and those they require. So a package holds the keys of what the root lists and of what it lists itself, and no other package's. Any other is a root contract, judged against the workspace's installed set (livery.workshop._extensions.installed_set): the root's set and every package's. Every problem is listed in one refusal (livery.workshop._contract_keys.judge). Inside an unjudged block a load parses alone and keeps nothing.

Source code in packages/workshop/src/livery/workshop/_contract.py
def load_contract(path: Path) -> dict[str, Any]:
    """Parse the contract at *path* and judge its keys; a refusal names the file.

    A contract is parsed and judged once per process; a later load
    answers from the first until the file, or one the judgement read,
    changes. The caller gets its own copy.

    A contract under ``packages/<name>/`` or ``packages/<group>/<name>/``
    is a package's, judged against the root's set, the extensions its
    workspace's root contract lists and those they require, and the
    package's own set, the extensions it lists and those they require.
    So a package holds the keys of what the root lists and of what it
    lists itself, and no other package's. Any other is a root contract,
    judged against the workspace's installed set
    ([livery.workshop._extensions.installed_set][]): the root's set and
    every package's. Every problem is listed in one refusal
    ([livery.workshop._contract_keys.judge][]). Inside an `unjudged`
    block a load parses alone and keeps nothing.
    """
    import copy

    from livery.workshop._composition import closure
    from livery.workshop._contract_keys import judge, listed_extensions
    from livery.workshop._extensions import (
        installed_declaration,
        installed_set,
        listing,
    )

    workspace = _package_workspace(path)
    if _UNJUDGED[0]:
        return parse_contract(path.read_text("utf-8"), where=str(path))
    key = _contract_key(path, workspace)
    held = _CONTRACTS.get(key)
    if held is not None:
        return copy.deepcopy(held)
    data = parse_contract(path.read_text("utf-8"), where=str(path))
    if workspace is not None:
        root = workspace / CONTRACT
        listed = None
        if root.is_file():
            own = data.get("extensions")
            entries = [str(name) for name in own] if isinstance(own, list) else []
            names = [
                *listed_extensions(_root_tables(root)),
                *(listing(entry).name for entry in entries),
            ]
            listed = frozenset(closure(names, installed_declaration))
        problems = judge(data, contract="package", where=str(path), listed=listed)
    else:
        listed = listed_extensions(data) | set(installed_set(path.parent))
        problems = judge(data, contract="root", where=str(path), listed=listed)
    if problems:
        fail(f"{path}:\n" + "\n".join(f"  {line}" for line in problems))
    _CONTRACTS[key] = copy.deepcopy(data)
    return data

read_contract

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

The contract in directory, its keys judged: the workspace's or a package's.

directory is the workspace root or a package's directory, and the contract is its workshop.toml. A package's contract is judged against the extensions the workspace lists, the root's against its own list, so a key of an extension the workspace does not list refuses naming the extension.

Raises:

Type Description
Failed

when the contract holds a key no listed extension and not the workshop declares, or a value of the wrong type, naming the file and every such key.

FileNotFoundError

when directory holds no contract.

Source code in packages/workshop/src/livery/workshop/_contract.py
def read_contract(directory: Path) -> dict[str, Any]:
    """The contract in *directory*, its keys judged: the workspace's or a package's.

    *directory* is the workspace root or a package's directory, and the
    contract is its ``workshop.toml``. A package's contract is judged
    against the extensions the workspace lists, the root's against its
    own list, so a key of an extension the workspace does not list
    refuses naming the extension.

    Raises:
        Failed: when the contract holds a key no listed extension and
            not the workshop declares, or a value of the wrong type,
            naming the file and every such key.
        FileNotFoundError: when *directory* holds no contract.
    """
    return load_contract(directory / CONTRACT)

contract_paths

contract_paths(root: Path) -> list[Path]

The root contract and every member's, the ones that exist.

Source code in packages/workshop/src/livery/workshop/_contract.py
def contract_paths(root: Path) -> list[Path]:
    """The root contract and every member's, the ones that exist."""
    paths = [root / CONTRACT]
    packages = root / "packages"
    if packages.is_dir():
        found: list[Path] = []
        for directory in (p for p in packages.iterdir() if p.is_dir()):
            if (directory / CONTRACT).is_file():
                found.append(directory / CONTRACT)
            else:
                # A group directory: its packages are one level down.
                found += (p / CONTRACT for p in directory.iterdir() if p.is_dir())
        paths += sorted(found)
    return [path for path in paths if path.is_file()]