Skip to content

API reference

The whole public surface. Anything underscore-prefixed is implementation — it moves without notice.

The handles

livery.toolroom.tools.Tool

Tool(name: str, *base: str, in_process: bool = False, path: str = '', entry: str = '', single_dash: bool = False, version_argv: tuple[str, ...] = ('--version',), policy: dict[str, Any] | None = None)

One command-line tool; see the module docstring for the grammar.

in_process (footman run-control set via .opts(), like nofail) runs a Python tool inside footman's process instead of spawning: the tool's own [console_scripts] entry point is resolved and invoked — the same no-transcription contract, minus the interpreter spawn. Beyond speed this matters for correctness: on macOS, SIP strips DYLD_* from child processes, so a tool that needs Homebrew's native libraries (mkdocs with cairo, say) can only see them in-process, where an env var set before the import sticks. Tools constructed with in_process=True default to it and fall back to a subprocess when no entry point is installed; .opts(in_process=True) is a demand and errors if the entry can't be found. Parallelism survives: entries that accept an argument list (click commands, main(argv=None) — detected from the signature) are called directly and capture through the per-task stdout router; even a legacy zero-arg main() parallelises — the argv router serves each call its own view of sys.argv.

The in-process lane is a host feature — those routers are footman's. Standalone, a tool constructed with in_process=True simply spawns (same command, same semantics), and .opts(in_process=True) — a demand — is a taught refusal.

Methods:

Name Description
__getattr__
opts

Set footman run-control policy for the call — the same .opts() a task

at

Rebind this handle to an executable — the identity channel,

flags

Bind a tool's own global options before the next subcommand.

__call__
installed_version

The version of the binary this tool runs, as a comparable int tuple.

Attributes:

Name Type Description
__class_getitem__
argv Tool[Argv]

Build this call's command line instead of running it.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def __init__(
    self,
    name: str,
    *base: str,
    in_process: bool = False,
    path: str = "",
    entry: str = "",
    single_dash: bool = False,
    version_argv: tuple[str, ...] = ("--version",),
    policy: dict[str, Any] | None = None,
) -> None:
    self._argv0 = name  # the name shown, and the console script looked up
    self._base = list(base)
    self._prefer_in_process = in_process
    # Run-control policy set via `.opts()` (nofail/in_process/capture/title),
    # resolved at call time. Rides the chain, so `git.opts(nofail=True).push()`
    # works. Kept apart from the tool's flags: policy vs work.
    self._opts = dict(policy or {})
    self._rebound = False
    # The executable actually run, when it isn't the name: `tools.python`
    # runs `sys.executable`, not whatever `python` is on PATH.
    self._path = path or name
    # An in-process callable to prefer over the console script, spelled
    # `module:attr`. pytest's console entry is the private zero-arg
    # `_console_main`, whose broken-pipe branch dup2s /dev/null over the
    # process's real stdout — footman's, and every sibling task's.
    # `pytest.main` is the public argument-accepting API and does none of
    # that, so it is recorded here.
    self._entry = entry
    # A Go-style tool whose `flag` package wants one dash on long flags
    # (`eclint -fix`, not `--fix`). Tool-wide: Go's flag package is uniform,
    # so this rides every flag the tool emits, chained subcommands included.
    self._single_dash = single_dash
    # How this tool is asked its version. Nearly everything answers
    # `--version`; Windows `cmd` has no such flag and spells it `cmd /c ver`.
    self._version_argv = tuple(version_argv)

__class_getitem__ class-attribute instance-attribute

__class_getitem__ = classmethod(_types.GenericAlias)

argv property

argv: Tool[Argv]

Build this call's command line instead of running it.

Insert .argv right before the parentheses — the call is otherwise spelled exactly as it would be to run it, same verb, same flags, same completion — and it hands back an Argv of raw tokens rather than executing:

mkdocs.gh_deploy.argv(force=True)
#  -> Argv(['mkdocs', 'gh-deploy', '--force'])

The tokens serialise at the point they cross into a shell — cmd.posix() / cmd.windows() — or splat on as tokens (*cmd):

inner = docker.compose.up.argv(detach=True)
ssh("app@host", inner.posix())

Like .opts(), it may sit anywhere earlier in the chain (docker.argv.compose.up(…) builds too); before the parentheses is where it reads best and how the docs spell it. The line it builds is colour-free: the forced-colour switch a few tools need is injected when spawning, so what runs may carry one more flag than this returns.

__getattr__

__getattr__(verb: str) -> Tool[_R]
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def __getattr__(self, verb: str) -> Tool:
    if verb.startswith("_"):
        raise AttributeError(verb)
    return self._sub(verb.replace("_", "-"))

opts

opts(**overrides: Any) -> Self

Set footman run-control policy for the call — the same .opts() a task has, mirroring its policy-vs-work split. A closed vocabulary (nofail, in_process, capture, title, step) that rides beside the call, never becoming a tool flag:

git.opts(nofail=True).push()          # tolerate a non-zero exit
pytest.opts(capture=False)("-s")      # stream this run live
git.opts(recorded=False).rev_parse("HEAD")  # a value read, not an event

recorded=False is the one that changes what the run sees rather than how the tool is invoked: the call runs in the task's directory and environment as always, but reports nothing — no receipt, no row in --json, no recording() entry — and hands back its Result. Reach for it when the call is how the task knows something rather than something the task did.

Because it is a fixed set, capture here is unambiguously footman's — a tool's own --capture (pytest's) still goes in the call. The overridden options ride the chain and win at call time. For a tool's own global options that must precede a verb, use .flags().

color="always"|"never" decides this call's colour outright, and "auto" (the default) takes the ambient answer — the run's inside a footman run, the user's environment outside one. An explicit choice beats NO_COLOR, which is what makes a colour assertion hold on CI that exports it:

git.opts(color="always").diff()       # colour, whatever the ambient

The decision travels on the call rather than through the environment because os.environ is one per process and calls are not — two threads wanting different answers can both have one this way. It drives whichever half of the forcing each tool needs: the variables for those that read them, their own switch for those that don't. For a tool's own colour flag, spell it in the call (ruff.check(color="always")) and toolroom keeps out of the way.

env= is the child's environment exactly as run(env=…) means it — what you pass is what the child gets — and like the rest of the set it rides the chain and replays. input= feeds the child's standard input, and unlike the rest it is consumed: stdin is consumable, so the payload is delivered exactly once however the handle is chained or shared, and a second call is a taught refusal rather than a silently-unfed child hanging on a stdin that never comes. Re-opt with a fresh payload per call:

uv.pip.install.opts(input=requirement)("-r", "-")
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def opts(self, **overrides: Any) -> Tool:
    """Set footman run-control policy for the call — the same `.opts()` a task
    has, mirroring its policy-vs-work split. A closed vocabulary
    (`nofail`, `in_process`, `capture`, `title`, `step`) that rides *beside*
    the call, never becoming a tool flag:

        git.opts(nofail=True).push()          # tolerate a non-zero exit
        pytest.opts(capture=False)("-s")      # stream this run live
        git.opts(recorded=False).rev_parse("HEAD")  # a value read, not an event

    `recorded=False` is the one that changes what the *run* sees rather than
    how the tool is invoked: the call runs in the task's directory and
    environment as always, but reports nothing — no receipt, no row in
    `--json`, no `recording()` entry — and hands back its `Result`. Reach
    for it when the call is how the task *knows* something rather than
    something the task *did*.

    Because it is a fixed set, `capture` here is unambiguously footman's — a
    tool's own `--capture` (pytest's) still goes in the call. The overridden
    options ride the chain and win at call time. For a tool's *own* global
    options that must precede a verb, use `.flags()`.

    `color="always"|"never"` decides this call's colour outright, and
    `"auto"` (the default) takes the ambient answer — the run's inside a
    footman run, the user's environment outside one. An explicit choice
    beats `NO_COLOR`, which is what makes a colour assertion hold on CI
    that exports it:

        git.opts(color="always").diff()       # colour, whatever the ambient

    The decision travels on the call rather than through the environment
    because `os.environ` is one per process and calls are not — two
    threads wanting different answers can both have one this way. It
    drives whichever half of the forcing each tool needs: the variables
    for those that read them, their own switch for those that don't. For
    a tool's own colour flag, spell it in the call
    (`ruff.check(color="always")`) and toolroom keeps out of the way.

    `env=` is the child's environment exactly as `run(env=…)` means it —
    what you pass is what the child gets — and like the rest of the set it
    rides the chain and replays. `input=` feeds the child's standard input,
    and unlike the rest it is **consumed**: stdin is consumable, so the
    payload is delivered exactly once however the handle is chained or
    shared, and a second call is a taught refusal rather than a
    silently-unfed child hanging on a stdin that never comes. Re-opt with
    a fresh payload per call:

        uv.pip.install.opts(input=requirement)("-r", "-")
    """
    t = self._sub()
    t._opts = {**self._opts, **_opts_overrides(overrides)}
    return t

at

at(path: str | Path) -> Self

Rebind this handle to an executable — the identity channel, beside .opts() (policy) and .flags() (the tool's own argv).

Everything else rides along: verbs, bound flags, policy — including a pending input= payload, whose cell is shared, not copied. What changes is what runs: tools.python.at(venv_python) is that venv's interpreter carrying python's whole typed surface, and the shown command line keeps the tool's own name.

The in-process lane runs this interpreter, which is exactly what an .at() handle says not to do — so the handle always spawns, and an explicit in_process=True on one is a taught refusal.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def at(self, path: str | _Path) -> Tool:
    """Rebind this handle to an executable — the *identity* channel,
    beside `.opts()` (policy) and `.flags()` (the tool's own argv).

    Everything else rides along: verbs, bound flags, policy — including
    a pending `input=` payload, whose cell is shared, not copied. What
    changes is *what runs*: `tools.python.at(venv_python)` is that
    venv's interpreter carrying python's whole typed surface, and the
    shown command line keeps the tool's own name.

    The in-process lane runs *this* interpreter, which is exactly what
    an `.at()` handle says not to do — so the handle always spawns, and
    an explicit `in_process=True` on one is a taught refusal.
    """
    t = type(self)(
        self._argv0,
        *self._base,
        in_process=False,
        path=str(path),
        entry=self._entry,
        single_dash=self._single_dash,
        version_argv=self._version_argv,
        policy=self._opts,
    )
    t._rebound = True
    return t

flags

flags(**kwargs: Any) -> Self

Bind a tool's own global options before the next subcommand.

Some flags belong to the tool, not the verb, and must precede it: docker --host tcp://x ps works, docker ps --host tcp://x does not. flags places them at the current point in the chain, so they land ahead of whatever verb follows and ahead of its arguments:

tools.docker.flags(host="tcp://x").ps(all=True)
#  -> docker --host=tcp://x ps --all

The flags are translated by the same rules as any call, and the returned tool keeps chaining, so .flags(...) composes mid-stream. (footman run-control — nofail, capture, … — goes in .opts().)

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def flags(self, **kwargs: Any) -> Tool:
    """Bind a tool's own global options *before* the next subcommand.

    Some flags belong to the tool, not the verb, and must precede it:
    `docker --host tcp://x ps` works, `docker ps --host tcp://x` does
    not. `flags` places them at the current point in the chain, so they
    land ahead of whatever verb follows and ahead of its arguments:

        tools.docker.flags(host="tcp://x").ps(all=True)
        #  -> docker --host=tcp://x ps --all

    The flags are translated by the same rules as any call, and the
    returned tool keeps chaining, so `.flags(...)` composes mid-stream.
    (footman run-control — `nofail`, `capture`, … — goes in `.opts()`.)
    """
    return self._sub(*_flags(kwargs, self._argv0, single_dash=self._single_dash))

__call__

__call__(*args: Any, **kwargs: Any) -> _R
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def __call__(self, *args: Any, **kwargs: Any) -> Result:
    # Run-control comes from `.opts()` (policy), never the call — so every
    # kwarg here is a tool flag, with no reserved name to collide with a real
    # option (pytest's own `--capture`, say).
    nofail = self._opts.get("nofail", False)
    capture = self._opts.get("capture", True)
    title = self._opts.get("title", None)
    in_process = self._opts.get("in_process", None)
    cwd_opt = self._opts.get("cwd", None)
    rel_opt = self._opts.get("rel", None)
    recorded = self._opts.get("recorded", True)
    timeout = self._opts.get("timeout", None)
    pre_record = self._opts.get("pre_record", None)
    env_opt = self._opts.get("env", None)
    # The mode travels to the executor unresolved — `auto` means "follow
    # whoever owns the ambient", and hosted that is the run. Only the argv
    # half is decided here, because a switch has to be a switch.
    colour_mode = self._opts.get("color", "auto")
    colour_on = _host.colour_wanted(colour_mode)
    # `input=` is consumed *at entry*: one `.opts(input=…)` is one
    # delivery, wherever in the chain the call lands. Entry rather than
    # after execution, so a dry-run or `recording()` rehearsal consumes
    # exactly as the run it predicts would. `.opts(input=…)` re-arms.
    cell = self._opts.get("input", None)
    input_: str | None = None
    if cell is not None:
        taken = cell.take()
        if isinstance(taken, _Consumed):
            raise TypeError(
                f"{self._argv0}: this handle's input= was already fed — "
                f"stdin is consumable, so a payload is delivered exactly "
                f"once. Re-opt with a fresh payload per call: "
                f"{self._argv0}.opts(input=…)(…)"
            )
        input_ = taken
    flags = _flags(kwargs, self._argv0, single_dash=self._single_dash)
    positionals = _positionals(args, self._argv0)
    wrapper = _is_wrapper(self._argv0, self._base)

    def _tail(fl: list[str]) -> list[str]:
        # A wrapper verb (`uv run`, `docker exec`) forwards everything after
        # its own arguments to a child, so this call's flags must precede the
        # positionals — otherwise `--frozen` lands on `pytest`, not `uv`.
        if wrapper:
            return [*self._base, *fl, *positionals]
        return [*self._base, *positionals, *fl]

    # `parts` is the shown/recorded command line and never carries a forced
    # colour switch, so `.command`/`recording()` stay the tool's own call.
    parts = _show_parts(
        self._argv0, self._base, args, kwargs, single_dash=self._single_dash
    )
    # The call as the caller wrote it, pre-render — a False keyword the
    # argv omits, a Path still a Path. The dict is copied at this
    # boundary so a later mutation cannot rewrite the record.
    handed = (args, dict(kwargs))
    # The in-process argv/tail are colour-free: an in-process tool reads the
    # run-wide colour from the environment (set once at the run boundary), so
    # only a *spawned* tool that ignores the environment (git) needs its own
    # switch. Execution runs the real executable (`python` → sys.executable).
    tail = _tail(flags)
    argv = [self._path, *tail]

    def _spawn() -> Result:
        # The forced colour switch, subprocess-only, into the executed argv:
        # a pre-verb global (`git -c color.ui=always`) leads; a verb-scoped
        # flag rides with the others. `.raw`/`--verbose` show what ran.
        colour = _color_tokens(self._argv0, self._base, kwargs, colour_on)
        if not colour.on:
            spawned = argv
        elif colour.pre_verb:
            spawned = [self._path, *colour.on, *tail]
        else:
            spawned = [self._path, *_tail([*flags, *colour.on])]
        return _host.run(
            spawned,
            parts=parts,
            exact=tuple(spawned),
            handed=handed,
            nofail=nofail,
            capture=capture,
            input=input_,
            env=env_opt,
            title=title,
            pre_record=pre_record,
            recorded=recorded,
            timeout=timeout,
            cwd=cwd_opt,
            rel=rel_opt,
            color=colour_mode,
        )

    wanted = self._prefer_in_process if in_process is None else in_process
    if wanted and self._rebound:
        raise ValueError(
            f"{self._argv0}: in_process=True on an .at() handle — the "
            f"in-process lane runs this interpreter, and .at() names a "
            f"different executable. Drop one of them."
        )
    if wanted and timeout is not None:
        # A bound needs a process to bound: an in-process call has no
        # child to signal and no safe way to unwind a thread. Demote to
        # the subprocess twin — the same choice a foreign cwd forces
        # below, and the timeout is the thing the caller actually asked
        # for.
        _host.note(
            f"note: {self._argv0}: ran as subprocess — a timeout needs "
            f"a process to bound\n"
        )
        return _spawn()
    if wanted and not _host.hosted():
        # The in-process lane is a host feature: it needs footman's
        # stdout router and argv router to capture and parallelise.
        # Standalone, a *preference* degrades to the subprocess twin —
        # same command, same semantics — and a *demand* is a taught
        # refusal rather than an uncaptured surprise.
        if in_process is True:
            raise ValueError(
                f"{self._argv0}: in_process=True needs a footman host — "
                f"standalone toolroom always spawns. Drop in_process, "
                f"or run under footman."
            )
        return _spawn()
    if wanted:
        from livery.footman import host

        running = host()
        target = (
            running.target_cwd(cwd_opt, rel_opt) if running is not None else None
        )
        if (
            running is not None
            and target is not None
            and target.resolve() != _Path(running.real_cwd())
        ):
            # In-process can't apply a foreign cwd (footman never chdirs
            # in a parallel task): demote to the subprocess twin — same
            # command, same semantics, still fully parallel; the
            # in-process speedup is the only loss. A serial task's cwd is
            # really applied, so it compares equal and stays in-process.
            _host.note(
                f"note: {self._argv0}: ran as subprocess — in-process "
                f"can't apply cwd in parallel\n"
            )
            return _spawn()
        loader = self._inprocess_loader()  # metadata only — no import
        if loader is None:
            if in_process is True:  # a demand can't be met — fail fast
                raise ValueError(
                    f"{self._argv0}: in_process=True, but no importable "
                    f"in-process entry ({self._entry or self._argv0!r})"
                )
            return _spawn()  # prefer → subproc

        def _invoke() -> Any:
            entry = loader()  # the tool's import — deferred to execution,
            # so a dry-run of this call imports nothing.
            if _accepts_args(entry):
                return entry(tail)  # click / main(argv): lock-free, parallel
            if running is not None and running.active:
                # The argv router: this call gets its own sys.argv view —
                # lock-free, so even a legacy zero-arg main() parallelises.
                with running.argv_override(argv):
                    return entry()
            with _argv_lock:  # bare calls outside a run: classic patch
                saved = _sys.argv
                _sys.argv = argv
                try:
                    return entry()
                finally:
                    _sys.argv = saved

        return _host.run(
            _invoke,
            parts=parts,
            exact=tuple(argv),
            handed=handed,
            nofail=nofail,
            capture=capture,
            # Forwarded so run()'s refusal teaches: an in-process tool
            # has no standard input to feed.
            input=input_,
            env=env_opt,
            title=title,
            pre_record=pre_record,
            recorded=recorded,
            timeout=timeout,
            cwd=cwd_opt,
            rel=rel_opt,
        )
    return _spawn()

installed_version

installed_version() -> tuple[int, ...]

The version of the binary this tool runs, as a comparable int tuple.

Asks the executable itself — <tool> --version, or whatever spelling the tool was declared with (cmd /c ver) — and reads the answer with the same parser the stub extractor uses, so the two can never disagree about a version string's grammar. Runs outside the task context, so --dry-run and recording() can't lie to it, and caches per process.

It answers "what will this task actually invoke", which is not the version a stub header records. A stub says what extraction read, on whatever machine synced it, from whatever binary it resolved — the two differ whenever PATH and the extractor disagree (a Homebrew keg against /usr/bin/git, say). This one is the end-user question; the stub's is maintainer bookkeeping.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def installed_version(self) -> tuple[int, ...]:
    """The version of the binary *this tool runs*, as a comparable int tuple.

    Asks the executable itself — `<tool> --version`, or whatever spelling
    the tool was declared with (`cmd /c ver`) — and reads the answer with
    the same parser the stub extractor uses, so the two can never disagree
    about a version string's grammar. Runs outside the task context, so
    `--dry-run` and `recording()` can't lie to it, and caches per process.

    It answers "what will this task actually invoke", which is *not* the
    version a stub header records. A stub says what extraction read, on
    whatever machine synced it, from whatever binary it resolved — the
    two differ whenever `PATH` and the extractor disagree (a Homebrew keg
    against `/usr/bin/git`, say). This one is the end-user question; the
    stub's is maintainer bookkeeping.
    """
    key = self._path
    if key not in _version_cache:
        argv = [self._path, *self._version_argv]
        out = _host.probe(
            argv,
            shown=(self._argv0, *self._version_argv),
            # A tool's own switches (gh's update check, a telemetry
            # opt-out) live in its record's env, exported by the entered
            # environment, so the read inherits them from the process.
            env=dict(_os.environ),
            timeout=30,
        )
        found = read_version(out.stdout or out.stderr)
        if out.code != 0 or not found:
            raise ValueError(f"could not read a version from `{' '.join(argv)}`")
        _version_cache[key] = version_tuple(found)
    return _version_cache[key]

The vocabulary

livery.toolroom.tools.Argv

Bases: list[str]

A command line built but not run — raw tokens, an ordinary list[str].

Methods:

Name Description
posix
windows

posix

posix() -> str
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
# `_host` is the seam: execution, host detection, and the standalone executor.

windows

windows() -> str
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
from livery.toolroom.tools import _host as _host

livery.toolroom.tools.Result

Bases: int

One standalone call's outcome: the exit code, plus streams and tokens.

Hosted calls answer with footman's richer twin; both satisfy this surface, which is the one the stubs promise.

Methods:

Name Description
__new__
to_argv

Attributes:

Name Type Description
ok bool
code int
stdout str
stderr str
command str

ok property

ok: bool

code property

code: int

stdout property

stdout: str

stderr property

stderr: str

command property

command: str

__new__

__new__(code: int, *, stdout: str = ..., stderr: str = ..., tokens: tuple[str, ...] = ...) -> Self
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
# The one way footman reads a version out of a tool's own words, shared with
# the extractor (`_drivers.version`) so a stub's recorded version and a task's
# `installed_version()` can never disagree about *parsing* — only, deliberately,
# about which binary they asked (see `installed_version`).
#
# A negative lookbehind, not `\b`: a version glued to a `v` prefix (`v0.23.1`)
# has no word boundary before its first digit, so `\b` would skip to the middle
# and read `23.1`. Reject only a preceding digit or dot, so `v0.23.1` -> `0.23.1`

to_argv

to_argv() -> Argv
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def read_version(text: str) -> str:

livery.toolroom.tools.ToolError

ToolError(result: Result)

Bases: RuntimeError

A standalone call exited non-zero without nofail; carries the Result.

Attributes:

Name Type Description
result Result
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
"""

result instance-attribute

result: Result

Flag control

livery.toolroom.tools.off module-attribute

off: _Off = _Off()

Versions

livery.toolroom.tools.read_version

read_version(text: str) -> str

The version string inside a tool's --version output, or "".

The string is preserved exactly, build tail and all (0.6.0-wk.5), for anything that records which build was read. Use version_tuple to compare.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def read_version(text: str) -> str:
    """The version string inside a tool's `--version` output, or `""`.

    The string is preserved exactly, build tail and all (`0.6.0-wk.5`), for
    anything that records *which* build was read. Use `version_tuple` to
    compare.
    """
    match = _VERSION.search(text)
    return match[1] if match else ""

livery.toolroom.tools.version_tuple

version_tuple(version: str) -> tuple[int, ...]

A version string reduced to comparable integers — the CLI generation.

Only the leading numeric run counts, and the first component carrying a build tag ends the read: 0.6.0-wk.5 and 1.13.0.git.kitware.jobserver-1 both compare as their base, (0, 6, 0) and (1, 13, 0).

That is the honest answer to the question this is asked — is the CLI new enough — because a build tail says nothing about which flags exist. Scraping its digits would answer it backwards: 0.6.0-wk.5 is a fork build of 0.6.0, which every version grammar sorts at or before it, while (0, 6, 0, 5) sorts after.

So two builds of one base compare equal, and every caller has to say what it does with that rather than read equality as an answer. Ordering a release chain breaks the tie on publication date, which separates a wk series correctly without this having to know what wk means. The snapshot guard cannot — an incoming reading is dated today whatever it holds — so it declines to move rather than guess.

An unreadable version yields (), which compares lower than everything — "can't tell" must never read as "newer".

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def version_tuple(version: str) -> tuple[int, ...]:
    """A version string reduced to comparable integers — the CLI generation.

    Only the leading numeric run counts, and the first component carrying a
    build tag ends the read: `0.6.0-wk.5` and `1.13.0.git.kitware.jobserver-1`
    both compare as their base, `(0, 6, 0)` and `(1, 13, 0)`.

    That is the honest answer to the question this is asked — *is the CLI new
    enough* — because a build tail says nothing about which flags exist.
    Scraping its digits would answer it backwards: `0.6.0-wk.5` is a fork
    build *of* 0.6.0, which every version grammar sorts at or before it,
    while `(0, 6, 0, 5)` sorts after.

    So two builds of one base compare **equal**, and every caller has to say
    what it does with that rather than read equality as an answer. Ordering a
    release chain breaks the tie on publication date, which separates a `wk`
    series correctly without this having to know what `wk` means. The
    snapshot guard cannot — an incoming reading is dated today whatever it
    holds — so it declines to move rather than guess.

    An unreadable version yields `()`, which compares lower than everything —
    "can't tell" must never read as "newer".
    """
    parts: list[int] = []
    for piece in version.split("."):
        digits = ""
        for char in piece:
            if not char.isdigit():
                break
            digits += char
        if digits:
            parts.append(int(digits))
        if not piece.isdigit():
            break
    return tuple(parts)

Testing

How these fit together is Testing's story; this is the reference.

livery.toolroom.tools.testing.answers

answers(table: Mapping[Any, Answer] | None = None, *, hosted: bool = False) -> Generator[list[Call]]

Answer every bridge call in the block from table, spawning nothing.

Yields the live list of Call records — assert on it after (or during) the block. With hosted=True the block simulates the hosted lane: _host.hosted answers True (so the bridge takes its hosted paths — an in-process tool's callable is recorded, never invoked), successes come back as footman's Result, and failures raise footman's RunFailed — what code written for a footman task returns and catches. The default speaks toolroom's own vocabulary: Result back, ToolError raised.

The per-process installed_version cache is cleared for the block and restored after it, so a canned version can neither be pre-empted by a real read earlier in the process nor leak into later tests. Not thread-safe: the seam is swapped module-wide for the duration.

A canned prefix that matched nothing by a clean block exit warns (UnservedAnswers): an answer canned but never served is almost always a mis-keyed prefix, and without the warning the test passes vacuously. A block that exits on an exception is not warned — it already failed loudly.

Source code in packages/toolroom/src/livery/toolroom/tools/testing.py
@contextlib.contextmanager
def answers(
    table: Mapping[Any, Answer] | None = None,
    *,
    hosted: bool = False,
) -> Generator[list[Call]]:
    """Answer every bridge call in the block from *table*, spawning nothing.

    Yields the live list of `Call` records — assert on it after (or
    during) the block. With `hosted=True` the block simulates the
    hosted lane: `_host.hosted` answers True (so the bridge takes its
    hosted paths — an in-process tool's callable is recorded, never
    invoked), successes come back as footman's `Result`, and failures
    raise footman's `RunFailed` — what code written for a footman task
    returns and catches. The default speaks toolroom's own vocabulary:
    `Result` back, `ToolError` raised.

    The per-process `installed_version` cache is cleared for the block
    and restored after it, so a canned version can neither be pre-empted
    by a real read earlier in the process nor leak into later tests.
    Not thread-safe: the seam is swapped module-wide for the duration.

    A canned prefix that matched nothing by a *clean* block exit warns
    (`UnservedAnswers`): an answer canned but never served is almost
    always a mis-keyed prefix, and without the warning the test passes
    vacuously. A block that exits on an exception is not warned — it
    already failed loudly.
    """
    canned = _normalise(table or {})
    fm_result: Any = None
    fm_failed: Any = None
    if hosted:
        try:
            from livery.footman import Result as fm_result
            from livery.footman import RunFailed as fm_failed
        except ImportError:
            raise ImportError(
                "answers(hosted=True) simulates the hosted lane, which is "
                "footman vocabulary (footman.Result back, RunFailed raised) — "
                "install footman, or drop hosted= to test the standalone lane."
            ) from None
    calls: list[Call] = []
    served: set[tuple[str, ...]] = set()

    def fake_run(
        target: list[str] | Any,
        *,
        parts: tuple[tuple[str, str], ...],
        exact: tuple[str, ...],
        handed: tuple[tuple[Any, ...], dict[str, Any]] | None = None,
        nofail: bool = False,
        capture: bool = True,
        input: str | bytes | None = None,
        env: dict[str, str] | None = None,
        title: str | None = None,
        pre_record: Any = None,
        recorded: bool = True,
        timeout: float | None = None,
        cwd: str | Path | None = None,
        rel: str | Path | None = None,
        color: str = "auto",
    ) -> Any:
        named = (parts[0][1], *exact[1:])
        command = " ".join(token for _role, token in parts)
        call_args, call_kwargs = handed if handed is not None else ((), {})
        calls.append(
            Call(
                argv=Argv(named),
                raw=Argv(exact),
                command=command,
                args=call_args,
                kwargs=call_kwargs,
                env=env,
                opts={
                    "nofail": nofail,
                    "capture": capture,
                    "input": input,
                    "title": title,
                    "pre_record": pre_record,
                    "recorded": recorded,
                    "timeout": timeout,
                    "cwd": cwd,
                    "rel": rel,
                    "color": color,
                },
            )
        )
        matched = _match(canned, named)
        if matched is None:
            code, stdout, stderr = 0, "", ""
        else:
            served.add(matched)
            code, stdout, stderr = _resolve(canned[matched], command)
        if hosted:
            result: Any = fm_result(
                code, command=command, stdout=stdout, stderr=stderr, tokens=exact
            )
            if code != 0 and not nofail:
                raise fm_failed(result)
            return result
        result = Result(code, stdout=stdout, stderr=stderr, tokens=exact)
        if code != 0 and not nofail:
            raise ToolError(result)
        return result

    def fake_probe(
        argv: list[str],
        *,
        shown: tuple[str, ...],
        env: dict[str, str] | None,
        timeout: float | None,
    ) -> Result:
        command = " ".join(shown)
        calls.append(
            Call(
                argv=Argv(shown),
                raw=Argv(argv),
                command=command,
                env=env,
                opts={"timeout": timeout},
                probe=True,
            )
        )
        matched = _match(canned, shown)
        if matched is None:
            # An empty answer would surface as installed_version's own
            # "could not read a version" ValueError — which reads as a bug
            # in the code under test. Name the missing entry instead: a
            # version read is never incidental, code branches on it.
            raise LookupError(
                f"answers(): no canned answer for the version read "
                f"`{command}` — installed_version() under answers() needs "
                f"one, e.g. {{{tuple(shown)!r}: '1.2.3'}}"
            )
        served.add(matched)
        code, stdout, stderr = _resolve(canned[matched], command)
        return Result(code, stdout=stdout, stderr=stderr, tokens=tuple(argv))

    saved_run, saved_probe, saved_hosted = _host.run, _host.probe, _host.hosted
    snapshot = dict(_toolroom._version_cache)
    _toolroom._version_cache.clear()
    # The host seam is swapped by design; the checker reads a def as
    # non-reassignable.
    _host.run = fake_run  # ty: ignore[invalid-assignment]
    _host.probe = fake_probe  # ty: ignore[invalid-assignment]
    if hosted:

        def _always_hosted() -> bool:
            return True

        _host.hosted = _always_hosted  # ty: ignore[invalid-assignment]
    try:
        yield calls
    finally:
        _host.run, _host.probe, _host.hosted = saved_run, saved_probe, saved_hosted
        _toolroom._version_cache.clear()
        _toolroom._version_cache.update(snapshot)
    # Reached only on a clean exit: an exception leaving the block is
    # already a loud failure, and a warning behind it would only mask it.
    unserved = [prefix for prefix in canned if prefix not in served]
    if unserved:
        rendered = "; ".join(" ".join(prefix) for prefix in unserved)
        warnings.warn(
            f"answers(): these canned answers matched no call: {rendered} — "
            f"an unserved entry is almost always a mis-keyed prefix "
            f"(matching is name-led, never a resolved path, and by argv "
            f"prefix), and the test passes vacuously without it",
            UnservedAnswers,
            stacklevel=3,
        )

livery.toolroom.tools.testing.Call

Call(*, argv: Argv, raw: Argv, command: str, args: tuple[Any, ...] = (), kwargs: dict[str, Any] | None = None, env: dict[str, str] | None, opts: dict[str, Any], probe: bool = False)

One intercepted call: what would have run, and what was handed.

argv is the name-led spelling — raw tokens, assert-friendly. raw is what would actually have spawned: resolved interpreter path, forced colour switch and all (the same pairing footman's steps keep as .command/.raw). command is the shown line, values quoted and secrets redacted.

args and kwargs are the call as the caller wrote it, pre-render: positionals verbatim (a Path stays a Path), and the call keywords with False values included — the bridge omits a False flag from the argv, the record must not, because "never handed" and "handed, as False" are different facts and tests assert on both. The rule of thumb: assert on kwargs for what the code decided to pass, on argv for what would have run. .flags() keywords are part of the handle, rendered into the verb path before any call exists, so they show only in argv/raw; run policy stays in opts.

env is the environment the call handed the seam (None inherits); opts carries the rest of the run policy (nofail, capture, input, cwd, timeout, …) exactly as it crossed. probe marks a version read — a probe has no call of its own, so its args/kwargs are () and {} by construction.

Methods:

Name Description
__repr__

Attributes:

Name Type Description
__slots__
argv Argv
raw Argv
command str
args tuple[Any, ...]
kwargs dict[str, Any]
env dict[str, str] | None
opts dict[str, Any]
probe bool
Source code in packages/toolroom/src/livery/toolroom/tools/testing.py
def __init__(
    self,
    *,
    argv: Argv,
    raw: Argv,
    command: str,
    args: tuple[Any, ...] = (),
    kwargs: dict[str, Any] | None = None,
    env: dict[str, str] | None,
    opts: dict[str, Any],
    probe: bool = False,
) -> None:
    self.argv = argv
    self.raw = raw
    self.command = command
    self.args = args
    self.kwargs = {} if kwargs is None else kwargs
    self.env = env
    self.opts = opts
    self.probe = probe

__slots__ class-attribute instance-attribute

__slots__ = ('args', 'argv', 'command', 'env', 'kwargs', 'opts', 'probe', 'raw')

argv instance-attribute

argv: Argv = argv

raw instance-attribute

raw: Argv = raw

command instance-attribute

command: str = command

args instance-attribute

args: tuple[Any, ...] = args

kwargs instance-attribute

kwargs: dict[str, Any] = {} if kwargs is None else kwargs

env instance-attribute

env: dict[str, str] | None = env

opts instance-attribute

opts: dict[str, Any] = opts

probe instance-attribute

probe: bool = probe

__repr__

__repr__() -> str
Source code in packages/toolroom/src/livery/toolroom/tools/testing.py
def __repr__(self) -> str:
    kind = "probe" if self.probe else "call"
    return f"Call({self.command!r}, {kind})"

livery.toolroom.tools.testing.UnservedAnswers

Bases: Warning

A canned answer matched no call by the end of an answers() block.

An unmatched call is often incidental — the recorder default exists for exactly that — but an unmatched table entry is a test bug in the making: an answer was canned to steer the code under test and never served, usually because the key was mis-spelt, path-led where matching is name-led, or split into the wrong tokens, and the test passes vacuously as if the entry did not exist. A warning rather than an error so a deliberately shared table (one fixture serving several tests, each exercising a subset) can filter it; escalate it to a failure with -W error or a filterwarnings mark where the table is per-test. A block that exits on an exception is not warned — it already failed loudly.