Skip to content

livery.toolroom.tools

livery.toolroom.tools

Typed handles for command-line tools — the tool room.

toolroom deliberately does not transcribe each tool's flags into Python parameters. Transcription drifts: the wrapper pins the flag-set its author copied, the tool moves on, and one day show_source=True emits a flag the installed binary rejects. Instead, keyword arguments translate mechanically — the installed tool's own CLI stays the single source of truth, at whatever version it is:

  • fix=True → --fix (False/None → omitted entirely)
  • strict=off → --no-strict (disable a default-on flag; off is the toolroom.off sentinel — no_strict=True is the same thing by name)
  • output_format="github" → --output-format github
  • select=["E", "F"] → --select E --select F (an empty list/tuple is omitted entirely, so a parameter's default passes straight through)
  • x=1 (single letter) → -x 1
  • a trailing underscore escapes Python keywords: import_="x" → --import x

Attribute access chains subcommands (toolroom.docker.compose.up(detach=True) → docker compose up --detach), positional strings pass through verbatim, and any executable works without being declared here: toolroom.terraform("plan") just runs terraform plan.

toolroom stands alone: with nothing else installed, a call spawns the tool with plain subprocess and answers in Result; a failure raises ToolError unless nofail. When footman is present in the process, the same call routes through footman's run() instead and inherits everything a task run means — capture, replay-on-failure, dry-run, recording(), --json receipts — without either package depending on the other. _host is the seam.

tool.installed_version() returns the installed binary's version as an int tuple (cached per process, resolved outside any host so dry-run and recording can't lie to it) — for the rare case where code must branch on the tool's actual CLI generation.

Modules:

Name Description
testing

Canned answers for bridge calls — toolroom's own test double.

Classes:

Name Description
Tool

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

ArgvTool

What .argv hands back: the same handle, whose call builds.

Functions:

Name Description
read_version

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

version_tuple

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

console_script

The [console_scripts] entry point named name, unloaded, or None.

negations

Each tool's keywords whose off spelling is not --no-<flag>, by tool.

wrappers

Each tool's verbs that wrap another command, by tool.

colour_controls

Each curated tool's probed colour control, by tool: how footman forces it.

__getattr__

Attributes:

Name Type Description
__version__ str
off _Off
Flag TypeAlias

A boolean flag: True → --flag, off → the tool's own negation,

Value TypeAlias

An option that takes a value. Scalars are str()-ed — a Path passes

ValuedFlag TypeAlias

An option whose value is optional — usable bare (gpg_sign=True, sign

ruff
ruff_format
basedpyright
uv
git
docker
bun
mkdocs
zensical
coverage
cspell
prek
markdownlint
claude
gh
ssh
ssh_keygen
ssh_keyscan
eclint
djlint
mypy
ty
twine
git_changelog
git_cliff
build
cmake
ninja
pytest
python
bash
zsh
fish
pwsh
nu
cmd

__version__ module-attribute

__version__: str = '0.12.0'

off module-attribute

off: _Off = _Off()

Flag module-attribute

Flag: TypeAlias = bool | _Off | None

A boolean flag: True → --flag, off → the tool's own negation, False/None → omitted (which is what lets a task parameter's default flow straight through).

Value module-attribute

Value: TypeAlias = str | int | float | _os.PathLike[str] | Sequence[str | int | float | _os.PathLike[str]] | _Off | None

An option that takes a value. Scalars are str()-ed — a Path passes straight through — and a sequence repeats the flag once per item.

ValuedFlag module-attribute

ValuedFlag: TypeAlias = bool | Value

An option whose value is optional — usable bare (gpg_sign=True, sign with the default key) or with a value (gpg_sign="KEY"). Both spell a valid command; the tool prints its placeholder attached to the flag, --gpg-sign[=<key-id>], which is how the extractor tells the two apart.

ruff module-attribute

ruff = Tool('ruff')

ruff_format module-attribute

ruff_format = Tool('ruff', 'format')

basedpyright module-attribute

basedpyright = Tool('basedpyright')

uv module-attribute

uv = Tool('uv')

git module-attribute

git = Tool('git')

docker module-attribute

docker = Tool('docker')

bun module-attribute

bun = Tool('bun')

mkdocs module-attribute

mkdocs = Tool('mkdocs', in_process=True)

zensical module-attribute

zensical = Tool('zensical', in_process=True)

coverage module-attribute

coverage = Tool('coverage', in_process=True)

cspell module-attribute

cspell = Tool('cspell')

prek module-attribute

prek = Tool('prek')

markdownlint module-attribute

markdownlint = Tool('markdownlint-cli2')

claude module-attribute

claude = Tool('claude')

gh module-attribute

gh = Tool('gh')

ssh module-attribute

ssh = Tool('ssh', version_argv=('-V',))

ssh_keygen module-attribute

ssh_keygen = Tool('ssh-keygen')

ssh_keyscan module-attribute

ssh_keyscan = Tool('ssh-keyscan')

eclint module-attribute

eclint = Tool('eclint', single_dash=True)

djlint module-attribute

djlint = Tool('djlint')

mypy module-attribute

mypy = Tool('mypy')

ty module-attribute

ty = Tool('ty')

twine module-attribute

twine = Tool('twine')

git_changelog module-attribute

git_changelog = Tool('git-changelog')

git_cliff module-attribute

git_cliff = Tool('git-cliff')

build module-attribute

build = Tool('pyproject-build')

cmake module-attribute

cmake = Tool('cmake')

ninja module-attribute

ninja = Tool('ninja')

pytest module-attribute

pytest = Tool('pytest', in_process=True, entry='pytest:main')

python module-attribute

python = Tool('python', path=_sys.executable)

bash module-attribute

bash = Tool('bash', '-c')

zsh module-attribute

zsh = Tool('zsh', '-c')

fish module-attribute

fish = Tool('fish', '-c')

pwsh module-attribute

pwsh = Tool('pwsh', '-c')

nu module-attribute

nu = Tool('nu', '-c')

cmd module-attribute

cmd = Tool('cmd', '/c', version_argv=('/c', 'ver'))

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]

ArgvTool

ArgvTool(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)

Bases: Tool

What .argv hands back: the same handle, whose call builds.

A Tool in every other respect — verbs chain, .opts()/.flags() still apply, and _sub carries the class down the chain so a verb reached through .argv keeps building rather than quietly reverting to a running handle. It is a real class rather than a flag on Tool so the typing stub can say what a built call returns without pretending a Tool sometimes returns one thing and sometimes another.

Methods:

Name Description
__call__

Attributes:

Name Type Description
__slots__
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)

__slots__ class-attribute instance-attribute

__slots__ = ()

__call__

__call__(*args: Any, **kwargs: Any) -> Result
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def __call__(self, *args: Any, **kwargs: Any) -> Result:
    # Builds and answers before anything with a side effect happens —
    # notably before a pending `input=` is consumed, since building a
    # command line feeds no child. The cast keeps the inherited
    # signature: the stub is where the return type tells the truth.
    return _cast("Result", Argv(self._tokens(args, kwargs)))

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 ""

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)

console_script

console_script(name: str) -> Any | None

The [console_scripts] entry point named name, unloaded, or None.

An installed distribution that declares a console script of that name answers; its tool runs in footman's own process from that entry point. The entry point is not loaded, so asking imports none of the tool's code.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def console_script(name: str) -> Any | None:
    """The `[console_scripts]` entry point named *name*, unloaded, or None.

    An installed distribution that declares a console script of that name
    answers; its tool runs in footman's own process from that entry point.
    The entry point is not loaded, so asking imports none of the tool's
    code.
    """
    return _console_entrypoint(name)

negations

negations() -> dict[str, dict[str, str]]

Each tool's keywords whose off spelling is not --no-<flag>, by tool.

fix=False on such a keyword spells the tool's own off flag, mkdocs's clean=False as --dirty; the stub generator reads the same table.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def negations() -> dict[str, dict[str, str]]:
    """Each tool's keywords whose off spelling is not `--no-<flag>`, by tool.

    `fix=False` on such a keyword spells the tool's own off flag, `mkdocs`'s
    `clean=False` as `--dirty`; the stub generator reads the same table.
    """
    return {tool: dict(table) for tool, table in _NEGATIONS.items()}

wrappers

wrappers() -> dict[str, frozenset[str]]

Each tool's verbs that wrap another command, by tool.

A wrapper takes its own options before the command it runs, so a call to one spells its flags first: uv run, docker exec, python itself.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def wrappers() -> dict[str, frozenset[str]]:
    """Each tool's verbs that wrap another command, by tool.

    A wrapper takes its own options before the command it runs, so a call
    to one spells its flags first: `uv run`, `docker exec`, `python` itself.
    """
    return dict(_WRAPPERS)

colour_controls

colour_controls() -> dict[str, tuple[str, str, str, tuple[str, ...], tuple[str, ...], bool]]

Each curated tool's probed colour control, by tool: how footman forces it.

A row is (argv0, on, off, flag_on, flag_off, pre_verb): the tool obeys env (FORCE_COLOR and NO_COLOR), needs its own flag, or can force neither way (none); unprobed had no trigger. fm toolroom.color writes the table, toolroom forces colour from it, and the docs show it.

Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def colour_controls() -> dict[
    str, tuple[str, str, str, tuple[str, ...], tuple[str, ...], bool]
]:
    """Each curated tool's probed colour control, by tool: how footman forces it.

    A row is `(argv0, on, off, flag_on, flag_off, pre_verb)`: the tool obeys
    `env` (FORCE_COLOR and NO_COLOR), needs its own `flag`, or can force
    neither way (`none`); `unprobed` had no trigger. `fm toolroom.color`
    writes the table, toolroom forces colour from it, and the docs show it.
    """
    from livery.toolroom.tools import _colordata

    return dict(_colordata.COLOUR)

__getattr__

__getattr__(name: str) -> Tool[Result]
Source code in packages/toolroom/src/livery/toolroom/tools/__init__.py
def __getattr__(name: str) -> Tool:
    # Any executable is a tool: `tools.terraform("plan")` needs no declaration.
    if name == "testing":
        # The one attribute that is a module, not a tool. `from livery.toolroom.tools
        # import testing` consults this hook *before* the import system
        # falls back to the submodule, so without the redirect it would
        # mint a Tool("testing") and quietly shadow the test helpers.
        import importlib

        return _cast("Tool", importlib.import_module("livery.toolroom.tools.testing"))
    if name.startswith("_"):
        raise AttributeError(name)
    return Tool(name.replace("_", "-"))