Skip to content

livery.workshop

livery.workshop

The livery ecosystem's devkit.

The task surface arrives through the footman plugin (plugin("livery.workshop")); this module's own API is the extension walk (livery.workshop.extension_names, livery.workshop.workspace_root), the package contracts (livery.workshop.discover_packages, livery.workshop.verify_workspace over livery.workshop.Package and livery.workshop.Edge). The forge lane belongs to livery.forge.Forge; the workshop orchestrates local, git, and forge steps and never hands a raw forge verb to a user.

An extension in its own wheel declares itself in an extension.toml beside the package its workshop.extensions entry point names: the steps it adds to the gate's phases under [phases.<phase>.<step>], each with its body under main, a template of its tool's words with {paths} where the paths the run reaches go and {arguments} where the words after -- go, or the function that runs it as "module:function". A step in code takes a livery.workshop.PhaseContext. One that narrows by paths reads them from livery.workshop.scoped_paths, which answers livery.workshop.WHOLE for the tool's configured whole, and calls its tool through livery.workshop.run_batched; a workspace step that declares no inputs narrows by packages and reads them from livery.workshop.scoped_packages, and one that judges a package at a time (scope = "package") reads its files from livery.workshop.scoped_files. One that declares inputs judges the whole workspace in every scope, and asks livery.workshop.selected_files which of them this run's change touched, with the context its run was handed; its widen reference receives the run's livery.workshop.Changes. A step declares the options a package may set on it under its options and reads a package's value with livery.workshop.step_option, which answers from the installed declaration in a process that mounted nothing. A step names the extensions it judges packages by, livery.workshop.step_extensions, and judges a package whose set holds one of them: the extensions it lists and every one they require, livery.workshop.extension_set. A step declared enabled = false registers once the root contract turns it on at the step's address, which livery.workshop.step_enabled answers. A step asks a package's extensions what it needs of the package with livery.workshop.answer: the modules a type-completeness step verifies, livery.workshop.PUBLIC_MODULES, or where the package's build writes the compilation database a linter reads, livery.workshop.COMPILE_COMMANDS. The workspace's own tests, the tests directory at its root, are a unit of their own, livery.workshop.workspace_suite, which holds the root's set. A test step runs them beside the packages it judges while that set holds an extension the step names: livery.workshop.scoped_suite returns the unit then. A step whose tool of the store is not on PATH refuses with livery.workshop.undeployed: the refusal names the tool and the sync that deploys it.

An extension reads the workspace through the names the engine reads it by: the root of the workspace a package is a member of, livery.workshop.Package.root; a contract's judged keys, livery.workshop.read_contract; a query's answer, livery.workshop.answer, asked with a package or the workspace root through a livery.workshop.Query handle; the CI run it belongs to, livery.workshop.ci_run, a livery.workshop.RunContext or None at a desk; the workspace's repository on its forge, livery.workshop.forge_repository, and, connected, livery.workshop.this_repository on livery.workshop.this_forge, whose everyday token livery.workshop.forge_token resolves; the registry an artifact kind goes to, livery.workshop.registry, a livery.workshop.RegistryTarget, which a step of the publish phase reads from its registry-target key with livery.workshop.RegistryTarget.from_table; and the release notes' provider the listed extensions answer, livery.workshop.release_notes, which answers the livery.workshop.ReleaseNotes protocol. A file an extension writes outside the engine opens with livery.workshop.generated_header. What a CI run changed against the base it measures from is livery.workshop.ci_changes. The guidance for one reader, livery.workshop.AGENT or livery.workshop.HUMAN, is the composed set of livery.workshop.Prose fragments livery.workshop.guidance answers; each listed extension's shipped files live where livery.workshop.shipped_content says; the gate's fixers run over named files through livery.workshop.fix_files, and a phase's steps over named packages through livery.workshop.run_phase_over; and what the listed extensions declare for an extension is livery.workshop.contributions_for. A phase the gate never runs, one declared gated = false, runs over the workspace through livery.workshop.run_phase, which first removes what a step that stopped running declared it writes under outputs. The members come in release order from livery.workshop.order_topologically, every dependency before its dependents, and livery.workshop.release_tag reads the member and the version a release tag names. A query's combine function that decides between answers by what each answering extension requires hands the lookup it is called with to livery.workshop.nearest_extensions.

An extension that keeps records of a CI run reaches them through the names the gate's own records use. The workshop's series live on the checkout's state store, livery.workshop.state_store; on it, livery.workshop.RUNS keeps each check leg's files for one run until the gate job collects them. A check leg's entry leaves a file for the leg's one write with livery.workshop.leave_leg_file, and reads what the gate ran on the leg, a livery.workshop.LegScope, from livery.workshop.leg_scope. The gate job's entry leaves a section of the run's row with livery.workshop.leave_section. The branch whose run proved the checkout's tree, a livery.workshop.VerifiedBranch, is what livery.workshop.verified_branch reads. The check legs the gate produces are livery.workshop.check_legs, and those a pull request's run produces are livery.workshop.pull_request_legs, unless the pull request carries livery.workshop.EVERY_RUNNER_LABEL, when its run produces every leg; split into the shards the contract gives each runner they are livery.workshop.check_shards and livery.workshop.pull_request_shards, each shard spelled by a livery.workshop.Shard at the end of its label, which livery.workshop.platform_leg and livery.workshop.shard_of split. A shard's share of the items a test step partitions, pytest's test files, is what livery.workshop.partition packs from the medians livery.workshop.read_durations takes over the platform leg's rows in the livery.workshop.DURATIONS family, bounded by livery.workshop.checkout_time; the set it partitioned has the digest livery.workshop.files_digest, and the shard leaves what it ran with livery.workshop.leave_shard, a livery.workshop.ShardMarker that livery.workshop.read_shard reads back. Of a set of units, each a member's suite or the workspace's own tests at livery.workshop.WORKSPACE_TESTS, livery.workshop.tested keeps those a test step runs. Whether a package holds the extension of the workshop's own language is livery.workshop.holds_runtime_language, and what a path is to its package, a livery.workshop.Category, is livery.workshop.category_of.

An extension that builds a release's artifacts in a CI job of its own reaches the release through the names the release train uses. The members a release squash releases, each with its version, are what livery.workshop.discover_release reads at a commit, and livery.workshop.build_release builds one of them as the release train does, into its dist/. The members a job of the release point builds before the wave are the workspace's answer to livery.workshop.JOB_BUILT_MEMBERS. The interpreters the CI matrix runs are livery.workshop.python_matrix. What the checkout installed of each tool is livery.workshop.tool_receipts, a livery.workshop.ToolReceipt per tool, and the tool store's home on this machine is livery.workshop.store_home.

An extension that judges a language's sources reads what each source references from its package's references answer: one livery.workshop.SourceReferences per source, and a livery.workshop.ReferencedName for each name the source references and how it makes the reference. Which member owns a referenced name is what livery.workshop.neighbours answers, a livery.workshop.Neighbours made from each member's module roots. A step over the sources runs over every one of them when livery.workshop.graph_changed says a contract, a native manifest or a root src/ changed.

An extension that runs python in a venv names its interpreter with livery.workshop.venv_python and its executables directory with livery.workshop.scripts_dir. A runner that starts pytest shares two names with the workshop's pytest plugins: livery.workshop.is_example says which files the examples plugin collects as documentation examples, and the speed plugin sums each package's test time into the file the runner names in the variable livery.workshop.SPEED_FILE_VARIABLE. The plugins read three more names of the workshop: the speed plugin sums by the package livery.workshop.package_of names for a test's node id, the points plugin selects the tests of the CI point named in livery.workshop.POINT_VARIABLE, and the layout plugin checks the tests directory of each directory livery.workshop.package_directories lists. Each package's mark on each check leg, a livery.workshop.SpeedMark, is what livery.workshop.speed_marks reads.

An extension adds steps to a package's lifecycle phases under [phases.<phase>.<step>], with the keys every step takes; each runs once per package whose set holds the extension and receives the same livery.workshop.PhaseContext, which carries the keys the steps provide and read. It answers questions about a package under [queries]: each a livery.workshop.Query the workshop defines, such as livery.workshop.PUBLIC_MODULES or livery.workshop.EXECUTABLES, which livery.workshop.answer asks of a package's extensions and combines by the query's rule. Each function it answers requirement-writers with writes a requirement on a sibling into the package's manifest, and is a livery.workshop.RequirementWriter.

Modules:

Name Description
testing

What an extension's steps and categories are judged against: the conformance kit.

Classes:

Name Description
Category

A path's category, and who supplied the rule that answered.

RunContext

The CI run this process belongs to, as the runner's environment names it.

Changes

What changed since the tree a gate measures from.

Edge

One declared dependency edge of a package.

Neighbours

Who owns each name the workspace's members reference each other by.

Package

One package, as its contract declares it.

ReferencedName

One name a source references, and how the source makes the reference.

SourceReferences

What one source references: one record of a package's references answer.

PhaseContext

What a run hands a step: the workspace, the run's scope, and the phase's keys.

Prose

One prose fragment: a file an extension ships, or a render from the registries.

Query

A handle naming a declared query, typed by its answer.

RequirementWriter

Write a package's requirement on a sibling into one ecosystem's manifest.

RegistryTarget

One resolved registry for one artifact kind.

ReleaseNotes

What a release-notes provider answers.

Shard

One shard of a leg: which of how many, spelled <i>of<n>.

ShardMarker

What a shard left in SHARD_FILE: what it ran and what it partitioned from.

SpeedMark

A package's mark on one check leg and the row that set it.

ToolReceipt

What this checkout installed of one tool, as its file records it.

LegScope

What the gate ran on one check leg, as the marker the leg left says.

VerifiedBranch

The branch whose run proved a tree, or why the record could not say.

Functions:

Name Description
category_of

Say what path, relative to package's directory, is to the package.

ci_run

The CI run this process belongs to, or None at a desk.

state_store

Open the state store of the checkout at root, with the workshop's policy.

extension_set

The extensions package holds: its list and every extension the list requires.

nearest_extensions

Of the extensions names, the ones no other of them requires: the nearest.

read_contract

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

is_example

Tell whether path is a documentation example.

contributions_for

What the installed extensions declare for target, by extension.

extension_names

The extensions the workspace installs and mounts, in mount order.

shipped_content

Each extension of the workspace's stack with its content/ directory.

workspace_root

The nearest ancestor carrying the workspace's contract, or None.

forge_repository

This workspace's repository name on its forge: the name origin points at.

this_forge

The workspace's forge, per the contract's [forge] table.

this_repository

The workspace's repository, per the contract and the remote.

order_topologically

packages in release order: every dependency before its dependents.

run_batched

Run call once per batch of paths; one refusal naming every failure.

build_release

Build package's release artifacts into its dist/; that directory.

leave_leg_file

Leave data in the leg's spool as name, for the leg's one write.

leave_section

Leave a section of the run's row, a number per package, for the gate job.

discover_packages

Every package the workspace carries, by its contract, sorted by path.

holds_runtime_language

Say whether package holds the extension of the workshop's own language.

neighbours

Map each module root packages ship to the member that ships it.

package_directories

List every directory under packages/ that should hold a package.

release_tag

The package path and version a release tag names; None for another tag.

verify_workspace

The layering lint: check every workspace invariant, or raise.

workspace_suite

The workspace's own tests, the tests directory at its root, as a unit.

run_phase

Run a phase the gate never runs over the workspace at root; the shared context.

check_legs

Name the check legs the gate produces, check-<os>-<python> each.

check_shards

Name the shard legs the gate produces, split as [ci] shards says.

pull_request_legs

Name the check legs a pull request's run produces, check-<os>-<python> each.

pull_request_shards

Name the shard legs a pull request's run produces, split as the contract says.

guidance

The guidance one reader gets in the workspace at root, in reading order.

generated_header

The provenance header a generated file opens with, as a comment block.

discover_release

The members the release squash at ref releases, each with its version.

python_matrix

The CI matrix: the contract's declaration, else the floor and the newest minor.

scripts_dir

Name venv's executables directory: Scripts on Windows, bin elsewhere.

venv_python

Name venv's interpreter on this platform.

ci_changes

What this CI run changed against the base it measures from; None for everything.

fix_files

Run the gate's fixers over paths, judging nothing.

run_phase_over

Run the steps of phase over packages whole; nothing recorded as proved.

answer

The answer to query about subject: the extensions' answers, combined.

registry

The registry the workspace at root reads and publishes kind artifacts at.

release_notes

The provider the extensions listed at root answer; None when none answers.

checkout_time

The committer time of HEAD's commit in the checkout at root, timezone-aware.

files_digest

A hex digest of the sorted names in files.

leave_shard

Leave the shard's record in SHARD_FILE at root, for the gate job's proof.

partition

Pack items into count shards by their durations, every item in exactly one.

platform_leg

The leg label without its shard; a label without one is returned as it is.

read_durations

The median seconds per item, and the head, of leg's rows before before.

read_shard

Read the record a shard left in SHARD_FILE at root.

shard_of

The shard the leg label ends in; ONE when it ends in none.

package_of

Name the workspace package a test belongs to, from its pytest node id.

speed_marks

Read each package's current test-time mark on each check leg.

graph_changed

Tell whether a contract, a native manifest or a root src/ changed.

scoped_files

The files of package the step name judges in this run, absolute.

scoped_packages

The members the package-narrowing step name judges in this run.

scoped_paths

The paths the path-narrowing step name judges in this run.

scoped_suite

The workspace's own tests, when the step name judges them.

selected_files

The files the running step judges in this run; None for every file it reads.

step_enabled

Whether the step name is on in the workspace at root.

step_extensions

The extensions the step name names in its extensions list.

step_option

What package sets for the step name's option, or the option's default.

tested

Keep the units whose suites a registered step of the test phase runs.

forge_token

The everyday token and the variable that supplied it.

store_home

The tool store's home on this machine, where every checkout's tools are.

tool_receipts

What the checkout at root installed of each tool, by the tool's name.

undeployed

Refuse the task: name is a tool of the store and is not on PATH.

leg_scope

Read what the gate ran on this leg from the marker it left at root.

verified_branch

Read which branch's run proved the tree checked out at root.

Attributes:

Name Type Description
POINT_VARIABLE
RUNS Keyed
WORKSPACE_TESTS
EVERY_RUNNER_LABEL
AGENT
HUMAN
COMPILE_COMMANDS Query[Path | None]
CURRENT_VERSION Query[str]
DISTRIBUTIONS Query[tuple[tuple[str, str], ...]]
EXECUTABLES Query[tuple[str, ...]]
JOB_BUILT_MEMBERS Query[Mapping[str, str]]
MODULE_ROOTS Query[tuple[str, ...]]
PUBLIC_MODULES Query[tuple[str, ...]]
REQUIREMENTS Query[Mapping[str, str]]
VERSION_FILES Query[tuple[Path, ...]]
DURATIONS Keyed
SPEED_FILE_VARIABLE
NONE
PACKAGE
PACKAGES
PATHS
WHOLE
__version__

TYPE_CHECKING module-attribute

TYPE_CHECKING = False

POINT_VARIABLE module-attribute

POINT_VARIABLE = 'WORKSHOP_POINT'

RUNS module-attribute

RUNS: Keyed = git.Keyed('run', ('run', 'leg'), schema=SCHEMA, stale_after=timedelta(hours=6))

WORKSPACE_TESTS module-attribute

WORKSPACE_TESTS = 'tests'

EVERY_RUNNER_LABEL module-attribute

EVERY_RUNNER_LABEL = 'ci:every-runner'

AGENT module-attribute

AGENT = 'agent'

HUMAN module-attribute

HUMAN = 'human'

COMPILE_COMMANDS module-attribute

COMPILE_COMMANDS: Query[Path | None] = Query('compile-commands')

CURRENT_VERSION module-attribute

CURRENT_VERSION: Query[str] = Query('current-version')

DISTRIBUTIONS module-attribute

DISTRIBUTIONS: Query[tuple[tuple[str, str], ...]] = Query('distributions')

EXECUTABLES module-attribute

EXECUTABLES: Query[tuple[str, ...]] = Query('executables')

JOB_BUILT_MEMBERS module-attribute

JOB_BUILT_MEMBERS: Query[Mapping[str, str]] = Query('job-built-members')

MODULE_ROOTS module-attribute

MODULE_ROOTS: Query[tuple[str, ...]] = Query('module-roots')

PUBLIC_MODULES module-attribute

PUBLIC_MODULES: Query[tuple[str, ...]] = Query('public-modules')

REQUIREMENTS module-attribute

REQUIREMENTS: Query[Mapping[str, str]] = Query('requirements')

VERSION_FILES module-attribute

VERSION_FILES: Query[tuple[Path, ...]] = Query('version-files')

DURATIONS module-attribute

DURATIONS: Keyed = git.Keyed('durations', ('leg',), window=WINDOW, schema=SCHEMA, current=_current_legs)

SPEED_FILE_VARIABLE module-attribute

SPEED_FILE_VARIABLE = 'WORKSHOP_SPEED_FILE'

NONE module-attribute

NONE = 'none'

PACKAGE module-attribute

PACKAGE = 'package'

PACKAGES module-attribute

PACKAGES = 'packages'

PATHS module-attribute

PATHS = 'paths'

WHOLE module-attribute

WHOLE = ('.',)

__version__ module-attribute

__version__ = '0.11.0'

__all__ module-attribute

__all__ = ['AGENT', 'COMPILE_COMMANDS', 'CURRENT_VERSION', 'DISTRIBUTIONS', 'DURATIONS', 'EVERY_RUNNER_LABEL', 'EXECUTABLES', 'HUMAN', 'JOB_BUILT_MEMBERS', 'MODULE_ROOTS', 'NONE', 'PACKAGE', 'PACKAGES', 'PATHS', 'POINT_VARIABLE', 'PUBLIC_MODULES', 'REQUIREMENTS', 'RUNS', 'SPEED_FILE_VARIABLE', 'VERSION_FILES', 'WHOLE', 'WORKSPACE_TESTS', 'Category', 'Changes', 'Edge', 'LegScope', 'Neighbours', 'Package', 'PhaseContext', 'Prose', 'Query', 'ReferencedName', 'RegistryTarget', 'ReleaseNotes', 'RequirementWriter', 'RunContext', 'Shard', 'ShardMarker', 'SourceReferences', 'SpeedMark', 'ToolReceipt', 'VerifiedBranch', '__version__', 'answer', 'build_release', 'category_of', 'check_legs', 'check_shards', 'checkout_time', 'ci_changes', 'ci_run', 'contributions_for', 'discover_packages', 'discover_release', 'extension_names', 'extension_set', 'files_digest', 'fix_files', 'forge_repository', 'forge_token', 'generated_header', 'graph_changed', 'guidance', 'holds_runtime_language', 'is_example', 'leave_leg_file', 'leave_section', 'leave_shard', 'leg_scope', 'nearest_extensions', 'neighbours', 'order_topologically', 'package_directories', 'package_of', 'partition', 'platform_leg', 'pull_request_legs', 'pull_request_shards', 'python_matrix', 'read_contract', 'read_durations', 'read_shard', 'registry', 'release_notes', 'release_tag', 'run_batched', 'run_phase', 'run_phase_over', 'scoped_files', 'scoped_packages', 'scoped_paths', 'scoped_suite', 'scripts_dir', 'selected_files', 'shard_of', 'shipped_content', 'speed_marks', 'state_store', 'step_enabled', 'step_extensions', 'step_option', 'store_home', 'tested', 'testing', 'this_forge', 'this_repository', 'tool_receipts', 'undeployed', 'venv_python', 'verified_branch', 'verify_workspace', 'workspace_root', 'workspace_suite']

Category dataclass

Category(name: str, supplier: str, pattern: str)

A path's category, and who supplied the rule that answered.

Attributes:

Name Type Description
name str

The category.

supplier str

The extension whose rule answered, or the package for its own contract's exception.

pattern str

The pattern that matched.

name instance-attribute

name: str

supplier instance-attribute

supplier: str

pattern instance-attribute

pattern: str

RunContext dataclass

RunContext(forge: str, run_id: str, event: str, ref: str, head_sha: str = '', base_ref: str = '', leg: str = '', head_ref: str = '', labels: tuple[str, ...] = (), attempt: str = '')

The CI run this process belongs to, as the runner's environment names it.

Attributes:

Name Type Description
forge str

github, gitea, or gitlab.

run_id str

The forge's identifier of the run (GitLab: the pipeline).

event str

What started the run (push, pull_request, ...).

ref str

The ref the run is for, as the runner spells it.

head_sha str

The commit the forge files the run under. On a pull request the checkout is the merge commit the forge synthesised, and the run's own head is the pull request's head, which the event payload names; on a push both are the same commit. Empty when the runner did not say.

base_ref str

The branch a pull request proposes into, as the event payload names it (GitLab: the merge request's target); empty on a push or when the runner did not say.

leg str

The check leg this process runs in (check-ubuntu-latest-3.14), as the job runner names it in WORKSHOP_LEG for every entry it spawns; empty outside a scheduled job.

head_ref str

The branch a pull request comes from, as the event payload names it (GitLab: the merge request's source), the base of the branch's own coverage record; empty on a push or when the runner did not say.

labels tuple[str, ...]

The pull request's label names, as the event payload names them (GitLab: CI_MERGE_REQUEST_LABELS); empty on a push, on a payload that does not name them, or when the runner did not say.

attempt str

Which attempt of the run this is, as the runner counts them from 1 (GitHub's and Gitea's GITHUB_RUN_ATTEMPT); a rerun of some or all jobs is the next attempt. Empty on GitLab, and when the runner did not say. A shard records it, so the gate job's fold can tell shards of two attempts apart.

forge instance-attribute

forge: str

run_id instance-attribute

run_id: str

event instance-attribute

event: str

ref instance-attribute

ref: str

head_sha class-attribute instance-attribute

head_sha: str = ''

base_ref class-attribute instance-attribute

base_ref: str = ''

leg class-attribute instance-attribute

leg: str = ''

head_ref class-attribute instance-attribute

head_ref: str = ''

labels class-attribute instance-attribute

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

attempt class-attribute instance-attribute

attempt: str = ''

shard property

shard: Shard

The shard the leg runs as, read from the end of leg; one of one without.

check-windows-latest-3.14-2of4 runs as the second of four shards; check-ubuntu-latest-3.14, and an empty leg, as the one shard of one. The label is the only source, so the shard and the leg cannot disagree. A livery.workshop.Shard.

Raises:

Type Description
ValueError

When the label ends in a shard spelling outside the form, such as 0of2, naming it.

Changes dataclass

Changes(root: Path, paths: tuple[str, ...], before: str = '')

What changed since the tree a gate measures from.

Attributes:

Name Type Description
root Path

The workspace root.

paths tuple[str, ...]

The changed paths, root-relative posix, deleted ones included.

before str

The commit or tree the paths were taken from; empty when the caller named the paths itself.

Methods:

Name Description
removed

The changed paths the working tree no longer holds: deleted or moved.

text_before

path where the change is measured from; empty if unknown.

root instance-attribute

root: Path

paths instance-attribute

paths: tuple[str, ...]

before class-attribute instance-attribute

before: str = ''

removed

removed() -> tuple[str, ...]

The changed paths the working tree no longer holds: deleted or moved.

Source code in packages/workshop/src/livery/workshop/_influence.py
def removed(self) -> tuple[str, ...]:
    """The changed paths the working tree no longer holds: deleted or moved."""
    return tuple(path for path in self.paths if not (self.root / path).exists())

text_before

text_before(path: str) -> str

path where the change is measured from; empty if unknown.

Source code in packages/workshop/src/livery/workshop/_influence.py
def text_before(self, path: str) -> str:
    """*path* where the change is measured from; empty if unknown."""
    if not self.before:
        return ""

    return git.file_at(self.root, self.before, path)

Edge dataclass

Edge(path: str, kind: str, floor: str)

One declared dependency edge of a package.

Attributes:

Name Type Description
path str

The dependency's identity: its directory path from the workspace root, as the tags spell it.

kind str

runtime, build, test, or tool. It decides one thing: a runtime or build edge must appear in the native manifest with a constraint carrying its floor, and the other two have no native home. Every edge counts everywhere else, whatever its kind: the acyclicity check, the dependents' closure the gate narrows by, the order the release wave publishes in, and the floor bump.

floor str

The released version the native manifest must require.

path instance-attribute

path: str

kind instance-attribute

kind: str

floor instance-attribute

floor: str

Neighbours dataclass

Neighbours(owners: Mapping[str, str], by_path: Mapping[str, Package])

Who owns each name the workspace's members reference each other by.

livery.workshop.neighbours makes it from the members; a rule over the sources asks it which member a referenced name belongs to.

Attributes:

Name Type Description
owners Mapping[str, str]

Each module root a member ships, to the member's path. Each member's extensions answer its roots (livery.workshop.MODULE_ROOTS), so a reference resolves the same way whichever extension made it.

by_path Mapping[str, Package]

Every member by its path.

Methods:

Name Description
owner_of

The package path owning reference, longest prefix winning.

owners instance-attribute

owners: Mapping[str, str]

by_path instance-attribute

by_path: Mapping[str, Package]

owner_of

owner_of(reference: str) -> str

The package path owning reference, longest prefix winning.

Empty when no package owns it: a third-party name, or the standard library. Longest prefix, because three distributions share the livery.toolroom namespace and the shortest match would attribute two of them to the third.

Source code in packages/workshop/src/livery/workshop/_packages.py
def owner_of(self, reference: str) -> str:
    """The package path owning *reference*, longest prefix winning.

    Empty when no package owns it: a third-party name, or the
    standard library. Longest prefix, because three distributions
    share the ``livery.toolroom`` namespace and the shortest match
    would attribute two of them to the third.
    """
    best = ""
    for prefix in self.owners:
        matches = reference == prefix or reference.startswith(prefix + ".")
        if matches and len(prefix) > len(best):
            best = prefix
    return self.owners[best] if best else ""

Package dataclass

Package(directory: Path, path: str, name: str, depends: tuple[Edge, ...], publish: bool = True, categories: tuple[tuple[str, tuple[str, ...]], ...] = (), step_options: tuple[tuple[str, tuple[tuple[str, object], ...]], ...] = (), extensions: tuple[str, ...] = ())

One package, as its contract declares it.

Attributes:

Name Type Description
directory Path

The package directory.

path str

The identity path from the workspace root (packages/forge, or packages/extensions/widgets for a package in a group directory).

name str

The distribution name (livery-forge).

depends tuple[Edge, ...]

The declared edges, in contract order.

step_options tuple[tuple[str, tuple[tuple[str, object], ...]], ...]

The options the package sets on its steps, by the table that sets them: phases.<phase> (every step of the phase) and phases.<phase>.<step> (one step), each to its (option, value) pairs; the step registry validates them against what the steps they reach declare.

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

The package's own reassignments of its paths among the categories, [categories] vendored = ["docs/assets/vendor/**"]: a fact about the package in the narrow shape a coverage floor has, on the category axis alone, winning over every extension's rule.

publish bool

Whether the release train uploads the package's artifact to its registry. [release] publish = false keeps an internal tool versioned, tagged and built by the train and never uploaded; the default is true.

extensions tuple[str, ...]

The extensions the package lists, in its contract's order: its canonical list, which the extensions it requires complete into its set.

directory instance-attribute

directory: Path

path instance-attribute

path: str

name instance-attribute

name: str

depends instance-attribute

depends: tuple[Edge, ...]

publish class-attribute instance-attribute

publish: bool = True

categories class-attribute instance-attribute

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

step_options class-attribute instance-attribute

step_options: tuple[tuple[str, tuple[tuple[str, object], ...]], ...] = field(default=(), hash=False)

extensions class-attribute instance-attribute

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

member property

member: str

The package's path under packages/: forge, extensions/widgets.

It names the package in a release tag (packages/<member>/v<version>) and everywhere else a package is addressed by its place rather than its distribution name.

root property

root: Path

The root of the workspace the package is a member of.

The package's directory with its path's parts taken off, read from the two fields alone, without touching the disk: the root is two directories above packages/forge, three above packages/extensions/widgets, and one above the workspace's own tests (livery.workshop.workspace_suite). A package whose path is . is at the root, so its directory is the root.

Raises:

Type Description
ValueError

when the directory does not end with the path, naming both.

ReferencedName dataclass

ReferencedName(name: str, lazy: bool = False, type_checking: bool = False, optional: bool = False)

One name a source references, and how the source makes the reference.

A record of livery.workshop.SourceReferences: an extension that answers the references query makes one for each name a source references, once for each way the source makes the reference.

Attributes:

Name Type Description
name str

The dotted name, as the source spells it.

lazy bool

Whether only a function or a method body makes the reference, so importing the source does not.

type_checking bool

Whether only a type checker makes it, so no run of the source does.

optional bool

Whether the source handles the name being absent, so it runs without it.

name instance-attribute

name: str

lazy class-attribute instance-attribute

lazy: bool = False

type_checking class-attribute instance-attribute

type_checking: bool = False

optional class-attribute instance-attribute

optional: bool = False

SourceReferences dataclass

SourceReferences(path: str, module: str = '', references: tuple[ReferencedName, ...] = (), accounted: tuple[str, ...] = ())

What one source references: one record of a package's references answer.

An extension that reads a language's sources answers the references query with one record for each source file of the package, and the layering steps resolve each name to the member that owns it with livery.workshop.neighbours.

Attributes:

Name Type Description
path str

The source, relative to the workspace root, posix: a file inside the package the answer is about.

module str

The name other code references the source by; empty for a source nothing references by name, such as a test.

references tuple[ReferencedName, ...]

Every name the source references, in source order, once for each way the source makes the reference.

accounted tuple[str, ...]

The names among them that the conventions of the source's language account for, so they need no dependency edge.

path instance-attribute

path: str

module class-attribute instance-attribute

module: str = ''

references class-attribute instance-attribute

references: tuple[ReferencedName, ...] = ()

accounted class-attribute instance-attribute

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

PhaseContext dataclass

PhaseContext(root: Path, packages: tuple[Package, ...] = (), subset: tuple[Package, ...] | None = None, tests: Mapping[str, tuple[str, ...]] = dict[str, tuple[str, ...]](), examples: tuple[str, ...] = (), fix: bool = False, files: tuple[str, ...] = (), safe: bool = False, point: str = '', shard: Shard = ONE, catalogue: Mapping[str, tuple[tuple[str, str], ...]] | None = None, package: Package | None = None, selection: tuple[str, ...] = (), changes: Changes | None = None, arguments: tuple[str, ...] = (), step: str = '', phase: str = '', _steps: Mapping[str, StepRecord] = dict[str, 'StepRecord'](), _given: Mapping[str, Mapping[str, object]] = dict[str, Mapping[str, object]](), _shared: _Shared = _Shared())

What a run hands a step: the workspace, the run's scope, and the phase's keys.

One context serves one walk, and every step receives its own view of it, with the step named in step and, for a package step, the package it runs over in package. A step writes the keys its table provides with livery.workshop.PhaseContext.provide and reads the ones it reads with livery.workshop.PhaseContext.read; the views share what is written, so the engine reads a provided key back from the context the walk returns (livery.workshop.PhaseContext.result). The run phase's step that starts the executable records its exit code with livery.workshop.PhaseContext.exit. A view is frozen: a step that assigns an attribute changes a copy nobody reads, so the keys and the exit code go through the methods.

Attributes:

Name Type Description
root Path

The workspace root.

packages tuple[Package, ...]

Every package the workspace carries.

subset tuple[Package, ...] | None

The packages a scoped gate judges, or None for the whole gate.

tests Mapping[str, tuple[str, ...]]

Per package path, the test files that stand for the package's suite in this run.

examples tuple[str, ...]

The package paths whose changed files are examples and nothing else: their examples run and no suite.

fix bool

Whether the rewriters run in their fix mode.

files tuple[str, ...]

The files the run is limited to, root-relative, from fm check <paths>; empty when the scope decides.

safe bool

Whether the fixers run in their in-flight mode, which removes no code: --safe-fix.

point str

The CI point whose tests the test phase selects; empty for the gate's own.

shard Shard

The shard of a sharded check leg this run is, as fm check --shard or the leg's label names it (livery.workshop.Shard); one shard of one for a run that is not split. A step that declares shard among its flags runs its share of it, and the walk runs every other step on the first shard alone (livery.workshop._steps.on_this_shard).

catalogue Mapping[str, tuple[tuple[str, str], ...]] | None

Every file the run may read, by unit, each with its category, listed once per walk by livery.workshop._steps.catalogue; None when there is no listing, and then every step that applies runs.

package Package | None

The package a package step runs over, else None.

selection tuple[str, ...]

The test files selected for that package, relative to it, else empty.

changes Changes | None

What changed since the tree the run measures from, which selects what each workspace step with declared inputs judges (livery.workshop._influence.select); None when the run knows nothing of it, and then each judges everything.

arguments tuple[str, ...]

The words after --, the same for every step of the run: on a step's own verb, which a step that takes them hands its tool (StepRecord.arguments, a template's {arguments}), and on fm run, which the step starting the executable passes it; empty in every other run.

step str

The running step's name, <phase>.<step>, which the walk sets as it hands the context to the step; empty outside a step's run.

phase str

The phase the engine runs, build, whose given keys livery.workshop.PhaseContext.result reads back; on a step's view, the step's own phase, whose given keys the step reads. Empty for a walk over several phases, the gate's.

Methods:

Name Description
exit

Record code as the exit code fm run exits with.

for_package

This context narrowed to one package and its selected tests.

provide

Write value under key, a key the running step's table provides.

read

The value under key, a key the running step's table reads.

result

The value under key once the phase ran, for the engine that ran it.

root instance-attribute

root: Path

packages class-attribute instance-attribute

packages: tuple[Package, ...] = ()

subset class-attribute instance-attribute

subset: tuple[Package, ...] | None = None

tests class-attribute instance-attribute

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

examples class-attribute instance-attribute

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

fix class-attribute instance-attribute

fix: bool = False

files class-attribute instance-attribute

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

safe class-attribute instance-attribute

safe: bool = False

point class-attribute instance-attribute

point: str = ''

shard class-attribute instance-attribute

shard: Shard = ONE

catalogue class-attribute instance-attribute

catalogue: Mapping[str, tuple[tuple[str, str], ...]] | None = None

package class-attribute instance-attribute

package: Package | None = None

selection class-attribute instance-attribute

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

changes class-attribute instance-attribute

changes: Changes | None = None

arguments class-attribute instance-attribute

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

step class-attribute instance-attribute

step: str = ''

phase class-attribute instance-attribute

phase: str = ''

scoped property

scoped: bool

Whether this is a package-scoped gate.

judged property

judged: tuple[Package, ...]

The packages under judgment: the subset, or every package.

member property

member: Package

The package the step runs over, for a step that runs once per package.

Raises:

Type Description
Failed

when the run names none: a workspace step, or a context built outside a package step's run.

exit_code property

exit_code: int

The exit code the run phase's step recorded; 0 until one does.

exit

exit(code: int) -> None

Record code as the exit code fm run exits with.

The run phase's step that starts the executable calls it with the executable's; the walk hands the code to the verb through the context it returns.

Source code in packages/workshop/src/livery/workshop/_phases.py
def exit(self, code: int) -> None:
    """Record *code* as the exit code ``fm run`` exits with.

    The ``run`` phase's step that starts the executable calls it
    with the executable's; the walk hands the code to the verb
    through the context it returns.
    """
    self._shared.exit_code = code

for_package

for_package(package: Package) -> PhaseContext

This context narrowed to one package and its selected tests.

Source code in packages/workshop/src/livery/workshop/_phases.py
def for_package(self, package: Package) -> PhaseContext:
    """This context narrowed to one package and its selected tests."""
    files = self.tests.get(package.path, ())
    relative = tuple(path[len(package.path) + 1 :] for path in files)
    return replace(self, package=package, selection=relative)

provide

provide(key: str, value: object) -> None

Write value under key, a key the running step's table provides.

Raises:

Type Description
PhaseError

when the step's table does not provide key, or value is not of the type it declares.

Source code in packages/workshop/src/livery/workshop/_phases.py
def provide(self, key: str, value: object) -> None:
    """Write *value* under *key*, a key the running step's table provides.

    Raises:
        PhaseError: when the step's table does not provide *key*,
            or *value* is not of the type it declares.
    """
    record = self._running()
    provided = dict(record.provides)
    if key not in provided:
        raise PhaseError(
            f"{self.step} provides {key}, and its {self._table()} table does"
            " not name it in provides"
        )
    if not _holds(provided[key], value):
        raise PhaseError(
            f"{self.step} provides {key} as {type(value).__name__}, and its"
            f" {self._table()} table declares it {provided[key]}"
        )
    with self._shared.lock:
        self._shared.values.setdefault(self._unit(), {})[key] = value

read

read(key: str) -> object

The value under key, a key the running step's table reads.

Its type is the one its provider declares, or the one the phase's declaration gives an engine key.

Raises:

Type Description
PhaseError

when the step's table does not read key, the engine did not give it, or its provider wrote nothing under it.

Source code in packages/workshop/src/livery/workshop/_phases.py
def read(self, key: str) -> object:
    """The value under *key*, a key the running step's table reads.

    Its type is the one its provider declares, or the one the
    phase's declaration gives an engine key.

    Raises:
        PhaseError: when the step's table does not read *key*, the
            engine did not give it, or its provider wrote nothing
            under it.
    """
    record = self._running()
    if key not in record.reads:
        raise PhaseError(
            f"{self.step} reads {key}, and its {self._table()} table does not"
            " name it in reads"
        )
    if key in self._engine():
        given = self._given.get(self.phase, {})
        if key not in given:
            raise PhaseError(
                f"{self.step} reads {key}, which the engine running the"
                f" {self.phase} phase did not give it"
            )
        return given[key]
    values = self._shared.values.get(self._unit(), {})
    if key not in values:
        provider = next(
            (
                name
                for name, held in self._steps.items()
                if key in dict(held.provides)
            ),
            "its provider",
        )
        raise PhaseError(
            f"{self.step} reads {key}, which {provider} has not provided in"
            f" the {self.phase} phase"
        )
    return values[key]

result

result(key: str) -> object | None

The value under key once the phase ran, for the engine that ran it.

A key a step provided for the context's package, else one the engine gave the context's phase; None when neither wrote one.

Source code in packages/workshop/src/livery/workshop/_phases.py
def result(self, key: str) -> object | None:
    """The value under *key* once the phase ran, for the engine that ran it.

    A key a step provided for the context's package, else one the
    engine gave the context's phase; None when neither wrote one.
    """
    values = self._shared.values.get(self._unit(), {})
    return values.get(key, self._given.get(self.phase, {}).get(key))

Prose dataclass

Prose(section: str, topic: str, audience: str = '', extension: str = BASE_EXTENSION, source: Path | None = None, render: Render | None = None)

One prose fragment: a file an extension ships, or a render from the registries.

Attributes:

Name Type Description
section str

The section it belongs to, one of the base's.

topic str

What it is about; with the section, its name.

audience str

agent or human for a file that serves one reader, empty for both; a rendered fragment is empty here and answers per audience.

extension str

The extension that ships or renders it; empty for the repository's own.

source Path | None

The shipped file, or None for a rendered fragment.

render Render | None

The render, or None for a shipped fragment.

Methods:

Name Description
text

The markdown for audience: the shipped text, or the render's answer.

section instance-attribute

section: str

topic instance-attribute

topic: str

audience class-attribute instance-attribute

audience: str = ''

extension class-attribute instance-attribute

extension: str = BASE_EXTENSION

source class-attribute instance-attribute

source: Path | None = None

render class-attribute instance-attribute

render: Render | None = None

name property

name: str

The delivered file name, <section>.<topic>.md.

origin property

origin: str

Where it comes from, for a refusal: the posix file, or the extension.

text

text(root: Path, audience: str | None) -> str

The markdown for audience: the shipped text, or the render's answer.

Source code in packages/workshop/src/livery/workshop/_prose.py
def text(self, root: Path, audience: str | None) -> str:
    """The markdown for *audience*: the shipped text, or the render's answer."""
    if self.render is not None:
        return self.render(root, audience)
    if self.source is not None:
        return self.source.read_text(encoding="utf-8")
    return ""

Query dataclass

Query(name: str)

Bases: Generic[T_co]

A handle naming a declared query, typed by its answer.

The handle is covariant in its answer: one typed by a tuple serves a reader that takes any iterable.

Attributes:

Name Type Description
name str

The key an extension answers it under: public-modules.

name instance-attribute

name: str

RequirementWriter

Bases: Protocol

Write a package's requirement on a sibling into one ecosystem's manifest.

An extension answers the requirement-writers query with its writers, and the test-requirement-writers query with the writers of a requirement the package's tests alone have. Every writer of a package's set is called for each requirement. A writer takes a sibling of its own ecosystem alone: for any other sibling it writes nothing and returns None, so the requirement lands in the manifest of the sibling's ecosystem. A requirement no writer of the set takes refuses, naming the sibling's set.

Methods:

Name Description
__call__

Write dependency at floor into package's manifest.

__call__

__call__(package: Package, dependency: Package, floor: str) -> list[str] | None

Write dependency at floor into package's manifest.

Parameters:

Name Type Description Default
package Package

The package whose manifest gains the requirement.

required
dependency Package

The sibling it requires.

required
floor str

The lowest version of dependency the requirement takes.

required

Returns:

Type Description
list[str] | None

The files changed, relative to the package; empty when the

list[str] | None

manifest names dependency already. None for a sibling

list[str] | None

outside the writer's ecosystem, which it leaves alone.

Source code in packages/workshop/src/livery/workshop/_queries.py
def __call__(
    self, package: Package, dependency: Package, floor: str
) -> list[str] | None:
    """Write *dependency* at *floor* into *package*'s manifest.

    Args:
        package: The package whose manifest gains the requirement.
        dependency: The sibling it requires.
        floor: The lowest version of *dependency* the requirement
            takes.

    Returns:
        The files changed, relative to the package; empty when the
        manifest names *dependency* already. None for a sibling
        outside the writer's ecosystem, which it leaves alone.
    """
    ...

RegistryTarget dataclass

RegistryTarget(kind: str, url: str, publish_url: str = '', local: bool = False, token: str = '', releases: bool = False)

One resolved registry for one artifact kind.

Attributes:

Name Type Description
kind str

Which artifact registry this is.

url str

The registry's address: the read index for python (the publish endpoint is publish_url), the remote for conan, the reference prefix for container. A local path when the declaration was a folder.

publish_url str

Where python dists upload; empty means the publisher's own default resolution (uv publish and trusted publishing on pypi.org). Unused by other kinds.

local bool

True when the target is a folder or share rather than a server.

releases bool

True when the artifacts ride the forge's own releases, attached to each member's receipt tag. The route a conan package takes on a forge that hosts no conan registry; url is then the repository's page, for printing.

token str

The registry credential, for reads and uploads alike: the kind's credential variable when set, else the forge lane's token when the forge rung answered. Empty reads anonymously and lets the publisher's own resolution decide.

Methods:

Name Description
from_table

The target a registry-target table holds.

kind instance-attribute

kind: str

url instance-attribute

url: str

publish_url class-attribute instance-attribute

publish_url: str = ''

local class-attribute instance-attribute

local: bool = False

token class-attribute instance-attribute

token: str = ''

releases class-attribute instance-attribute

releases: bool = False

from_table classmethod

from_table(table: Mapping[str, object]) -> RegistryTarget

The target a registry-target table holds.

The engine gives each step of the publish phase the registry it resolved as the registry-target key: a table of this class's fields by name, which the step reads back with this constructor. The table holds kind and url, and a field it leaves out takes its default.

Parameters:

Name Type Description Default
table Mapping[str, object]

Each field of the target by its name.

required

Returns:

Type Description
RegistryTarget

The target the table holds.

Raises:

Type Description
ValueError

when the table is not a registry target: it has no kind or no url, a value has another type than its field, or a key names no field. The message names the field and what it takes, and never a value, since token is a credential.

Source code in packages/workshop/src/livery/workshop/_registries.py
@classmethod
def from_table(cls, table: Mapping[str, object]) -> RegistryTarget:
    """The target a ``registry-target`` table holds.

    The engine gives each step of the ``publish`` phase the registry
    it resolved as the ``registry-target`` key: a table of this
    class's fields by name, which the step reads back with this
    constructor. The table holds ``kind`` and ``url``, and a field
    it leaves out takes its default.

    Args:
        table: Each field of the target by its name.

    Returns:
        The target the table holds.

    Raises:
        ValueError: when the table is not a registry target: it has
            no ``kind`` or no ``url``, a value has another type than
            its field, or a key names no field. The message names
            the field and what it takes, and never a value, since
            ``token`` is a credential.
    """
    names = tuple(field.name for field in fields(cls))
    unknown = [name for name in table if name not in names]
    if unknown:
        raise ValueError(
            f"not a registry target: the table holds {', '.join(unknown)};"
            f" a registry target holds {', '.join(names)}"
        )
    for field in fields(cls):
        if field.default is MISSING and field.name not in table:
            raise ValueError(
                f"not a registry target: the table has no {field.name},"
                " which every registry target holds"
            )
    return cls(
        kind=_text(table, "kind"),
        url=_text(table, "url"),
        publish_url=_text(table, "publish_url"),
        local=_flag(table, "local"),
        token=_text(table, "token"),
        releases=_flag(table, "releases"),
    )

ReleaseNotes

Bases: Protocol

What a release-notes provider answers.

Methods:

Name Description
entry

The notes the commits since package's last release earn.

record

Write version's entry into package's history.

verify

The problems with version's recorded notes; empty when sound.

entry

entry(root: Path, package: Package, version: str = '') -> str

The notes the commits since package's last release earn.

Headed by version when one is given, as unreleased otherwise; empty when nothing unreleased touches the package.

Source code in packages/workshop/src/livery/workshop/_release_notes.py
def entry(self, root: Path, package: Package, version: str = "") -> str:
    """The notes the commits since *package*'s last release earn.

    Headed by *version* when one is given, as unreleased otherwise;
    empty when nothing unreleased touches the package.
    """
    ...

record

record(package: Package, version: str, entry: str) -> list[str]

Write version's entry into package's history.

An empty entry records a placeholder for a person to write. Returns the files changed, each with a note for the reader, empty when the history already holds the version's entry.

Source code in packages/workshop/src/livery/workshop/_release_notes.py
def record(self, package: Package, version: str, entry: str) -> list[str]:
    """Write *version*'s *entry* into *package*'s history.

    An empty *entry* records a placeholder for a person to write.
    Returns the files changed, each with a note for the reader,
    empty when the history already holds the version's entry.
    """
    ...

verify

verify(package: Package, version: str) -> list[str]

The problems with version's recorded notes; empty when sound.

Source code in packages/workshop/src/livery/workshop/_release_notes.py
def verify(self, package: Package, version: str) -> list[str]:
    """The problems with *version*'s recorded notes; empty when sound."""
    ...

Shard dataclass

Shard(index: int, count: int)

One shard of a leg: which of how many, spelled <i>of<n>.

Attributes:

Name Type Description
index int

The shard's number, from 1.

count int

How many shards the leg runs as.

Raises:

Type Description
ValueError

When the count is below 1, the index below 1, or the index above the count.

Methods:

Name Description
__post_init__
parse

The shard text spells, 2of4.

__str__

index instance-attribute

index: int

count instance-attribute

count: int

first property

first: bool

Whether this is the first shard, the one that runs what is not split.

__post_init__

__post_init__() -> None
Source code in packages/workshop/src/livery/workshop/_shard.py
def __post_init__(self) -> None:
    why = _unsound(self.index, self.count)
    if why:
        raise ValueError(f"shard {self.index} of {self.count}: {why}")

parse classmethod

parse(text: str) -> Shard

The shard text spells, 2of4.

Raises:

Type Description
ValueError

When text is not of the form, naming it.

Source code in packages/workshop/src/livery/workshop/_shard.py
@classmethod
def parse(cls, text: str) -> Shard:
    """The shard *text* spells, ``2of4``.

    Raises:
        ValueError: When *text* is not of the form, naming it.
    """
    matched = _SPELLING.match(text)
    if matched is None:
        raise ValueError(
            f"{text!r} is not a shard; a shard is spelled <i>of<n>, such as 2of4"
        )
    index, count = int(matched.group(1)), int(matched.group(2))
    why = _unsound(index, count)
    if why:
        raise ValueError(f"{text!r} is not a shard: {why}")
    return cls(index, count)

__str__

__str__() -> str
Source code in packages/workshop/src/livery/workshop/_shard.py
def __str__(self) -> str:
    return f"{self.index}of{self.count}"

ShardMarker dataclass

ShardMarker(shard: Shard, digest: str, items: tuple[str, ...], rows: tuple[str, ...], before: datetime, suites: tuple[str, ...] = (), attempt: str = '')

What a shard left in SHARD_FILE: what it ran and what it partitioned from.

Attributes:

Name Type Description
shard Shard

The shard the leg ran as.

digest str

The digest of the set it partitioned, livery.workshop.files_digest of every item of every shard.

items tuple[str, ...]

The items this shard ran, in packing order; pytest's are test files.

rows tuple[str, ...]

The durations rows it read, newest first.

before datetime

The bound it read them under, the checkout's committer time.

suites tuple[str, ...]

The units whose items were in the set, by path. A unit the record does not name ran whole on the first shard, with every step that does not read the shard, so the first shard leaves its parts. A record written without the key names none.

attempt str

The attempt of the run the shard ran in, as the runner counts them (livery.workshop.RunContext's attempt); empty when the runner did not say, and for a record written without the key. Two shards of one platform from two attempts partitioned from the record as it was each time, which the fold names when their partitions differ.

shard instance-attribute

shard: Shard

digest instance-attribute

digest: str

items instance-attribute

items: tuple[str, ...]

rows instance-attribute

rows: tuple[str, ...]

before instance-attribute

before: datetime

suites class-attribute instance-attribute

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

attempt class-attribute instance-attribute

attempt: str = ''

SpeedMark dataclass

SpeedMark(package: str, leg: str, seconds: float, kind: str, by: str, reason: str, when: str)

A package's mark on one check leg and the row that set it.

The mark is the suite's summed test time the gate job judges the leg's runs against; livery.workshop.speed_marks reads the current mark of each package on each leg.

Attributes:

Name Type Description
package str

The package path (packages/forge).

leg str

The check leg (check-ubuntu-latest-3.14).

seconds float

The mark: the suite's summed test time.

kind str

first (a run recorded it), ratchet (a run moved it down), or accept (a person raised it).

by str

The run or the person that wrote the row.

reason str

The reason an accept gave; empty otherwise.

when str

When the row was written, ISO 8601.

package instance-attribute

package: str

leg instance-attribute

leg: str

seconds instance-attribute

seconds: float

kind instance-attribute

kind: str

by instance-attribute

by: str

reason instance-attribute

reason: str

when instance-attribute

when: str

ToolReceipt dataclass

ToolReceipt(tool: str, version: str, host: str, kind: str, mode: str, deployment: str = '', tool_dir: str = '', paths: tuple[str, ...] = (), env: dict[str, str] = dict(), entry_points: tuple[str, ...] = (), source: str = 'store', answered: str = '', stamp: dict[str, str] = dict())

What this checkout installed of one tool, as its file records it.

fm sync writes one receipt per tool under the checkout's .workshop/receipts/; livery.workshop.tool_receipts reads them all.

Attributes:

Name Type Description
tool str

The tool's name.

version str

The exact version installed, the lock's.

host str

The host key it was installed for, this machine's.

kind str

The installer kind.

mode str

How it reached PATH, one of livery.toolroom.store.MODES.

deployment str

The digest of the deployment installed; empty for a delegated kind, whose installer resolves the host.

tool_dir str

Where the tool is, under the machine's store home (livery.workshop.store_home).

paths tuple[str, ...]

The absolute directories the tool puts on PATH in path mode; empty otherwise.

env dict[str, str]

The variables the tool sets, resolved against its directory.

entry_points tuple[str, ...]

The executables' names the tool puts on PATH: linked into the checkout's bin directory in link mode, found on paths in path mode; empty in none mode. A check resolves the tool by these, never by its name, since a name (git_cliff) is not always a binary (git-cliff).

source str

store for a tool the store supplied, host for a copy already on the machine that served under the allowance; version is the lock's either way, what the stubs render for and the drift check speaks of.

answered str

The version the host's copy printed when it served; empty for a store install.

stamp dict[str, str]

The host copy's identity when it served: its path, size and mtime, so a sync that finds the same file probes nothing; empty for a store install.

Methods:

Name Description
to_json

The receipt as a JSON object.

load

The receipt at path.

tool instance-attribute

tool: str

version instance-attribute

version: str

host instance-attribute

host: str

kind instance-attribute

kind: str

mode instance-attribute

mode: str

deployment class-attribute instance-attribute

deployment: str = ''

tool_dir class-attribute instance-attribute

tool_dir: str = ''

paths class-attribute instance-attribute

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

env class-attribute instance-attribute

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

entry_points class-attribute instance-attribute

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

source class-attribute instance-attribute

source: str = 'store'

answered class-attribute instance-attribute

answered: str = ''

stamp class-attribute instance-attribute

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

to_json

to_json() -> dict[str, Any]

The receipt as a JSON object.

Source code in packages/workshop/src/livery/workshop/_tools.py
def to_json(self) -> dict[str, Any]:
    """The receipt as a JSON object."""
    return {
        "schema": RECEIPT_SCHEMA,
        "tool": self.tool,
        "version": self.version,
        "host": self.host,
        "kind": self.kind,
        "mode": self.mode,
        "deployment": self.deployment,
        "tool_dir": self.tool_dir,
        "paths": list(self.paths),
        "env": dict(self.env),
        "entry_points": list(self.entry_points),
        "source": self.source,
        "answered": self.answered,
        "stamp": dict(self.stamp),
    }

load classmethod

load(path: Path) -> ToolReceipt

The receipt at path.

Raises:

Type Description
ValueError

for a file that is not a receipt of this schema, naming the file.

Source code in packages/workshop/src/livery/workshop/_tools.py
@classmethod
def load(cls, path: Path) -> ToolReceipt:
    """The receipt at *path*.

    Raises:
        ValueError: for a file that is not a receipt of this schema,
            naming the file.
    """
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as error:
        raise ValueError(f"{path}: not a receipt ({error})") from None
    if not isinstance(data, dict) or data.get("schema") != RECEIPT_SCHEMA:
        raise ValueError(f"{path}: not a receipt of schema {RECEIPT_SCHEMA}")
    try:
        return cls(
            str(data["tool"]),
            str(data["version"]),
            str(data["host"]),
            str(data["kind"]),
            str(data["mode"]),
            str(data.get("deployment", "")),
            str(data.get("tool_dir", "")),
            tuple(str(p) for p in data.get("paths", [])),
            {str(k): str(v) for k, v in data.get("env", {}).items()},
            tuple(str(e) for e in data.get("entry_points", [])),
            str(data.get("source", "store")),
            str(data.get("answered", "")),
            {str(k): str(v) for k, v in data.get("stamp", {}).items()},
        )
    except (KeyError, TypeError, AttributeError) as error:
        raise ValueError(f"{path}: not a receipt ({error})") from None

LegScope dataclass

LegScope(scope: str, packages: tuple[str, ...] = (), leg: str = '', base_tree: str = '')

What the gate ran on one check leg, as the marker the leg left says.

Attributes:

Name Type Description
scope str

What the gate ran. full: the whole gate. affected: the gate narrowed to the packages a change affects. nothing: no package's steps, for a change that affects no package, such as prose alone; the workspace steps whose inputs it changed still run. verified: no step, since the verified record already proves the tree. unknown: the leg left no marker, or one that does not parse.

packages tuple[str, ...]

The paths of the suites a narrowed gate ran; empty for every other scope.

leg str

The label the leg's rows are keyed by (check-ubuntu-latest-3.14); empty when the marker names none.

base_tree str

The tree a narrowed gate measured from; empty for every other scope.

scope instance-attribute

scope: str

packages class-attribute instance-attribute

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

leg class-attribute instance-attribute

leg: str = ''

base_tree class-attribute instance-attribute

base_tree: str = ''

VerifiedBranch dataclass

VerifiedBranch(branch: str, reason: str = '')

The branch whose run proved a tree, or why the record could not say.

Attributes:

Name Type Description
branch str

The pull request branch whose run proved the tree; empty when no row names the tree, when the row names no branch, as main's own run's does, and when the row could not be read.

reason str

Why the record decided nothing: the tree has no id, or its row could not be read; empty when the record was read.

branch instance-attribute

branch: str

reason class-attribute instance-attribute

reason: str = ''

category_of

category_of(package: Package, path: str) -> Category

Say what path, relative to package's directory, is to the package.

The package's own [categories] exception answers first. Then the most specific rule of the tables that answer for the package wins, and between rules of one specificity the nearer table's: the extension later in composition order, the base's table last. Nothing matching is configuration, which the base's table also says last. The base's table names the documentation's paths (prose, nav, asset, example, generated) and everything else configuration; the extensions a package holds name the rest, such as source and test. The workspace's own tests (livery.workshop.WORKSPACE_TESTS) are answered by one table of the base's alone, in which a file under tests/ is test or test-support.

Returns:

Type Description
Category

The category's name, who supplied the rule that answered, and

Category

the pattern that matched.

Raises:

Type Description
CategoryError

a ValueError, when two rules of one specificity and one table claim path for different categories or from different extensions.

Source code in packages/workshop/src/livery/workshop/_categories.py
def category_of(package: Package, path: str) -> Category:
    """Say what *path*, relative to *package*'s directory, is to the package.

    The package's own ``[categories]`` exception answers first. Then
    the most specific rule of the tables that answer for the package
    wins, and between rules of one specificity the nearer table's: the
    extension later in composition order, the base's table last.
    Nothing matching is configuration, which the base's table also says
    last. The base's table names the documentation's paths (``prose``,
    ``nav``, ``asset``, ``example``, ``generated``) and everything else
    ``configuration``; the extensions a package holds name the rest,
    such as ``source`` and ``test``. The workspace's own tests
    ([livery.workshop.WORKSPACE_TESTS][]) are answered by one table of
    the base's alone, in which a file under ``tests/`` is ``test`` or
    ``test-support``.

    Returns:
        The category's name, who supplied the rule that answered, and
        the pattern that matched.

    Raises:
        CategoryError: a ValueError, when two rules of one specificity
            and one table claim *path* for different categories or from
            different extensions.
    """
    for category, patterns in package.categories:
        for pattern in patterns:
            if matches(pattern, path):
                return Category(category, "the package", pattern)
    rules = _package_rules(package)
    best: list[tuple[int, CategoryRule]] = []
    tables = {
        name: index for index, name in enumerate(dict.fromkeys(r.table for r in rules))
    }
    for rule in rules:
        if not matches(rule.pattern, path):
            continue
        if not best:
            best = [(tables[rule.table], rule)]
            continue
        _, current = best[0]
        if rule.specificity > current.specificity:
            best = [(tables[rule.table], rule)]
        elif rule.specificity == current.specificity:
            best.append((tables[rule.table], rule))
    if not best:
        return Category(CONFIGURATION, _BASE, "")
    nearest = min(depth for depth, _ in best)
    at_nearest = [rule for depth, rule in best if depth == nearest]
    if len(at_nearest) > 1 and any(
        rule.category != at_nearest[0].category
        or rule.extension != at_nearest[0].extension
        for rule in at_nearest
    ):
        first, second = at_nearest[0], at_nearest[1]
        raise CategoryError(
            f"{package.path}/{path}: two rules of one specificity claim it,"
            f" {first.pattern!r} as {first.category} ({first.extension}) and"
            f" {second.pattern!r} as {second.category} ({second.extension});"
            " the more specific pattern wins, so one of them names the file"
            " more closely"
        )
    rule = at_nearest[0]
    return Category(rule.category, rule.extension, rule.pattern)

ci_run

ci_run(environ: dict[str, str] | None = None) -> RunContext | None

The CI run this process belongs to, or None at a desk.

Read from the runner's environment, environ when given, the process's own otherwise: GitHub's and Gitea's GITHUB_* variables, GitLab's CI_*. An extension that behaves differently in CI asks this, never a variable of one forge.

Source code in packages/workshop/src/livery/workshop/_ci_context.py
def ci_run(environ: dict[str, str] | None = None) -> RunContext | None:
    """The CI run this process belongs to, or None at a desk.

    Read from the runner's environment, *environ* when given, the
    process's own otherwise: GitHub's and Gitea's ``GITHUB_*``
    variables, GitLab's ``CI_*``. An extension that behaves
    differently in CI asks this, never a variable of one forge.
    """
    return run_context(environ)

state_store

state_store(root: Path) -> StateStore

Open the state store of the checkout at root, with the workshop's policy.

A CI run may write a ci_only series and a desk may not; every commit the store makes is by the tools' identity (livery.git.tool_identity); a published listing travels in the WORKSHOP_SNAPSHOT variable. Every series the workshop and its extensions keep is read and written through it.

Source code in packages/workshop/src/livery/workshop/_ci_context.py
def state_store(root: Path) -> git.StateStore:
    """Open the state store of the checkout at *root*, with the workshop's policy.

    A CI run may write a ``ci_only`` series and a desk may not; every
    commit the store makes is by the tools' identity
    ([livery.git.tool_identity][]); a published listing travels in the
    ``WORKSHOP_SNAPSHOT`` variable. Every series the workshop and its
    extensions keep is read and written through it.
    """
    prog = footman.prog()
    return git.StateStore(
        root,
        in_ci=run_context() is not None,
        identity=git.tool_identity(prog),
        snapshot_variable=SNAPSHOT_VARIABLE,
        prog=prog,
    )

extension_set

extension_set(package: Package) -> tuple[str, ...]

The extensions package holds: its list and every extension the list requires.

In composition order, as the installed declarations declare it: each extension after the ones it requires, ties alphabetical, and alphabetical while the declared order has no start. The list's own order means nothing. Empty for a package that lists none. The workspace's own tests (livery.workshop.workspace_suite) hold the root's set: the extensions [workspace] extensions lists and every one they require, read from the root's contract on each call. A step that names extensions judges a package whose set holds one of them.

A list is composed once for each scan of the installed extensions, so a scan taken after an install composes it again.

Source code in packages/workshop/src/livery/workshop/_composition.py
def extension_set(package: Package) -> tuple[str, ...]:
    """The extensions *package* holds: its list and every extension the list requires.

    In composition order, as the installed declarations declare it:
    each extension after the ones it requires, ties alphabetical, and
    alphabetical while the declared order has no start. The list's own
    order means nothing. Empty for a package that lists none. The
    workspace's own tests ([livery.workshop.workspace_suite][]) hold the
    root's set: the extensions ``[workspace] extensions`` lists and
    every one they require, read from the root's contract on each call.
    A step that names extensions judges a package whose set holds one
    of them.

    A list is composed once for each scan of the installed extensions,
    so a scan taken after an install composes it again.
    """
    from livery.workshop._packages import WORKSPACE_TESTS

    if package.path == WORKSPACE_TESTS:
        from livery.workshop._extensions import root_set

        return root_set(package.root)
    listed = package.extensions
    if not listed:
        return ()
    from livery.footman import installed_entry_points
    from livery.workshop._extensions import installed_declaration

    scan = installed_entry_points()
    held = _SETS.get(listed)
    if held is not None and held[0] is scan:
        return held[1]
    found = order_or_sorted(
        closure(listed, installed_declaration), installed_declaration
    )
    _SETS[listed] = (scan, found)
    return found

nearest_extensions

nearest_extensions(names: Iterable[str], lookup: object) -> tuple[str, ...]

Of the extensions names, the ones no other of them requires: the nearest.

The rule a query's nearest combine applies, for a combine function that decides between answers by what each answering extension requires, transitively. lookup is the one such a function is called with, passed on as it came. The nearest come in the order of names; two of them means neither requires the other. Answers whose requires close a cycle leave none nearest, and layering.graph names the cycle.

Source code in packages/workshop/src/livery/workshop/_composition.py
def nearest_extensions(names: Iterable[str], lookup: object) -> tuple[str, ...]:
    """Of the extensions *names*, the ones no other of them requires: the nearest.

    The rule a query's ``nearest`` combine applies, for a combine
    function that decides between answers by what each answering
    extension requires, transitively. *lookup* is the one such a
    function is called with, passed on as it came. The nearest come in
    the order of *names*; two of them means neither requires the other.
    Answers whose requires close a cycle leave none nearest, and
    ``layering.graph`` names the cycle.
    """
    named = tuple(dict.fromkeys(names))
    required = implied(named, cast("Lookup", lookup))
    return tuple(name for name in named if name not in required)

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)

is_example

is_example(path: Path) -> bool

Tell whether path is a documentation example.

An example is a python file under a docs/examples/ directory at any depth of path, which the examples plugin collects as one test. A conftest.py there is the package's setup around the examples, never an example. Nothing is read from the disk.

Parameters:

Name Type Description Default
path Path

The file, relative or absolute.

required

Returns:

Type Description
bool

True for an example; False for any other file.

Source code in packages/workshop/src/livery/workshop/_examples.py
def is_example(path: Path) -> bool:
    """Tell whether *path* is a documentation example.

    An example is a python file under a ``docs/examples/`` directory at
    any depth of *path*, which the examples plugin collects as one
    test. A ``conftest.py`` there is the package's setup around the
    examples, never an example. Nothing is read from the disk.

    Args:
        path: The file, relative or absolute.

    Returns:
        True for an example; False for any other file.
    """
    if path.suffix != ".py" or path.name == "conftest.py":
        return False
    parts = path.parts
    return any(parts[i : i + 2] == ("docs", "examples") for i in range(len(parts) - 1))

contributions_for

contributions_for(target: str, start: Path | None = None) -> dict[str, dict[str, Any]]

What the installed extensions declare for target, by extension.

The extensions come in composition order. An extension contributes its [for.<target>] table while target is listed and the extension's listing contributes to it (every listed target it declares a table for, except those its root entry's without names), the rule the mount grafts by; an extension that requires target contributes its top-level tables. The tables come as the declaration file holds them, and an extension that declares nothing for target is left out, as is every extension when target is not listed. start is a directory in the workspace, the working directory when absent.

Source code in packages/workshop/src/livery/workshop/_extensions.py
def contributions_for(
    target: str, start: Path | None = None
) -> dict[str, dict[str, Any]]:
    """What the installed extensions declare for *target*, by extension.

    The extensions come in composition order. An extension contributes
    its ``[for.<target>]`` table while *target* is listed and the
    extension's listing contributes to it (every listed target it
    declares a table for, except those its root entry's ``without``
    names), the rule the mount grafts by; an extension that requires
    *target* contributes its top-level tables. The tables come as the
    declaration file holds them, and an extension that declares nothing
    for *target* is left out, as is every extension when *target* is
    not listed. *start* is a directory in the workspace, the working
    directory when absent.
    """
    names = extension_names(start)
    if target not in names:
        return {}
    contributes = contributing(start)
    found: dict[str, dict[str, Any]] = {}
    for owner in names:
        declared = _readable(owner)
        if declared is None or owner == target:
            continue
        if target in declared.requires:
            found[owner] = dict(declared.tables)
        elif target in contributes.get(owner, ()):
            found[owner] = dict(declared.target_tables[target])
    return found

extension_names

extension_names(start: Path | None = None) -> tuple[str, ...]

The extensions the workspace installs and mounts, in mount order.

The root's set and every package's set, in composition order (livery.workshop._extensions.installed_set). workspace_names reads the workspace list alone, and root_set the root's set.

Source code in packages/workshop/src/livery/workshop/_extensions.py
def extension_names(start: Path | None = None) -> tuple[str, ...]:
    """The extensions the workspace installs and mounts, in mount order.

    The root's set and every package's set, in composition order
    ([livery.workshop._extensions.installed_set][]).
    ``workspace_names`` reads the workspace list alone, and
    ``root_set`` the root's set.
    """
    return installed_set(start)

shipped_content

shipped_content(start: Path | None = None) -> tuple[tuple[str, Path], ...]

Each extension of the workspace's stack with its content/ directory.

The base first, then the installed set in mount order, each with the directory its shipped files live in; an extension that ships no content, or that no installed distribution declares, is left out.

Source code in packages/workshop/src/livery/workshop/_extensions.py
def shipped_content(start: Path | None = None) -> tuple[tuple[str, Path], ...]:
    """Each extension of the workspace's stack with its ``content/`` directory.

    The base first, then the installed set in mount order, each with
    the directory its shipped files live in; an extension that ships no
    content, or that no installed distribution declares, is left out.
    """
    found: list[tuple[str, Path]] = []
    for extension in stack_names(start):
        content = extension_content(extension)
        if content is not None:
            found.append((extension, content))
    return tuple(found)

workspace_root

workspace_root(start: Path | None = None) -> Path | None

The nearest ancestor carrying the workspace's contract, or None.

The workspace contract is the marker; a checkout without one is not a workspace and gets no extensions. A package's own workshop.toml, under packages/<name>/ or packages/<group>/<name>/ of a workspace whose root holds a contract, is passed over, so a verb run inside a package resolves the workspace it belongs to. Without start, the search starts at the running task's directory, the process's outside a run: a task never reads the process's own, which a parallel run shares.

Source code in packages/workshop/src/livery/workshop/_extensions.py
def workspace_root(start: Path | None = None) -> Path | None:
    """The nearest ancestor carrying the workspace's contract, or None.

    The workspace contract is the marker; a checkout without one is
    not a workspace and gets no extensions. A package's own
    ``workshop.toml``, under ``packages/<name>/`` or
    ``packages/<group>/<name>/`` of a workspace whose root holds a
    contract, is passed over, so a verb run inside a package resolves
    the workspace it belongs to. Without *start*, the search starts at
    the running task's directory, the process's outside a run: a task
    never reads the process's own, which a parallel run shares.
    """
    from livery.workshop._contract import _package_workspace

    origin = (start or cwd()).resolve()
    for candidate in (origin, *origin.parents):
        contract = candidate / "workshop.toml"
        if not contract.is_file():
            continue
        above = _package_workspace(contract)
        if above is not None and (above / "workshop.toml").is_file():
            continue
        return candidate
    return None

forge_repository

forge_repository(root: Path) -> str

This workspace's repository name on its forge: the name origin points at.

The remote's URL in either spelling, https://host/owner/name or git@host:owner/name, with or without .git.

Raises:

Type Description
Failed

when root has no origin remote, or its URL names no owner and name.

Source code in packages/workshop/src/livery/workshop/_forge_lane.py
def forge_repository(root: Path) -> str:
    """This workspace's repository name on its forge: the name ``origin`` points at.

    The remote's URL in either spelling, ``https://host/owner/name`` or
    ``git@host:owner/name``, with or without ``.git``.

    Raises:
        Failed: when *root* has no ``origin`` remote, or its URL names
            no owner and name.
    """
    try:
        url = git.remote_url(root)
    except git.GitError as error:
        fail(f"no origin remote:\n{error}")
    match = _REMOTE_RE.search(url)
    if match is None:
        fail(f"cannot read owner/name from origin url {shown_url(url)!r}")
    return match.group("name")

this_forge

this_forge(root: Path) -> Forge

The workspace's forge, per the contract's [forge] table.

The token is FORGE_TOKEN (host-qualified first); with neither set, the backend's own documented fallback decides.

Returns:

Type Description
Forge

The connected livery.forge.Forge.

Source code in packages/workshop/src/livery/workshop/_forge_lane.py
def this_forge(root: Path) -> Forge:
    """The workspace's forge, per the contract's ``[forge]`` table.

    The token is ``FORGE_TOKEN`` (host-qualified first); with neither
    set, the backend's own documented fallback decides.

    Returns:
        The connected [livery.forge.Forge][].
    """
    contract = load_contract(root / "workshop.toml")
    forge_table = contract.get("forge") or {}
    kind = str(forge_table.get("kind", ""))
    url = str(forge_table.get("url", ""))
    if not kind:
        fail("workshop.toml [forge] must carry kind and owner")
    token, _ = forge_token(kind, url)
    return _connect(kind, url, token or None)

this_repository

this_repository(root: Path) -> Repository

The workspace's repository, per the contract and the remote.

Source code in packages/workshop/src/livery/workshop/_forge_lane.py
def this_repository(root: Path) -> Repository:
    """The workspace's repository, per the contract and the remote."""
    contract = load_contract(root / "workshop.toml")
    owner = str((contract.get("forge") or {}).get("owner", ""))
    if not owner:
        fail("workshop.toml [forge] must carry kind and owner")
    return this_forge(root).repository(owner, forge_repository(root))

order_topologically

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

packages in release order: every dependency before its dependents.

Kahn's walk over the [[depends]] edges restricted to the given set; ties keep the input order so the result is deterministic. A cycle cannot arise, the layering lint refuses one long before a release asks.

Source code in packages/workshop/src/livery/workshop/_graph.py
def order_topologically(packages: tuple[Package, ...]) -> tuple[Package, ...]:
    """*packages* in release order: every dependency before its dependents.

    Kahn's walk over the ``[[depends]]`` edges restricted to the given
    set; ties keep the input order so the result is deterministic. A
    cycle cannot arise, the layering lint refuses one long before a
    release asks.
    """
    chosen = {p.path for p in packages}
    remaining = list(packages)
    ordered: list[Package] = []
    placed: set[str] = set()
    while remaining:
        for index, package in enumerate(remaining):
            needs = {
                edge.path
                for edge in package.depends
                if edge.path in chosen and edge.path not in placed
            }
            if not needs:
                ordered.append(package)
                placed.add(package.path)
                del remaining[index]
                break
        else:  # pragma: no cover - guarded by the layering lint
            ordered.extend(remaining)
            break
    return tuple(ordered)

run_batched

run_batched(paths: Sequence[str], call: Callable[[tuple[str, ...]], None], *, limit: int = ARGV_LIMIT) -> None

Run call once per batch of paths; one refusal naming every failure.

Every batch runs even when an earlier one fails, so one gate shows every finding. An empty paths runs nothing.

Raises:

Type Description
Failed

when any batch failed, with each failure's reason.

Source code in packages/workshop/src/livery/workshop/_invoke.py
def run_batched(
    paths: Sequence[str],
    call: Callable[[tuple[str, ...]], None],
    *,
    limit: int = ARGV_LIMIT,
) -> None:
    """Run *call* once per batch of *paths*; one refusal naming every failure.

    Every batch runs even when an earlier one fails, so one gate shows
    every finding. An empty *paths* runs nothing.

    Raises:
        Failed: when any batch failed, with each failure's reason.
    """
    reasons: list[str] = []
    for batch in batches(paths, limit=limit):
        try:
            call(batch)
        except Failed as failure:
            reasons.append(str(failure))
    if len(reasons) == 1:
        fail(reasons[0])
    if reasons:
        fail(f"{len(reasons)} calls failed:\n" + "\n".join(reasons))

build_release

build_release(package: Package, root: Path, *, epoch: int = 0) -> Path

Build package's release artifacts into its dist/; that directory.

The release train's build: the steps package's set adds to the build phase, run on the phase's isolated side in the release configuration. One of them provides the dist directory it wrote.

Parameters:

Name Type Description Default
package Package

The member to build.

required
root Path

The workspace root package is a member of.

required
epoch int

The build's source date in seconds, so two builds of one tree are the same bytes; 0 takes the build tool's own.

0

Returns:

Type Description
Path

The directory the build phase's steps wrote the artifacts into.

Raises:

Type Description
Failed

naming the package, its set and the phase, when no extension of the set adds a step to the build phase; and naming the package, when the steps that ran provide no dist directory.

Source code in packages/workshop/src/livery/workshop/_lifecycle.py
def build_release(package: Package, root: Path, *, epoch: int = 0) -> Path:
    """Build *package*'s release artifacts into its ``dist/``; that directory.

    The release train's build: the steps *package*'s set adds to the
    build phase, run on the phase's isolated side in the ``release``
    configuration. One of them provides the ``dist`` directory it
    wrote.

    Args:
        package: The member to build.
        root: The workspace root *package* is a member of.
        epoch: The build's source date in seconds, so two builds of one
            tree are the same bytes; 0 takes the build tool's own.

    Returns:
        The directory the build phase's steps wrote the artifacts into.

    Raises:
        Failed: naming the package, its set and the phase, when no
            extension of the set adds a step to the build phase; and
            naming the package, when the steps that ran provide no
            ``dist`` directory.
    """
    from pathlib import Path

    ctx = _served(package, "build", root, {**RELEASE_BUILD, "epoch": epoch})
    return cast("Path", _provided(ctx, "dist", Path))

leave_leg_file

leave_leg_file(root: Path, name: str, data: Mapping[str, Any]) -> Path

Leave data in the leg's spool as name, for the leg's one write.

The leg's last entry, ci.leg, puts every file the spool holds on the leg's per-run ref, a series of livery.workshop.RUNS, beside its timing row and under its own name, where the gate job reads it. That write refuses a file named row.json, the timing row's own name. A file left twice under one name keeps the last data.

Returns:

Type Description
Path

The path of the file left under root.

Source code in packages/workshop/src/livery/workshop/_metrics.py
def leave_leg_file(root: Path, name: str, data: Mapping[str, Any]) -> Path:
    """Leave *data* in the leg's spool as *name*, for the leg's one write.

    The leg's last entry, ``ci.leg``, puts every file the spool holds
    on the leg's per-run ref, a series of [livery.workshop.RUNS][],
    beside its timing row and under its own name, where the gate job
    reads it. That write refuses a file named ``row.json``, the timing
    row's own name. A file left twice under one name keeps the last
    *data*.

    Returns:
        The path of the file left under *root*.
    """
    spool = root / LEG_SPOOL
    spool.mkdir(parents=True, exist_ok=True)
    path = spool / name
    path.write_text(json.dumps(data, sort_keys=True), encoding="utf-8")
    return path

leave_section

leave_section(root: Path, name: str, packages: Mapping[str, float], *, unit: str = '') -> str

Leave a section of the run's row, a number per package, for the gate job.

The gate job's ci.metrics.collect entry, before its verdict, folds every section left at root into the run's file on the metrics series, and fm ci.timings renders each as a trend, the numbers followed by unit. A section left twice under one name keeps the last numbers.

Returns:

Type Description
str

The line to print, naming the section and how many packages

str

it holds.

Source code in packages/workshop/src/livery/workshop/_metrics.py
def leave_section(
    root: Path, name: str, packages: Mapping[str, float], *, unit: str = ""
) -> str:
    """Leave a section of the run's row, a number per package, for the gate job.

    The gate job's ``ci.metrics.collect`` entry, before its verdict,
    folds every section left at *root* into the run's file on the
    metrics series, and ``fm ci.timings`` renders each as a trend, the
    numbers followed by *unit*. A section left twice under one *name*
    keeps the last numbers.

    Returns:
        The line to print, naming the section and how many packages
        it holds.
    """
    directory = root / RUN_ROW
    directory.mkdir(parents=True, exist_ok=True)
    (directory / f"{name}.json").write_text(
        json.dumps({"unit": unit, "packages": dict(sorted(packages.items()))}),
        encoding="utf-8",
    )
    return f"{name} row: {len(packages)} package(s) for the run's record"

discover_packages

discover_packages(root: Path) -> tuple[Package, ...]

Every package the workspace carries, by its contract, sorted by path.

Raises ValueError, with every finding listed, when a directory under packages/ lacks its contract, or holds the runtime's language (holds_runtime_language) and lacks the pyproject.toml a distribution of that language carries: a half-present package is a wrong state, not a lesser one. A directory holding only what a removed package left behind is named as such, with the fm sync that removes it. A package that lists no extension holds none, and needs no project file.

Source code in packages/workshop/src/livery/workshop/_packages.py
def discover_packages(root: Path) -> tuple[Package, ...]:
    """Every package the workspace carries, by its contract, sorted by path.

    Raises ValueError, with every finding listed, when a directory
    under ``packages/`` lacks its contract, or holds the runtime's
    language (`holds_runtime_language`) and lacks the
    ``pyproject.toml`` a distribution of that language carries: a
    half-present package is a wrong state, not a lesser one. A
    directory holding only what a removed package left behind is
    named as such, with the ``fm sync`` that removes it. A package
    that lists no extension holds none, and needs no project file.
    """
    problems = []
    packages = []
    # A workspace born a moment ago has no members yet; zero packages
    # is a legal answer, not a missing directory.
    for directory in package_directories(root):
        member = directory.relative_to(root / PACKAGES_DIR).as_posix()
        contract_file = directory / "workshop.toml"
        if not contract_file.is_file():
            problems.append(_no_contract(root, directory))
            continue
        contract = load_contract(contract_file)
        depends = tuple(
            Edge(
                path=str(edge.get("path", "")),
                kind=str(edge.get("kind", "build")),
                floor=str(edge.get("floor", "")),
            )
            for edge in contract.get("depends", [])
        )
        release = contract.get("release") or {}
        # The contract's judge has held every table below to its shape.
        reassigned = [
            (str(category), tuple(patterns))
            for category, patterns in contract.get("categories", {}).items()
        ]
        options: list[tuple[str, tuple[tuple[str, object], ...]]] = []
        for phase, table in contract.get("phases", {}).items():
            # Scalars are the phase's own options, for every step of
            # the phase; a table is one step's.
            own = tuple(
                (str(key), value)
                for key, value in table.items()
                if not isinstance(value, dict)
            )
            if own or not table:
                options.append((f"phases.{phase}", own))
            options.extend(
                (
                    f"phases.{phase}.{step}",
                    tuple((str(key), value) for key, value in nested.items()),
                )
                for step, nested in table.items()
                if isinstance(nested, dict)
            )
        publish = bool(release.get("publish", True))
        package = Package(
            directory=directory,
            path=f"{PACKAGES_DIR}/{member}",
            name=str(contract.get("name", "")),
            depends=depends,
            publish=publish,
            categories=tuple(reassigned),
            step_options=tuple(options),
            extensions=tuple(str(name) for name in contract.get("extensions", ())),
        )
        if (
            holds_runtime_language(package)
            and not (directory / "pyproject.toml").is_file()
        ):
            problems.append(
                f"{member}: holds {RUNTIME_LANGUAGE} and has no pyproject.toml"
            )
            continue
        packages.append(package)
    if problems:
        raise ValueError(
            "packages missing a file they need:\n  " + "\n  ".join(problems)
        )
    return tuple(packages)

holds_runtime_language

holds_runtime_language(package: Package) -> bool

Say whether package holds the extension of the workshop's own language.

That extension is python. A member holds it when it lists it, or when an extension it lists requires it. The workspace's own tests hold it when the root's set does. Discovery asks this of every member, so a member that lists it is answered without reading any extension's declaration.

Source code in packages/workshop/src/livery/workshop/_packages.py
def holds_runtime_language(package: Package) -> bool:
    """Say whether *package* holds the extension of the workshop's own language.

    That extension is ``python``. A member holds it when it lists it,
    or when an extension it lists requires it. The workspace's own
    tests hold it when the root's set does. Discovery asks this of
    every member, so a member that lists it is answered without
    reading any extension's declaration.
    """
    if RUNTIME_LANGUAGE in package.extensions:
        return True
    from livery.workshop._composition import extension_set

    return RUNTIME_LANGUAGE in extension_set(package)

neighbours

neighbours(packages: tuple[Package, ...]) -> Neighbours

Map each module root packages ship to the member that ships it.

Each member's set answers the roots it ships (livery.workshop.MODULE_ROOTS), so the map names no language. A member whose set answers no root owns no name.

Parameters:

Name Type Description Default
packages tuple[Package, ...]

The workspace's members, as livery.workshop.discover_packages reads them.

required

Returns:

Type Description
Neighbours

The roots by owner and the members by path.

Source code in packages/workshop/src/livery/workshop/_packages.py
def neighbours(packages: tuple[Package, ...]) -> Neighbours:
    """Map each module root *packages* ship to the member that ships it.

    Each member's set answers the roots it ships
    ([livery.workshop.MODULE_ROOTS][]), so the map names no language.
    A member whose set answers no root owns no name.

    Args:
        packages: The workspace's members, as
            [livery.workshop.discover_packages][] reads them.

    Returns:
        The roots by owner and the members by path.
    """
    from livery.workshop import _lifecycle

    owners: dict[str, str] = {}
    for package in packages:
        for prefix in _lifecycle.module_roots(package):
            owners[prefix] = package.path
    return Neighbours(owners=owners, by_path={p.path: p for p in packages})

package_directories

package_directories(root: Path) -> tuple[Path, ...]

List every directory under packages/ that should hold a package.

A package lives at packages/<name>/ or, inside a group directory, at packages/<group>/<name>/. A group is a directory with no workshop.toml of its own and at least one subdirectory that has one. The directories are listed whether or not they carry a contract, and nothing in them is judged; livery.workshop.discover_packages reads and judges the contracts. Reach for this where a glob would assume one level.

Parameters:

Name Type Description Default
root Path

The workspace root.

required

Returns:

Type Description
Path

The directories, sorted by path; empty when root has no

...

packages/ directory.

Source code in packages/workshop/src/livery/workshop/_packages.py
def package_directories(root: Path) -> tuple[Path, ...]:
    """List every directory under ``packages/`` that should hold a package.

    A package lives at ``packages/<name>/`` or, inside a group
    directory, at ``packages/<group>/<name>/``. A group is a directory
    with no ``workshop.toml`` of its own and at least one subdirectory
    that has one. The directories are listed whether or not they carry
    a contract, and nothing in them is judged;
    [livery.workshop.discover_packages][] reads and judges the
    contracts. Reach for this where a glob would assume one level.

    Args:
        root: The workspace root.

    Returns:
        The directories, sorted by path; empty when *root* has no
        ``packages/`` directory.
    """
    packages_dir = root / PACKAGES_DIR
    if not packages_dir.is_dir():
        return ()
    found: list[Path] = []
    for directory in (p for p in packages_dir.iterdir() if p.is_dir()):
        if is_group(directory):
            found.extend(p for p in directory.iterdir() if p.is_dir())
        else:
            found.append(directory)
    return tuple(sorted(found, key=lambda path: path.as_posix()))

release_tag

release_tag(tag: str) -> tuple[str, str] | None

The package path and version a release tag names; None for another tag.

A release tag is packages/<member>/v<major>.<minor>.<patch>, and the member may sit in a group directory: packages/extensions/widgets/v1.2.0 names ("packages/extensions/widgets", "1.2.0"). Every reader of release tags parses them here, so a package at any depth under packages/ releases like any other.

Source code in packages/workshop/src/livery/workshop/_packages.py
def release_tag(tag: str) -> tuple[str, str] | None:
    """The package path and version a release *tag* names; None for another tag.

    A release tag is ``packages/<member>/v<major>.<minor>.<patch>``, and
    the member may sit in a group directory:
    ``packages/extensions/widgets/v1.2.0`` names
    ``("packages/extensions/widgets", "1.2.0")``. Every reader of
    release tags parses them here, so a package at any depth under
    ``packages/`` releases like any other.
    """
    match = _RELEASE_TAG.fullmatch(tag)
    return (match.group(1), match.group(2)) if match else None

verify_workspace

verify_workspace(root: Path) -> tuple[Package, ...]

The layering lint: check every workspace invariant, or raise.

The graph's invariants (livery.workshop._packages.verify_graph) and the base's rules over every python source (livery.workshop._packages.import_problems) together, in one refusal. Returns the discovered packages when everything holds. Raises ValueError listing every violation verbatim otherwise:

  • every build edge appears in the native manifest with a constraint carrying its floor, and every workspace-internal native dependency is a declared edge (agreement both ways);
  • the dependency graph is acyclic, so dependencies only point downward;
  • the base imports no extension, and each reference a package's sources make to a sibling is a declared edge.
Source code in packages/workshop/src/livery/workshop/_packages.py
def verify_workspace(root: Path) -> tuple[Package, ...]:
    """The layering lint: check every workspace invariant, or raise.

    The graph's invariants ([livery.workshop._packages.verify_graph][]) and
    the base's rules over every python source
    ([livery.workshop._packages.import_problems][]) together, in one refusal.
    Returns the discovered packages when everything holds. Raises
    ValueError listing every violation verbatim otherwise:

    - every ``build`` edge appears in the native manifest with a
      constraint carrying its floor, and every workspace-internal
      native dependency is a declared edge (agreement both ways);
    - the dependency graph is acyclic, so dependencies only point
      downward;
    - the base imports no extension, and each reference a package's
      sources make to a sibling is a declared edge.
    """
    packages = discover_packages(root)
    problems = graph_problems(root, packages) + import_problems(root, packages)
    if problems:
        raise ValueError(
            "the workspace breaks its layering:\n  " + "\n  ".join(problems)
        )
    return packages

workspace_suite

workspace_suite(root: Path) -> Package | None

The workspace's own tests, the tests directory at its root, as a unit.

None when the workspace has none. The unit lists no extension and holds the root's set. A test step whose extensions that set holds runs it beside the members it judges (livery.workshop.scoped_suite). It is no member, so no package step judges it, and the workspace's category table answers for its files (is_workspace_unit).

Source code in packages/workshop/src/livery/workshop/_packages.py
def workspace_suite(root: Path) -> Package | None:
    """The workspace's own tests, the ``tests`` directory at its root, as a unit.

    ``None`` when the workspace has none. The unit lists no extension
    and holds the root's set. A test step whose extensions that set
    holds runs it beside the members it judges
    ([livery.workshop.scoped_suite][]). It is no member, so no package
    step judges it, and the workspace's category table answers for its
    files (`is_workspace_unit`).
    """
    directory = root / WORKSPACE_TESTS
    if not directory.is_dir():
        return None
    return Package(
        directory=directory,
        path=WORKSPACE_TESTS,
        name="workspace-tests",
        depends=(),
    )

run_phase

run_phase(root: Path, phase: str, *, outputs: Iterable[str] = ()) -> PhaseContext

Run a phase the gate never runs over the workspace at root; the shared context.

The steps the listed extensions register for phase, their own and those of the [for.<target>] tables that apply, run side by side through the walk every phase runs through, each workspace step once and each package step once per package whose set holds an extension it names. A workspace step that names extensions runs while a package holds one of them; while none does, a line says so and the step does not run. A phase with no registered step runs nothing.

Before the steps run, the paths a step declares under outputs are settled: each one the phase's last run recorded, or a step that does not run now declares, is removed unless a step that runs now declares it, and a line names each path removed. So a step that stops running, its extension unlisted or no longer installed or the step turned off, leaves nothing behind wherever it wrote, and a running step finds its own output as it left it. The record lives in the checkout's .workshop/state/.

Parameters:

Name Type Description Default
root Path

The workspace root.

required
phase str

The phase, one declared with gated = false.

required
outputs Iterable[str]

Paths this run writes that no step declares, such as those of the verbs a step runs: each in the shape a step declares one, and removed and recorded as a running step's are.

()

Returns:

Type Description
PhaseContext

The context the steps shared.

Raises:

Type Description
PhaseError

when nobody declares phase, naming the declared phases; when the gate runs it; or when an output in outputs is not a path below the root, or names docs/ itself.

Exception

the first failing step's, raised again once every step ran.

Source code in packages/workshop/src/livery/workshop/_phases.py
def run_phase(root: Path, phase: str, *, outputs: Iterable[str] = ()) -> PhaseContext:
    """Run a phase the gate never runs over the workspace at *root*; the shared context.

    The steps the listed extensions register for *phase*, their own and
    those of the ``[for.<target>]`` tables that apply, run side by side
    through the walk every phase runs through, each workspace step once
    and each package step once per package whose set holds an
    extension it names. A workspace step that names extensions runs
    while a package holds one of them; while none does, a line says so
    and the step does not run. A phase with no registered step runs
    nothing.

    Before the steps run, the paths a step declares under ``outputs``
    are settled: each one the phase's last run recorded, or a step that
    does not run now declares, is removed unless a step that runs now
    declares it, and a line names each path removed. So a step that
    stops running, its extension unlisted or no longer installed or the
    step turned off, leaves nothing behind wherever it wrote, and a
    running step finds its own output as it left it. The record lives
    in the checkout's ``.workshop/state/``.

    Args:
        root: The workspace root.
        phase: The phase, one declared with ``gated = false``.
        outputs: Paths this run writes that no step declares, such as
            those of the verbs a step runs: each in the shape a step
            declares one, and removed and recorded as a running step's
            are.

    Returns:
        The context the steps shared.

    Raises:
        PhaseError: when nobody declares *phase*, naming the declared
            phases; when the gate runs it; or when an output in
            *outputs* is not a path below the root, or names ``docs/``
            itself.
        Exception: the first failing step's, raised again once every
            step ran.
    """
    from livery.workshop._packages import discover_packages

    spec = phase_spec(phase)
    if spec.gated:
        raise PhaseError(
            f"the gate runs the {phase} phase; run_phase runs a phase declared"
            " with gated = false, and run_phase_over runs a gated phase's steps"
            " over named packages"
        )
    given = tuple(outputs)
    for output in given:
        refusal = output_refusal(output)
        if refusal:
            raise PhaseError(f"an output of the {phase} phase {refusal}")
    ctx = PhaseContext(root=root, packages=discover_packages(root), phase=phase)
    running, idle = _registered(ctx)
    _remove_outputs(
        root,
        phase,
        (*(o for record in running for o in record.outputs), *given),
        tuple(o for record in idle for o in record.outputs),
        ctx.packages,
    )
    return walk_steps(ctx, running)

check_legs

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

Name the check legs the gate produces, check-<os>-<python> each.

One per runner the root contract names ([ci] runners, ubuntu-latest without it) and Python the gate runs: the contract's [ci] python-versions, or the newest Python of the derived matrix. Each label is spelled as the job runner names the leg it runs, the key of the leg's rows on the state store.

Source code in packages/workshop/src/livery/workshop/_points.py
def check_legs(root: Path) -> list[str]:
    """Name the check legs the gate produces, ``check-<os>-<python>`` each.

    One per runner the root contract names (``[ci] runners``,
    ``ubuntu-latest`` without it) and Python the gate runs: the
    contract's ``[ci] python-versions``, or the newest Python of the
    derived matrix. Each label is spelled as the job runner names the
    leg it runs, the key of the leg's rows on the state store.
    """
    from livery.workshop._pythons import gate_pythons

    contract = load_contract(root / "workshop.toml")
    runners = list((contract.get("ci") or {}).get("runners") or ["ubuntu-latest"])
    pythons = gate_pythons(root)
    return [f"check-{runner}-{python}" for runner in runners for python in pythons]

check_shards

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

Name the shard legs the gate produces, split as [ci] shards says.

One leg per runner and Python livery.workshop.check_legs names, spelled as that leg, check-<os>-<python>, for a count of one, the count of every runner the table does not name; and check-<os>-<python>-<i>of<n> for each of the n shards otherwise, in order. [ci] shards-max caps a count, 4 when absent. The task fails, naming the key and the runner, when the table names a runner [ci] runners does not list, gives a count below 1 or above the cap, or gives one that is not a whole number.

Source code in packages/workshop/src/livery/workshop/_points.py
def check_shards(root: Path) -> list[str]:
    """Name the shard legs the gate produces, split as ``[ci] shards`` says.

    One leg per runner and Python [livery.workshop.check_legs][] names,
    spelled as that leg, ``check-<os>-<python>``, for a count of one,
    the count of every runner the table does not name; and
    ``check-<os>-<python>-<i>of<n>`` for each of the ``n`` shards
    otherwise, in order. ``[ci] shards-max`` caps a count, 4 when
    absent. The task fails, naming the key and the runner, when the
    table names a runner ``[ci] runners`` does not list, gives a count
    below 1 or above the cap, or gives one that is not a whole number.
    """
    from livery.workshop._pythons import gate_pythons

    contract = load_contract(root / "workshop.toml")
    ci = contract.get("ci") or {}
    runners = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
    counts = shard_counts(ci, key="shards", runners=runners, listed="[ci] runners")
    return _shard_legs(runners, gate_pythons(root), counts)

pull_request_legs

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

Name the check legs a pull request's run produces, check-<os>-<python> each.

One per runner the root contract's [ci] pull-request-runners names and Python the gate runs; the first runner's legs among those livery.workshop.check_legs names when the key is absent. The task fails, naming both lists, when the key names a runner [ci] runners does not list, and when it is empty.

Source code in packages/workshop/src/livery/workshop/_points.py
def pull_request_legs(root: Path) -> list[str]:
    """Name the check legs a pull request's run produces, ``check-<os>-<python>`` each.

    One per runner the root contract's ``[ci] pull-request-runners``
    names and Python the gate runs; the first runner's legs among those
    [livery.workshop.check_legs][] names when the key is absent. The
    task fails, naming both lists, when the key names a runner
    ``[ci] runners`` does not list, and when it is empty.
    """
    from livery.workshop._pythons import gate_pythons

    contract = load_contract(root / "workshop.toml")
    ci = contract.get("ci") or {}
    pythons = gate_pythons(root)
    return [
        f"check-{runner}-{python}"
        for runner in pull_request_runners(ci)
        for python in pythons
    ]

pull_request_shards

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

Name the shard legs a pull request's run produces, split as the contract says.

One leg per runner and Python livery.workshop.pull_request_legs names, split as livery.workshop.check_shards splits the gate's: by [ci] pull-request-shards, judged against the pull request's runners, or by [ci] shards when that key is absent. The task fails as check_shards fails, and as pull_request_legs fails.

Source code in packages/workshop/src/livery/workshop/_points.py
def pull_request_shards(root: Path) -> list[str]:
    """Name the shard legs a pull request's run produces, split as the contract says.

    One leg per runner and Python [livery.workshop.pull_request_legs][]
    names, split as [livery.workshop.check_shards][] splits the gate's:
    by ``[ci] pull-request-shards``, judged against the pull request's
    runners, or by ``[ci] shards`` when that key is absent. The task
    fails as `check_shards` fails, and as `pull_request_legs` fails.
    """
    from livery.workshop._pythons import gate_pythons

    contract = load_contract(root / "workshop.toml")
    ci = contract.get("ci") or {}
    runners = pull_request_runners(ci)
    if ci.get("pull-request-shards") is None:
        every = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
        counts = shard_counts(ci, key="shards", runners=every, listed="[ci] runners")
    else:
        counts = shard_counts(
            ci,
            key="pull-request-shards",
            runners=runners,
            listed=pull_request_listed(ci),
        )
    return _shard_legs(runners, gate_pythons(root), counts)

guidance

guidance(root: Path, audience: str) -> list[Prose]

The guidance one reader gets in the workspace at root, in reading order.

audience is livery.workshop.AGENT or livery.workshop.HUMAN. The set is every fragment the mounted extensions ship, every fragment the base renders, and the repository's own under fragments/: by section, then by extension in mount order, the repository's own last, then by name. A fragment written for the other reader is left out.

Raises:

Type Description
ValueError

when two fragments in the set deliver under one name, naming both.

Source code in packages/workshop/src/livery/workshop/_prose.py
def guidance(root: Path, audience: str) -> list[Prose]:
    """The guidance one reader gets in the workspace at *root*, in reading order.

    *audience* is [livery.workshop.AGENT][] or [livery.workshop.HUMAN][].
    The set is every fragment the mounted extensions ship, every
    fragment the base renders, and the repository's own under
    ``fragments/``: by section, then by extension in mount order, the
    repository's own last, then by name. A fragment written for the
    other reader is left out.

    Raises:
        ValueError: when two fragments in the set deliver under one name,
            naming both.
    """
    return fragments(root, in_play(root), audience)

generated_header

generated_header(style: str, lines: tuple[str, ...] = ()) -> str

The provenance header a generated file opens with, as a comment block.

style is the file's comment marker (# or //), or html for a <!-- --> block. lines say what writes the file and how a reader changes it, for a file an extension writes outside the engine; without them, the header says what every artifact the engine emits says: the contract is the source, and an edit here is drift.

Source code in packages/workshop/src/livery/workshop/_provenance.py
def generated_header(style: str, lines: tuple[str, ...] = ()) -> str:
    """The provenance header a generated file opens with, as a comment block.

    *style* is the file's comment marker (``#`` or ``//``), or ``html``
    for a ``<!-- -->`` block. *lines* say what writes the file and how
    a reader changes it, for a file an extension writes outside the
    engine; without them, the header says what every artifact the
    engine emits says: the contract is the source, and an edit here is
    drift.
    """
    if not lines:
        prog = footman.prog()
        lines = (
            "Generated by the workshop from workshop.toml; the gate keeps",
            "it matching. Edit the contract (or the emitters) and run",
            f"`{prog} sync`; an edit here is drift.",
        )
    return format_header(lines, style)

discover_release

discover_release(root: Path, ref: str) -> tuple[tuple[Package, str], ...]

The members the release squash at ref releases, each with its version.

The members and their versions are the release's member list, .release-manifest.json, as committed at ref: the record the release branch writes when it prepares the set. They come in release order, every dependency before its dependents (livery.workshop.order_topologically). A rider file in the squash changes nothing here, which is what makes hand-editing a release branch safe.

Parameters:

Name Type Description Default
root Path

The workspace root.

required
ref str

The commit whose member list is read, as git names it.

required

Returns:

Type Description
tuple[tuple[Package, str], ...]

Each released member and the version the list states for it.

Raises:

Type Description
Failed

when the commit carries no readable member list, since it is then no release squash, naming the flag that points the publish at the squash; and when the list names a member the workspace does not hold.

Source code in packages/workshop/src/livery/workshop/_publish.py
def discover_release(root: Path, ref: str) -> tuple[tuple[Package, str], ...]:
    """The members the release squash at *ref* releases, each with its version.

    The members and their versions are the release's member list,
    ``.release-manifest.json``, as committed at *ref*: the record the
    release branch writes when it prepares the set. They come in
    release order, every dependency before its dependents
    ([livery.workshop.order_topologically][]). A rider file in the
    squash changes nothing here, which is what makes hand-editing a
    release branch safe.

    Args:
        root: The workspace root.
        ref: The commit whose member list is read, as git names it.

    Returns:
        Each released member and the version the list states for it.

    Raises:
        Failed: when the commit carries no readable member list, since
            it is then no release squash, naming the flag that points
            the publish at the squash; and when the list names a member
            the workspace does not hold.
    """
    from livery.workshop._graph import order_topologically

    pairs = read_manifest(git.file_at(root, ref, MANIFEST))
    if pairs is None:
        fail(
            f"this commit is not a release squash: it carries no readable"
            f" {MANIFEST}, the member list a release branch commits. Publish"
            " runs on the merge commit of a workflow.release PR; pass"
            " --ref=<squash sha> when HEAD has moved past it."
        )
    listed = {p.member: p for p in discover_packages(root)}
    chosen: list[Package] = []
    stated: dict[str, str] = {}
    for name, version in pairs:
        member = listed.get(name)
        if member is None:
            fail(
                f"the release manifest at {ref[:10]} names"
                f" packages/{name}, which is not a workspace package"
            )
        chosen.append(member)
        stated[member.path] = version
    in_order = order_topologically(tuple(chosen))
    return tuple((member, stated[member.path]) for member in in_order)

python_matrix

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

The CI matrix: the contract's declaration, else the floor and the newest minor.

[ci] python-versions in the root's workshop.toml wins where declared, so a development workspace runs one leg and a production contract keeps the full pair. Without it the pair derives: the lower bound of the root pyproject.toml's requires-python, and the newest minor the workshop tests against, so a new Python reaches every instance through a wheel bump. Each entry is a version such as 3.14, or 3.14t for a free-threaded build: in the declared order, or the floor first.

Raises:

Type Description
Failed

naming the key, when [ci] python-versions is not a non-empty list of such versions.

Source code in packages/workshop/src/livery/workshop/_pythons.py
def python_matrix(root: Path) -> list[str]:
    """The CI matrix: the contract's declaration, else the floor and the newest minor.

    ``[ci] python-versions`` in the root's ``workshop.toml`` wins where
    declared, so a development workspace runs one leg and a production
    contract keeps the full pair. Without it the pair derives: the
    lower bound of the root ``pyproject.toml``'s ``requires-python``,
    and the newest minor the workshop tests against, so a new Python
    reaches every instance through a wheel bump. Each entry is a
    version such as ``3.14``, or ``3.14t`` for a free-threaded build: in
    the declared order, or the floor first.

    Raises:
        Failed: naming the key, when ``[ci] python-versions`` is not a
            non-empty list of such versions.
    """
    declared = declared_pythons(root)
    if declared is not None:
        return declared
    floor = python_floor(root)
    if _minor(floor) >= _minor(NEWEST_SUPPORTED):
        return [floor]
    return [floor, NEWEST_SUPPORTED]

scripts_dir

scripts_dir(venv: Path) -> Path

Name venv's executables directory: Scripts on Windows, bin elsewhere.

The running platform decides: a venv is used on the machine that made it. Nothing is read from the disk, so the venv may not exist yet.

Parameters:

Name Type Description Default
venv Path

The venv's directory.

required

Returns:

Type Description
Path

The directory its interpreter and its console scripts are in.

Source code in packages/workshop/src/livery/workshop/_pythons.py
def scripts_dir(venv: Path) -> Path:
    """Name *venv*'s executables directory: ``Scripts`` on Windows, ``bin`` elsewhere.

    The running platform decides: a venv is used on the machine that
    made it. Nothing is read from the disk, so the venv may not exist
    yet.

    Args:
        venv: The venv's directory.

    Returns:
        The directory its interpreter and its console scripts are in.
    """
    return venv / ("Scripts" if sys.platform == "win32" else "bin")

venv_python

venv_python(venv: Path) -> Path

Name venv's interpreter on this platform.

python.exe in livery.workshop.scripts_dir on Windows, and python there elsewhere. Nothing is read from the disk, so the venv may not exist yet.

Parameters:

Name Type Description Default
venv Path

The venv's directory.

required

Returns:

Type Description
Path

The interpreter's path.

Source code in packages/workshop/src/livery/workshop/_pythons.py
def venv_python(venv: Path) -> Path:
    """Name *venv*'s interpreter on this platform.

    ``python.exe`` in [livery.workshop.scripts_dir][] on Windows, and
    ``python`` there elsewhere. Nothing is read from the disk, so the
    venv may not exist yet.

    Args:
        venv: The venv's directory.

    Returns:
        The interpreter's path.
    """
    return scripts_dir(venv) / ("python.exe" if sys.platform == "win32" else "python")

ci_changes

ci_changes(root: Path) -> Changes | None

What this CI run changed against the base it measures from; None for everything.

A pull request's run in a workspace that declares [ci] affected-legs measures from its base branch: the paths changed since the merge base with origin/<base>, committed or not, with that merge base, so a widen reference can read a file as it was. None at a desk, on any other event, without affected-legs, and when git cannot answer; the run then judges everything, and the line printed says why.

Source code in packages/workshop/src/livery/workshop/_quality.py
def ci_changes(root: Path) -> Changes | None:
    """What this CI run changed against the base it measures from; None for everything.

    A pull request's run in a workspace that declares ``[ci]
    affected-legs`` measures from its base branch: the paths changed
    since the merge base with ``origin/<base>``, committed or not, with
    that merge base, so a ``widen`` reference can read a file as it
    was. None at a desk, on any other event, without
    ``affected-legs``, and when git cannot answer; the run then judges
    everything, and the line printed says why.
    """
    from livery.workshop._ci_context import run_context
    from livery.workshop._influence import Changes

    run = run_context()
    base = ci_affected_base(root, run) if run is not None else ""
    if not base:
        return None
    try:
        git.fetch(root)
        paths = tuple(git.changed_paths(root, base))
        before = git.merge_base(root, base)
    except git.GitError as error:
        print(
            f"  affected-legs: no diff against origin/{base}; everything is"
            f" judged ({error})"
        )
        return None
    return Changes(root, paths, before)

fix_files

fix_files(paths: tuple[str, ...], *, safe: bool = True) -> None

Run the gate's fixers over paths, judging nothing.

Every step whose claims reach a file fixes it, and a file no claim reaches is left alone. safe keeps to the fixes a step marks safe, which never remove code an edit in flight still needs; an agent's post-edit hook runs it after each edit.

Source code in packages/workshop/src/livery/workshop/_quality.py
def fix_files(paths: tuple[str, ...], *, safe: bool = True) -> None:
    """Run the gate's fixers over *paths*, judging nothing.

    Every step whose claims reach a file fixes it, and a file no claim
    reaches is left alone. *safe* keeps to the fixes a step marks
    safe, which never remove code an edit in flight still needs; an
    agent's post-edit hook runs it after each edit.
    """
    _check_files(paths, fix=True, safe=safe, point="", judge=False)

run_phase_over

run_phase_over(phase: str, packages: tuple[Package, ...]) -> None

Run the steps of phase over packages whole; nothing recorded as proved.

The gate's walk (livery.workshop._quality.walk) narrowed to the steps the extensions register for phase, and the steps they run after, over the named packages alone, with the gate's inputs. A package no step of the phase judges is skipped by the walk, and a phase with no step runs nothing. An extension runs a phase this way over packages the gate did not run it on. Inside CI the leg's label names the shard the run is, as check reads it without the flag.

Source code in packages/workshop/src/livery/workshop/_quality.py
def run_phase_over(phase: str, packages: tuple[Package, ...]) -> None:
    """Run the steps of *phase* over *packages* whole; nothing recorded as proved.

    The gate's walk ([livery.workshop._quality.walk][]) narrowed to the
    steps the extensions register for *phase*, and the steps they run
    after, over the named packages alone, with the gate's inputs. A
    package no step of the phase judges is skipped by the walk, and a
    phase with no step runs nothing. An extension runs a phase this
    way over packages the gate did not run it on. Inside CI the leg's
    label names the shard the run is, as `check` reads it without the
    flag.
    """
    names = tuple(
        record.name
        for record in _steps.steps_by_name().values()
        if record.phase == phase
    )
    if not names:
        return
    walk(_context(subset=packages, shard=_current_shard()), only=frozenset(names))

answer

answer(subject: Package | Path, query: Query[T], *, lookup: Lookup | None = None) -> T

The answer to query about subject: the extensions' answers, combined.

subject is the package for a package-level query, answered by its set in composition order, and the workspace root, or a directory in the workspace, for a workspace-level one, answered by the installed set in composition order. With no extension answering, the query's declared default, or its rule's answer over nothing.

Raises:

Type Description
QueryError

when no extension declares the query, when subject is at the other level, when an answer is off the query's values, or when the answers break the query's rule; the message names the query and the extensions, and a package's path for a package-level query.

Source code in packages/workshop/src/livery/workshop/_queries.py
def answer(
    subject: Package | Path, query: Query[T], *, lookup: Lookup | None = None
) -> T:
    """The answer to *query* about *subject*: the extensions' answers, combined.

    *subject* is the package for a package-level query, answered by its
    set in composition order, and the workspace root, or a directory in
    the workspace, for a workspace-level one, answered by the installed
    set in composition order. With no extension answering, the query's
    declared default, or its rule's answer over nothing.

    Raises:
        QueryError: when no extension declares the query, when *subject*
            is at the other level, when an answer is off the query's
            values, or when the answers break the query's rule; the
            message names the query and the extensions, and a package's
            path for a package-level query.
    """
    if lookup is None:
        from livery.workshop._extensions import installed_declaration

        lookup = installed_declaration
    spec = query_spec(query.name)
    found = answers(subject, query, lookup=lookup)
    if not found and spec.default is not None:
        return cast("T", spec.default)
    combine: Combine = (
        RULES[spec.combine] if isinstance(spec.combine, str) else spec.combine
    )
    where = "" if isinstance(subject, Path) else f"{subject.path}: "
    try:
        return cast("T", combine(found, lookup))
    except (QueryError, ValueError) as error:
        raise QueryError(f"{where}{query.name}: {error}") from None

registry

registry(root: Path, kind: str) -> RegistryTarget

The registry the workspace at root reads and publishes kind artifacts at.

kind is python, conan or container. The first rung that names one wins: the environment's variables for the kind, the contract's [registries] table, the forge's own registry of the kind, then the ecosystem's default.

Raises:

Type Description
Failed

when kind is not an artifact registry kind, naming the three.

Source code in packages/workshop/src/livery/workshop/_registries.py
def registry(root: Path, kind: str) -> RegistryTarget:
    """The registry the workspace at *root* reads and publishes *kind* artifacts at.

    *kind* is ``python``, ``conan`` or ``container``. The first rung
    that names one wins: the environment's variables for the kind, the
    contract's ``[registries]`` table, the forge's own registry of the
    kind, then the ecosystem's default.

    Raises:
        Failed: when *kind* is not an artifact registry kind, naming
            the three.
    """
    return resolve_registry(root, kind)

release_notes

release_notes(root: Path) -> ReleaseNotes | None

The provider the extensions listed at root answer; None when none answers.

The answer is imported when first asked, so a mount imports none of the answering extension's code.

Raises:

Type Description
QueryError

when two listed extensions answer and neither requires the other, naming both.

Source code in packages/workshop/src/livery/workshop/_release_notes.py
def release_notes(root: Path) -> ReleaseNotes | None:
    """The provider the extensions listed at *root* answer; None when none answers.

    The answer is imported when first asked, so a mount imports none
    of the answering extension's code.

    Raises:
        QueryError: when two listed extensions answer and neither
            requires the other, naming both.
    """
    return answer(root, RELEASE_NOTES)

checkout_time

checkout_time(root: Path) -> datetime

The committer time of HEAD's commit in the checkout at root, timezone-aware.

Every shard of a run checks out the same commit, so this bounds the durations rows every shard reads without a call to the forge.

Raises:

Type Description
GitError

When HEAD names no commit.

Source code in packages/workshop/src/livery/workshop/_shard.py
def checkout_time(root: Path) -> datetime:
    """The committer time of HEAD's commit in the checkout at *root*, timezone-aware.

    Every shard of a run checks out the same commit, so this bounds
    the durations rows every shard reads without a call to the forge.

    Raises:
        GitError: When HEAD names no commit.
    """
    spelled = git.run(root, "log", "-1", "--format=%cI", "HEAD").strip()
    return datetime.fromisoformat(spelled)

files_digest

files_digest(files: Iterable[str]) -> str

A hex digest of the sorted names in files.

Two shards that partitioned one set have one digest, so the gate job can prove they did.

Source code in packages/workshop/src/livery/workshop/_shard.py
def files_digest(files: Iterable[str]) -> str:
    """A hex digest of the sorted names in *files*.

    Two shards that partitioned one set have one digest, so the gate
    job can prove they did.
    """
    text = "\n".join(sorted(set(files)))
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

leave_shard

leave_shard(root: Path, *, shard: Shard, digest: str, items: Iterable[str], rows: Iterable[str], before: datetime, suites: Iterable[str] = (), attempt: str = '') -> Path

Leave the shard's record in SHARD_FILE at root, for the gate job's proof.

suites names the units whose items are in the set; a unit left out ran whole on the first shard. attempt is the run's attempt the shard ran in, the run context's; empty when unknown. The leg's one write copies the record into its timing row under shard, where the gate job's fold reads it.

Returns:

Type Description
Path

The path of the file left.

Source code in packages/workshop/src/livery/workshop/_shard.py
def leave_shard(
    root: Path,
    *,
    shard: Shard,
    digest: str,
    items: Iterable[str],
    rows: Iterable[str],
    before: datetime,
    suites: Iterable[str] = (),
    attempt: str = "",
) -> Path:
    """Leave the shard's record in `SHARD_FILE` at *root*, for the gate job's proof.

    *suites* names the units whose items are in the set; a unit
    left out ran whole on the first shard. *attempt* is the run's
    attempt the shard ran in, the run context's; empty when unknown.
    The leg's one write copies the record into its timing row under
    ``shard``, where the gate job's fold reads it.

    Returns:
        The path of the file left.
    """
    path = root / SHARD_FILE
    path.parent.mkdir(parents=True, exist_ok=True)
    marker = ShardMarker(
        shard, digest, tuple(items), tuple(rows), before, tuple(suites), attempt
    )
    path.write_text(json.dumps(marker_fields(marker), sort_keys=True), encoding="utf-8")
    return path

partition

partition(items: Iterable[str], durations: Mapping[str, float], count: int, *, head: float = 0.0) -> tuple[tuple[str, ...], ...]

Pack items into count shards by their durations, every item in exactly one.

The items go longest first, ties by name, each into the shard with the least summed seconds so far, ties to the lowest shard. The first shard's sum starts at head seconds, the time of the steps it runs that the other shards leave to it, so its share of the items is lighter by about that much; a head above every other shard's final sum leaves the first shard no item. An item durations does not name weighs the median of the named durations, or one second when none are named. The result is a function of the set, the durations and the head alone: the same whatever order items comes in, and an item given twice is one item. With more shards than items the surplus shards are empty.

Returns:

Type Description
tuple[str, ...]

One tuple of items per shard, in the order the items were

...

packed.

Raises:

Type Description
ValueError

When count is below 1, or head is below 0.

Source code in packages/workshop/src/livery/workshop/_shard.py
def partition(
    items: Iterable[str],
    durations: Mapping[str, float],
    count: int,
    *,
    head: float = 0.0,
) -> tuple[tuple[str, ...], ...]:
    """Pack *items* into *count* shards by their *durations*, every item in exactly one.

    The items go longest first, ties by name, each into the shard with
    the least summed seconds so far, ties to the lowest shard. The
    first shard's sum starts at *head* seconds, the time of the steps
    it runs that the other shards leave to it, so its share of the
    items is lighter by about that much; a head above every other
    shard's final sum leaves the first shard no item. An item
    *durations* does not name weighs the median of the named
    durations, or one second when none are named. The result is a
    function of the set, the durations and the head alone: the same
    whatever order *items* comes in, and an item given twice is one
    item. With more shards than items the surplus shards are empty.

    Returns:
        One tuple of items per shard, in the order the items were
        packed.

    Raises:
        ValueError: When *count* is below 1, or *head* is below 0.
    """
    if count < 1:
        raise ValueError(f"count is {count}; a partition has at least one shard")
    if head < 0:
        raise ValueError(f"head is {head}; a head is at least 0 seconds")
    named = [float(seconds) for seconds in durations.values()]
    fill = statistics.median(named) if named else 1.0

    def weight(name: str) -> float:
        seconds = durations.get(name)
        return float(seconds) if seconds is not None else fill

    ordered = sorted(set(items), key=lambda name: (-weight(name), name))
    shards: list[list[str]] = [[] for _ in range(count)]
    sums = [0.0] * count
    sums[0] = float(head)
    for name in ordered:
        at = min(range(count), key=lambda index: (sums[index], index))
        shards[at].append(name)
        sums[at] += weight(name)
    return tuple(tuple(shard) for shard in shards)

platform_leg

platform_leg(label: str) -> str

The leg label without its shard; a label without one is returned as it is.

check-windows-latest-3.14-2of4 gives check-windows-latest-3.14.

Source code in packages/workshop/src/livery/workshop/_shard.py
def platform_leg(label: str) -> str:
    """The leg *label* without its shard; a label without one is returned as it is.

    ``check-windows-latest-3.14-2of4`` gives ``check-windows-latest-3.14``.
    """
    matched = _TAIL.match(label)
    return matched.group("leg") if matched else label

read_durations

read_durations(root: Path, leg: str, *, before: datetime) -> tuple[dict[str, float], float, tuple[str, ...], str]

The median seconds per item, and the head, of leg's rows before before.

The rows are the newest NEWEST of the series durations/<platform leg> whose store stamp is before before; a row stamped at or after it, or not stamped, is not read, so every shard of a run reads the same rows whatever lands while the run is in flight. The median of an item is over the rows that name it with a number under items. The head is the median of every row read's head, a row without a number there counting as 0, and is what livery.workshop.partition starts the first shard's sum at. A naive before is read as UTC.

Returns:

Type Description
dict[str, float]

The seconds per item, the head in seconds, the names of the

float

rows read, newest first, and why the series could not be read.

tuple[str, ...]

A series that cannot be read is ({}, 0.0, (), reason),

str

never a raise: the caller runs as one shard of one and says

tuple[dict[str, float], float, tuple[str, ...], str]

so. An absent series is ({}, 0.0, (), "").

Source code in packages/workshop/src/livery/workshop/_shard.py
def read_durations(
    root: Path, leg: str, *, before: datetime
) -> tuple[dict[str, float], float, tuple[str, ...], str]:
    """The median seconds per item, and the head, of *leg*'s rows before *before*.

    The rows are the newest `NEWEST` of the series ``durations/<platform
    leg>`` whose store stamp is before *before*; a row stamped at or
    after it, or not stamped, is not read, so every shard of a run
    reads the same rows whatever lands while the run is in flight. The
    median of an item is over the rows that name it with a number
    under ``items``. The head is the median of every row read's
    ``head``, a row without a number there counting as 0, and is what
    [livery.workshop.partition][] starts the first shard's sum at. A
    naive *before* is read as UTC.

    Returns:
        The seconds per item, the head in seconds, the names of the
        rows read, newest first, and why the series could not be read.
        A series that cannot be read is ``({}, 0.0, (), reason)``,
        never a raise: the caller runs as one shard of one and says
        so. An absent series is ``({}, 0.0, (), "")``.
    """
    bound = before if before.tzinfo is not None else before.replace(tzinfo=UTC)
    series = DURATIONS.series(platform_leg(leg))
    found = series.rows(state_store(root))
    if found.failed:
        return {}, 0.0, (), found.reason
    chosen: list[git.Row] = []
    for row in found.rows:
        when = _moment(row.when)
        if when is None or when >= bound:
            continue
        chosen.append(row)
        if len(chosen) == NEWEST:
            break
    seen: dict[str, list[float]] = defaultdict(list)
    for row in chosen:
        held: Any = row.data.get("items")
        if not isinstance(held, dict):
            continue
        for name, seconds in held.items():
            if isinstance(seconds, int | float) and not isinstance(seconds, bool):
                seen[str(name)].append(float(seconds))
    medians = {
        name: round(statistics.median(values), 1)
        for name, values in sorted(seen.items())
    }
    heads = [_seconds(row.data.get("head")) for row in chosen]
    head = round(statistics.median(heads), 1) if heads else 0.0
    return medians, head, tuple(row.name for row in chosen), ""

read_shard

read_shard(root: Path) -> tuple[ShardMarker | None, str]

Read the record a shard left in SHARD_FILE at root.

Returns:

Type Description
ShardMarker | None

(record, "") when it reads; (None, "") when there is no

str

file; (None, reason) when the file is not a record.

Source code in packages/workshop/src/livery/workshop/_shard.py
def read_shard(root: Path) -> tuple[ShardMarker | None, str]:
    """Read the record a shard left in `SHARD_FILE` at *root*.

    Returns:
        ``(record, "")`` when it reads; ``(None, "")`` when there is no
        file; ``(None, reason)`` when the file is not a record.
    """
    path = root / SHARD_FILE
    if not path.is_file():
        return None, ""
    try:
        loaded: Any = json.loads(path.read_text("utf-8"))
    except (OSError, ValueError) as error:
        return None, f"{SHARD_FILE} does not parse ({error})"
    return parse_marker(loaded, source=SHARD_FILE)

shard_of

shard_of(label: str) -> Shard

The shard the leg label ends in; ONE when it ends in none.

Raises:

Type Description
ValueError

When the label ends in a shard spelling outside the form, such as 0of2, naming it.

Source code in packages/workshop/src/livery/workshop/_shard.py
def shard_of(label: str) -> Shard:
    """The shard the leg *label* ends in; `ONE` when it ends in none.

    Raises:
        ValueError: When the label ends in a shard spelling outside the
            form, such as ``0of2``, naming it.
    """
    matched = _TAIL.match(label)
    return Shard.parse(matched.group("shard")) if matched else ONE

package_of

package_of(nodeid: str) -> str

Name the workspace package a test belongs to, from its pytest node id.

The package is the path before the first directory a package keeps its tests or sources in, tests, src or docs: packages/forge/tests/test_x.py::test_y belongs to packages/forge. A package in a group directory is one level deeper, and its own name may be one of those three: in packages/extensions/docs/tests/test_x.py::test_y the tests beneath docs says docs is the package, so the answer is packages/extensions/docs. Nothing is read from the disk.

Parameters:

Name Type Description Default
nodeid str

A test's node id, relative to the workspace root.

required

Returns:

Type Description
str

The package's path relative to the workspace root, or "" for

str

a node outside packages/, such as a workspace test under

str

tests/.

Source code in packages/workshop/src/livery/workshop/_speed.py
def package_of(nodeid: str) -> str:
    """Name the workspace package a test belongs to, from its pytest node id.

    The package is the path before the first directory a package keeps
    its tests or sources in, ``tests``, ``src`` or ``docs``:
    ``packages/forge/tests/test_x.py::test_y`` belongs to
    ``packages/forge``. A package in a group directory is one level
    deeper, and its own name may be one of those three: in
    ``packages/extensions/docs/tests/test_x.py::test_y`` the ``tests``
    beneath ``docs`` says ``docs`` is the package, so the answer is
    ``packages/extensions/docs``. Nothing is read from the disk.

    Args:
        nodeid: A test's node id, relative to the workspace root.

    Returns:
        The package's path relative to the workspace root, or ``""`` for
        a node outside ``packages/``, such as a workspace test under
        ``tests/``.
    """
    parts = nodeid.split("::", 1)[0].split("/")
    if len(parts) < 3 or parts[0] != "packages":
        return ""
    for index in range(2, len(parts) - 1):
        if parts[index] not in PACKAGE_TREES:
            continue
        if index == 2 and parts[3] in PACKAGE_TREES and len(parts) > 4:
            continue
        return "/".join(parts[:index])
    return "/".join(parts[:2])

speed_marks

speed_marks(root: Path) -> tuple[dict[tuple[str, str], SpeedMark] | None, str]

Read each package's current test-time mark on each check leg.

The marks live on the checkout's state store (livery.workshop.state_store). The newest row per package and leg is its mark. A row that does not parse, is of another schema, or lacks a mark's fields is skipped, so one bad row disables nothing. A store that cannot be read falls open: the caller prints the reason and judges nothing.

Parameters:

Name Type Description Default
root Path

The checkout whose state store holds the marks.

required

Returns:

Type Description
dict[tuple[str, str], SpeedMark] | None

Each mark by its package's path and its leg, with an empty

str

reason; an empty store gives ({}, ""). When the store

tuple[dict[tuple[str, str], SpeedMark] | None, str]

cannot be read, None and the reason.

Source code in packages/workshop/src/livery/workshop/_speed.py
def speed_marks(root: Path) -> tuple[dict[tuple[str, str], SpeedMark] | None, str]:
    """Read each package's current test-time mark on each check leg.

    The marks live on the checkout's state store
    ([livery.workshop.state_store][]). The newest row per package and
    leg is its mark. A row that does not parse, is of another schema,
    or lacks a mark's fields is skipped, so one bad row disables
    nothing. A store that cannot be read falls open: the caller prints
    the reason and judges nothing.

    Args:
        root: The checkout whose state store holds the marks.

    Returns:
        Each mark by its package's path and its leg, with an empty
        reason; an empty store gives ``({}, "")``. When the store
        cannot be read, None and the reason.
    """
    found = SERIES.rows(state_store(root))
    if found.failed:
        return None, found.reason
    current: dict[tuple[str, str], SpeedMark] = {}
    for row in found.rows:
        mark = _mark(row.data)
        if mark is not None:
            current.setdefault((mark.package, mark.leg), mark)
    return current, ""

graph_changed

graph_changed(changes: Changes) -> bool

Tell whether a contract, a native manifest or a root src/ changed.

A step over a language's sources widens on it through its widen reference, a function of its own extension that calls this one: the members, their module roots and what they declare come from these files, so a change to one judges every source again, as the base's own layering steps do. Prose and the licence beside a manifest never count.

Parameters:

Name Type Description Default
changes Changes

What the run changed, as a step's widen reference receives it.

required

Returns:

Type Description
bool

True when a changed path is the root contract, a file directly

bool

in a member's directory, or a file under src/ at the root.

Source code in packages/workshop/src/livery/workshop/_steps.py
def graph_changed(changes: Changes) -> bool:
    """Tell whether a contract, a native manifest or a root ``src/`` changed.

    A step over a language's sources widens on it through its
    ``widen`` reference, a function of its own extension that calls
    this one: the members, their module roots and what they declare
    come from these files, so a change to one judges every source
    again, as the base's own layering steps do. Prose and the licence
    beside a manifest never count.

    Args:
        changes: What the run changed, as a step's ``widen`` reference
            receives it.

    Returns:
        True when a changed path is the root contract, a file directly
        in a member's directory, or a file under ``src/`` at the root.
    """
    from livery.workshop._categories import matches

    patterns = graph_files(changes.root)
    return any(
        matches(pattern, path)
        for path in changes.paths
        if not any(matches(ignored, path) for ignored in NOT_INPUTS)
        for pattern in patterns
    )

scoped_files

scoped_files(ctx: PhaseContext, name: str, package: Package | None = None) -> tuple[Path, ...]

The files of package the step name judges in this run, absolute.

package is the run's own package unless named: a package step names none, and a step that narrows by packages names each one livery.workshop.scoped_packages answers. The files the run names, when it names any; else every file the step's claims reach in the package, an untracked new one among them.

Raises:

Type Description
Failed

when neither package nor the run names a package.

Source code in packages/workshop/src/livery/workshop/_steps.py
def scoped_files(
    ctx: PhaseContext, name: str, package: Package | None = None
) -> tuple[Path, ...]:
    """The files of *package* the step *name* judges in this run, absolute.

    *package* is the run's own package unless named: a package step
    names none, and a step that narrows by packages names each one
    [livery.workshop.scoped_packages][] answers. The files the run
    names, when it names any; else every file the step's claims reach
    in the package, an untracked new one among them.

    Raises:
        Failed: when neither *package* nor the run names a package.
    """
    record = step_for(name)
    package = package or ctx.package
    if package is None:
        fail(f"{name} judges one package at a time, and this run names none")
    if ctx.files:
        return tuple(Path(path) for path in claimed_files(record, ctx, package.path))
    return tuple(package.directory / path for path in judged_files(record, package))

scoped_packages

scoped_packages(ctx: PhaseContext, name: str) -> tuple[Package, ...]

The members the package-narrowing step name judges in this run.

The members holding an extension it names, in a scoped run those of the subset, less each one that turned the step off in its contract. Each skip is printed, so a narrowed gate names what it left out. A run over named files keeps the members holding a named file the step claims. The workspace's own tests are not a member.

Source code in packages/workshop/src/livery/workshop/_steps.py
def scoped_packages(ctx: PhaseContext, name: str) -> tuple[Package, ...]:
    """The members the package-narrowing step *name* judges in this run.

    The members holding an extension it names, in a scoped run those
    of the subset, less each one that turned the step off in its
    contract. Each skip is printed, so a narrowed gate names what it
    left out. A run over named files keeps the members holding a named
    file the step claims. The workspace's own tests are not a member.
    """
    record = step_for(name)
    chosen = enabled(name, judged_by(record, members(ctx)))
    if not ctx.files:
        return chosen
    return tuple(p for p in chosen if claimed_files(record, ctx, p.path))

scoped_paths

scoped_paths(ctx: PhaseContext, name: str) -> tuple[str, ...]

The paths the path-narrowing step name judges in this run.

The files the run names, when it names any. Otherwise the whole tree, ., when the run reaches every member the step judges; else the src and tests directories of the reached members holding the runtime's language, the workspace's own tests when the run and the step judge them, and the files the step's claims give it in the other reached members.

Source code in packages/workshop/src/livery/workshop/_steps.py
def scoped_paths(ctx: PhaseContext, name: str) -> tuple[str, ...]:
    """The paths the path-narrowing step *name* judges in this run.

    The files the run names, when it names any. Otherwise the whole
    tree, ``.``, when the run reaches every member the step judges;
    else the ``src`` and ``tests`` directories of the reached members
    holding the runtime's language, the workspace's own tests when the
    run and the step judge them, and the files the step's claims give
    it in the other reached members.
    """
    from livery.workshop._packages import holds_runtime_language, package_paths

    record = step_for(name)
    if ctx.files:
        return claimed_files(record, ctx)
    gated_members = judged_by(record, members(ctx))
    chosen_members = enabled(name, gated_members)
    pythons = tuple(p for p in chosen_members if holds_runtime_language(p))
    natives = tuple(p for p in chosen_members if not holds_runtime_language(p))
    unit = judged_by(record, _workspace_unit(ctx), quiet=True)

    def holding(packages: tuple[Package, ...]) -> tuple[str, ...]:
        # A directory with no file the claims reach has nothing to
        # judge, and a tool such as mypy refuses one it is handed.
        return tuple(
            path
            for path in package_paths(packages)
            if _holds_claimed(record, ctx.root / path)
        )

    if ctx.subset is None:
        if len(chosen_members) == len(gated_members):
            return WHOLE
        chosen = holding(pythons + unit) + _claimed(name, natives)
        return chosen or WHOLE
    judged = tuple(p for p in ctx.subset if p in pythons or p in unit)
    present = tuple(p for p in natives if p in ctx.subset)
    if _every_unit_reached(ctx, record, len(judged) + len(present)):
        return WHOLE
    return holding(judged) + _claimed(name, present)

scoped_suite

scoped_suite(ctx: PhaseContext, name: str) -> Package | None

The workspace's own tests, when the step name judges them.

The unit (livery.workshop.workspace_suite) holds the root's set, so the step judges it while that set holds an extension the step names. Its tests reach any package, so every run of the step runs them then. None when the workspace has no tests directory. None as well when the step does not judge the unit, and then a line says why.

Source code in packages/workshop/src/livery/workshop/_steps.py
def scoped_suite(ctx: PhaseContext, name: str) -> Package | None:
    """The workspace's own tests, when the step *name* judges them.

    The unit ([livery.workshop.workspace_suite][]) holds the root's
    set, so the step judges it while that set holds an extension the
    step names. Its tests reach any package, so every run of the step
    runs them then. None when the workspace has no ``tests``
    directory. None as well when the step does not judge the unit, and
    then a line says why.
    """
    from livery.workshop._packages import workspace_suite

    record = step_for(name)
    unit = workspace_suite(ctx.root)
    if unit is None or judges_unit(record, unit):
        return unit
    wanted = " or ".join(record.extensions)
    which = "it" if len(record.extensions) == 1 else "one"
    print(
        f"  {name}: {unit.path} skips (the root's set holds no {wanted};"
        f" list {which} in [workspace] extensions to run them)"
    )
    return None

selected_files

selected_files(ctx: PhaseContext) -> frozenset[str] | None

The files the running step judges in this run; None for every file it reads.

A workspace step that declares inputs judges, in a run that knows what changed, the changed files among its inputs, and what its widen reference adds; in a run that knows nothing of the changes, it judges every file it reads, and this is None. The context names the running step, so a step asks with the context its run was handed.

Raises:

Type Description
Failed

when ctx names no step: one built by hand, outside a step's run.

Source code in packages/workshop/src/livery/workshop/_steps.py
def selected_files(ctx: PhaseContext) -> frozenset[str] | None:
    """The files the running step judges in this run; None for every file it reads.

    A workspace step that declares ``inputs`` judges, in a run that
    knows what changed, the changed files among its inputs, and what
    its ``widen`` reference adds; in a run that knows nothing of the
    changes, it judges every file it reads, and this is None. The
    context names the running step, so a step asks with the context
    its run was handed.

    Raises:
        Failed: when *ctx* names no step: one built by hand, outside
            a step's run.
    """
    if not ctx.step:
        fail(
            "selected_files() answers for the running step, and this"
            " PhaseContext names none: call it with the context a step's"
            " run is handed, which sets PhaseContext.step"
        )
    return _selected_files(step_for(ctx.step), ctx)

step_enabled

step_enabled(root: Path, name: str) -> bool

Whether the step name is on in the workspace at root.

A step its extension declares on is always on. A step it declares enabled = false is on while the root contract turns it on, with enabled = true in the step's [phases.<phase>.<step>] table, and registers only then. A package turns a step off for itself with the step's enabled option, which livery.workshop.step_option reads.

Raises:

Type Description
Failed

when no installed extension declares the step, naming it.

Source code in packages/workshop/src/livery/workshop/_steps.py
def step_enabled(root: Path, name: str) -> bool:
    """Whether the step *name* is on in the workspace at *root*.

    A step its extension declares on is always on. A step it declares
    ``enabled = false`` is on while the root contract turns it on, with
    ``enabled = true`` in the step's ``[phases.<phase>.<step>]`` table,
    and registers only then. A package turns a step off for itself
    with the step's ``enabled`` option, which
    [livery.workshop.step_option][] reads.

    Raises:
        Failed: when no installed extension declares the step, naming it.
    """
    if declared_step(name).enabled:
        return True
    from livery.workshop._extensions import enabled_steps

    return name in enabled_steps(root)

step_extensions

step_extensions(name: str) -> tuple[str, ...]

The extensions the step name names in its extensions list.

The step judges a package whose set holds one of them (livery.workshop.extension_set), and every package when it names none. The step is read as livery.workshop.step_option reads it: registered, else installed.

Raises:

Type Description
Failed

when no installed extension declares the step, naming it.

Source code in packages/workshop/src/livery/workshop/_steps.py
def step_extensions(name: str) -> tuple[str, ...]:
    """The extensions the step *name* names in its ``extensions`` list.

    The step judges a package whose set holds one of them
    ([livery.workshop.extension_set][]), and every package when it
    names none. The step is read as [livery.workshop.step_option][]
    reads it: registered, else installed.

    Raises:
        Failed: when no installed extension declares the step, naming it.
    """
    return declared_step(name).extensions

step_option

step_option(name: str, package: Package, option: str) -> object

What package sets for the step name's option, or the option's default.

The deepest of the package's tables that sets it wins. A step the mount registered answers from its registration. A step it did not register, as in a process that mounted nothing, answers from the installed extension that declares it.

Raises:

Type Description
Failed

when no installed extension declares the step, naming it; when the step declares no option, naming its options; or when the package sets a value of the wrong type, naming the table.

Source code in packages/workshop/src/livery/workshop/_steps.py
def step_option(name: str, package: Package, option: str) -> object:
    """What *package* sets for the step *name*'s *option*, or the option's default.

    The deepest of the package's tables that sets it wins. A step the
    mount registered answers from its registration. A step it did not
    register, as in a process that mounted nothing, answers from the
    installed extension that declares it.

    Raises:
        Failed: when no installed extension declares the step, naming
            it; when the step declares no *option*, naming its options;
            or when the package sets a value of the wrong type, naming
            the table.
    """
    return option_value(declared_step(name), package, option)

tested

tested(units: tuple[Package, ...]) -> tuple[Package, ...]

Keep the units whose suites a registered step of the test phase runs.

A step runs a unit's suite while the unit's set holds an extension the step names, and every unit's when it names none: a member holds its own set, and the workspace's own tests (livery.workshop.WORKSPACE_TESTS) hold the root's set. A step of package scope runs over one member at a time and never over the workspace's own tests.

Returns:

Type Description
tuple[Package, ...]

The units of units some test step runs, in units order.

Source code in packages/workshop/src/livery/workshop/_steps.py
def tested(units: tuple[Package, ...]) -> tuple[Package, ...]:
    """Keep the *units* whose suites a registered step of the test phase runs.

    A step runs a unit's suite while the unit's set holds an extension
    the step names, and every unit's when it names none: a member holds
    its own set, and the workspace's own tests
    ([livery.workshop.WORKSPACE_TESTS][]) hold the root's set. A step
    of package scope runs over one member at a time and never over the
    workspace's own tests.

    Returns:
        The units of *units* some test step runs, in *units* order.
    """
    from livery.workshop._packages import WORKSPACE_TESTS

    tests = [record for record in _STEPS.values() if record.phase == "test"]
    return tuple(
        unit
        for unit in units
        if any(
            judges_unit(record, unit)
            and not (unit.path == WORKSPACE_TESTS and record.scope == PACKAGE)
            for record in tests
        )
    )

forge_token

forge_token(kind: str, url: str) -> tuple[str, str]

The everyday token and the variable that supplied it.

Host-qualified first, then bare FORGE_TOKEN; both empty means the backend's own documented resolution decides (GitHub asks gh auth token; a backend may read its own dialect's variables).

Source code in packages/workshop/src/livery/workshop/_tokens.py
def forge_token(kind: str, url: str) -> tuple[str, str]:
    """The everyday token and the variable that supplied it.

    Host-qualified first, then bare ``FORGE_TOKEN``; both empty means
    the backend's own documented resolution decides (GitHub asks
    ``gh auth token``; a backend may read its own dialect's
    variables).
    """
    return _lookup("FORGE_TOKEN", host_qualifier(kind, url))

store_home

store_home() -> Home

The tool store's home on this machine, where every checkout's tools are.

The toolroom directory in the runner's data directory, one per machine and shared by every checkout on it, as a livery.toolroom.store.Home.

Source code in packages/workshop/src/livery/workshop/_tools.py
def store_home() -> Home:
    """The tool store's home on this machine, where every checkout's tools are.

    The ``toolroom`` directory in the runner's data directory, one per
    machine and shared by every checkout on it, as a
    [livery.toolroom.store.Home][].
    """
    from livery.footman import data_dir
    from livery.toolroom.store import Home

    return Home.under(data_dir())

tool_receipts

tool_receipts(root: Path) -> dict[str, ToolReceipt]

What the checkout at root installed of each tool, by the tool's name.

The receipts the last sync wrote, each a livery.workshop.ToolReceipt: a receipt names the version the lock pins and where the tool is on this machine. Empty for a checkout no sync has supplied.

Raises:

Type Description
ValueError

for a file under the receipts directory that is not a receipt, naming it.

Source code in packages/workshop/src/livery/workshop/_tools.py
def tool_receipts(root: Path) -> dict[str, ToolReceipt]:
    """What the checkout at *root* installed of each tool, by the tool's name.

    The receipts the last sync wrote, each a
    [livery.workshop.ToolReceipt][]: a receipt names the version the
    lock pins and where the tool is on this machine. Empty for a
    checkout no sync has supplied.

    Raises:
        ValueError: for a file under the receipts directory that is not
            a receipt, naming it.
    """
    directory = receipts_dir(root)
    if not directory.is_dir():
        return {}
    found = {}
    for path in sorted(directory.glob("*.json")):
        receipt = ToolReceipt.load(path)
        found[receipt.tool] = receipt
    return found

undeployed

undeployed(name: str) -> NoReturn

Refuse the task: name is a tool of the store and is not on PATH.

Call it where a step spawns a tool of the store and the spawn raises OSError, or where shutil.which finds nothing for a tool the step spawns by its path. A toolroom handle spawns its tool by name from PATH, and the store's tools are on PATH only after the machine has deployed them and the shell has entered the environment. A traceback from the spawn names nothing a person can act on. This refusal names the tool and the next action: run fm sync, then the env.emit line it prints, then run the task again.

It never returns.

Parameters:

Name Type Description Default
name str

The tool's name, as its handle spawns it.

required

Raises:

Type Description
Failed

always, naming name and the sync that deploys it.

Source code in packages/workshop/src/livery/workshop/_tools.py
def undeployed(name: str) -> NoReturn:
    """Refuse the task: *name* is a tool of the store and is not on ``PATH``.

    Call it where a step spawns a tool of the store and the spawn
    raises ``OSError``, or where ``shutil.which`` finds nothing for a
    tool the step spawns by its path. A toolroom handle spawns its tool
    by name from ``PATH``, and the store's tools are on ``PATH`` only
    after the machine has deployed them and the shell has entered the
    environment. A traceback from the spawn names nothing a person can
    act on. This refusal names the tool and the next action: run
    ``fm sync``, then the ``env.emit`` line it prints, then run the task
    again.

    It never returns.

    Args:
        name: The tool's name, as its handle spawns it.

    Raises:
        Failed: always, naming *name* and the sync that deploys it.
    """
    fail(
        f"{name} is not on PATH: it is a tool of the store, so enter the"
        f" environment (`{prog()} sync`, then the printed"
        " env.emit line) and re-run"
    )

leg_scope

leg_scope(root: Path) -> LegScope

Read what the gate ran on this leg from the marker it left at root.

The gate leaves the marker on a CI run's check leg, so the leg's entries after the gate read it there. A gate outside CI leaves none.

Returns:

Type Description
LegScope

The leg's scope; unknown when there is no marker, or the

LegScope

marker is not a JSON object.

Source code in packages/workshop/src/livery/workshop/_verified.py
def leg_scope(root: Path) -> LegScope:
    """Read what the gate ran on this leg from the marker it left at *root*.

    The gate leaves the marker on a CI run's check leg, so the leg's
    entries after the gate read it there. A gate outside CI leaves
    none.

    Returns:
        The leg's scope; ``unknown`` when there is no marker, or the
        marker is not a JSON object.
    """
    unknown = LegScope("unknown")
    path = root / MARKER
    if not path.is_file():
        return unknown
    try:
        loaded = json.loads(path.read_text("utf-8"))
    except (OSError, ValueError):
        return unknown
    if not isinstance(loaded, dict):
        return unknown
    return LegScope(
        scope=str(loaded.get("scope", "unknown")),
        packages=tuple(str(p) for p in loaded.get("packages", []) or []),
        leg=str(loaded.get("leg", "") or ""),
        base_tree=str(loaded.get("base_tree", "") or ""),
    )

verified_branch

verified_branch(root: Path) -> VerifiedBranch

Read which branch's run proved the tree checked out at root.

Main's run after a squash merge reads it to find the branch whose records the tree carries. A row the store cannot read, and a tree git cannot name, decide nothing: the branch is empty and the reason says why, so the caller reads main's records alone.

Source code in packages/workshop/src/livery/workshop/_verified.py
def verified_branch(root: Path) -> VerifiedBranch:
    """Read which branch's run proved the tree checked out at *root*.

    Main's run after a squash merge reads it to find the branch whose
    records the tree carries. A row the store cannot read, and a tree
    git cannot name, decide nothing: the branch is empty and the
    reason says why, so the caller reads main's records alone.
    """
    try:
        tree = tree_id(root)
    except git.GitError as error:
        return VerifiedBranch("", f"the tree has no id ({error})")
    row, why = record(root, tree)
    if why:
        return VerifiedBranch("", why)
    return VerifiedBranch(row.branch if row is not None else "")

__getattr__

__getattr__(name: str) -> object

Serve a public name from its module, each time it is read.

The value is never kept here. A kept value would be whatever the module held at the first read, so a test that patched the module's name before that read would leave its fake in this module for the rest of the process.

Source code in packages/workshop/src/livery/workshop/__init__.py
def __getattr__(name: str) -> object:
    """Serve a public name from its module, each time it is read.

    The value is never kept here. A kept value would be whatever the
    module held at the first read, so a test that patched the module's
    name before that read would leave its fake in this module for the
    rest of the process.
    """
    import importlib

    if name in _PACKAGES:
        value: object = importlib.import_module(f"livery.workshop.{name}")
    else:
        module = _EXPORTS.get(name)
        if module is None:
            raise AttributeError(f"module 'livery.workshop' has no attribute {name!r}")
        value = getattr(importlib.import_module(module), name)
    return value