Skip to content

API reference

Auto-generated from the source via mkdocstrings. Everything here is importable straight from the livery.footman package (from livery.footman import task, run, App).

Defining tasks

livery.footman.task module-attribute

task: Final[TaskDecorator] = root.task

livery.footman.group module-attribute

group: Final[GroupFactory] = root.group

livery.footman.Group

Group(name: str, help: str = '', hidden: bool | None = None, expose: str | None = None)

A node in the command tree: named tasks and nested sub-groups.

Methods:

Name Description
task

Register a function as a task.

group

Create and register a nested command group, returning it.

pre_tasks

Register the once-per-invocation hook, run before anything else.

pre_bind

Register the before-binding hook: pre_bind(inv, task).

post_tasks

Register the once-per-invocation closing hook: post_tasks(inv).

pre_reexec

Register a block for the moment this process replaces itself.

wrap_task

Register a one-yield wrapper around the body: sugar over the pair.

wrap_bind

Register a two-yield wrapper spanning bind, body and all: sugar

pre_task

Register the before-each-task hook: pre_task(inv, task).

post_task

Register the after-each-task hook: post_task(inv, task, result).

default

Register fn as this group's default action — what a bare

opts

Per-use option overrides for this group's default action, the same

__call__

Run this group's default action — the imperative mirror of a bare

Attributes:

Name Type Description
name
help
hidden
expose
tasks dict[str, Task]
groups dict[str, Group]
contributions dict[str, list[Any]]
mounted_from str | None
default_task Task | None

The default action — what a bare fm <group> runs.

Source code in packages/footman/src/livery/footman/_registry.py
def __init__(
    self,
    name: str,
    help: str = "",
    hidden: bool | None = None,
    expose: str | None = None,
) -> None:
    self.name = name
    self.help = help
    # Tri-state, like a task's: unset inherits the enclosing group's
    # answer, so a hidden subtree needs saying once at its root and a
    # child can still opt back into the listings with `hidden=False`.
    self.hidden = hidden
    # The same tri-state, for the same reason:
    # `group("ci", expose="project_only")` answers for everything under it,
    # and a child can still say otherwise. `None` asks whoever encloses.
    self.expose = expose
    self.tasks: dict[str, Task] = {}
    self.groups: dict[str, Group] = {}
    # Lifecycle contributions, one bucket per hook kind (root registry
    # only), every kind in `CONTRIBUTION_KINDS`.
    # Hook kinds hold callables; the `globals` kind holds
    # `GlobalOption` singletons — one generic carriage, typed loosely.
    self.contributions: dict[str, list[Any]] = {
        kind: [] for kind in CONTRIBUTION_KINDS
    }
    # Provenance: the plugin identity that mounted this group in, or None
    # for a locally-defined one. Collision messages cite it, `--plugins`
    # reports it, and "local silently wins" is decided by it.
    self.mounted_from: str | None = None

name instance-attribute

name = name

help instance-attribute

help = help

hidden instance-attribute

hidden = hidden

expose instance-attribute

expose = expose

tasks instance-attribute

tasks: dict[str, Task] = {}

groups instance-attribute

groups: dict[str, Group] = {}

contributions instance-attribute

contributions: dict[str, list[Any]] = {kind: [] for kind in CONTRIBUTION_KINDS}

mounted_from instance-attribute

mounted_from: str | None = None

default_task property

default_task: Task | None

The default action — what a bare fm <group> runs.

Derived, never stored: the default is the child task named default (@group.default ↔ fm lint.default), so default-ness has one spelling, survives forks and grafts by construction, and there is no pointer to desync.

task

task(fn: Callable[_P, _R_co]) -> TaskFn[_P, _R_co]
task(fn: None = None, *, name: str = '', pre: Sequence[Task] = (), post: Sequence[Task] = (), progress: bool = True, infinite: bool = False, shared: bool | None = None, confirm: str = '', interactive: bool = False, keep_going: bool | None = None, atomic: bool = False, timeout: float | None = None, retries: int = 0, cwd: str | Path = '', rel: str | Path = '', serial: bool = False, exclusive: bool = False, hidden: bool | None = None, expose: str | None = None, lanes: Sequence[Lane] = (), uses: Sequence[GlobalOption] = ()) -> Callable[[Callable[_P, _R_co]], TaskFn[_P, _R_co]]
task(fn: Task | None = None, *, name: str = '', pre: Sequence[Task] = (), post: Sequence[Task] = (), progress: bool = True, infinite: bool = False, shared: bool | None = None, confirm: str = '', interactive: bool = False, keep_going: bool | None = None, atomic: bool = False, timeout: float | None = None, retries: int = 0, cwd: str | Path = '', rel: str | Path = '', serial: bool = False, exclusive: bool = False, hidden: bool | None = None, expose: str | None = None, lanes: Sequence[Lane] = (), uses: Sequence[GlobalOption] = ()) -> Task | Callable[[Task], Task]

Register a function as a task.

Usable bare (@task) or parameterised (@task(name="build")) to override the command name. pre/post declare dependency tasks (by reference) that run before/after this one — the scheduler runs independent prerequisites in parallel:

@task(pre=[format, lint, typecheck, test])
def check(): ...

Availability gating lives in the @requires decorators — stack @requires, @requires_dep, @requires_tool, or @requires_env above @task to list a task as unavailable (with a reason) where it can't run, rather than hide it.

Three different things, worth keeping apart:

  • hidden=True — out of the listings, callable as ever. The task drops out of --list, --tree and group help (--all brings it back), while fm <name> runs it exactly as before, Tab completes it, and the did-you-mean index knows it: a listing is prose about the project, completion is help with a name you are already typing. For the tasks a machine calls and a human never types: a CI entry point, a release step another task drives. It is presentation only — prerequisites still run it, a group's empty-body fan-out still includes it, and --json reports it marked rather than missing, because a machine is who calls it. Unset inherits the enclosing group's answer, so group("internal", hidden=True) hides a whole subtree and a child can still say hidden=False.
  • @requires… — listed with a reason it can't run here.
  • if sys.platform == "darwin": @task ... — plain Python, and the task does not exist: nothing to list, nothing to call, no address at all. Reach for it when the task is meaningless on this machine, not when it is merely uninteresting to type.

progress=False marks a task whose duration has no rhyme or reason (a REPL, a watcher, a network fetch): any run containing it never records timing history and never shows a determinate progress bar — the indeterminate pulse still does.

infinite=True marks a task that runs until stopped — a dev server, a follow-mode tail. It implies progress=False, and the run swaps the status line for a one-time hint that Ctrl-C is how this ends. Listings and help carry the same note.

shared=False says this task is never shared: every request for it runs. A run normally performs one execution per task and arguments, whoever asks — pre=[build] then build() in a body is one build — which is wrong for work whose whole point is to happen again, like a notification or a timestamp. One rule covers every spelling, so nobody has to remember whether a task was reached by declaration or by call: two dependents each get their own run, just as two calls do.

Sharing is a property of the request, resolved by a ladder: this reference's own .opts(shared=…), then the task's declaration, then whatever asked for it, then shared. It propagates down — an unshared request asks unshared for everything it needs, or the promise would be a half-truth — which is worth knowing before reaching for it, because one shared=False unshares that task's whole subtree. A step that genuinely is reusable pins itself with shared=True, which beats an inherited answer.

.opts(shared=False) asks for one unshared run without changing the task, on a call or on a declared edge alike. Such a run gets its own value but never rewrites what the run already remembers: the first result stands, so later shared requests stay stable.

confirm="…" gates the task on a yes/no answer asked before the task and its prerequisites run — deny and the task (and its subtree) is skipped; --yes auto-answers it. interactive=True hands the task the real terminal — no output capture, sole stdio — so its body can prompt or run a REPL; it can't run under --json, and because it owns the terminal, a run that contains an interactive task goes fully sequential — that task and everything else, one at a time.

cwd= roots the task's working directory: a policy token ("root" — the highest cascade file's directory, "taskfile" — the file the task was defined in (the default), "asinvoked" — a pinned snapshot of the launch directory, "unmanaged" — footman stays out entirely) or an absolute path. rel= appends a relative suffix to the resolved base. ctx.cwd and every run()/tools subprocess follow it.

Source code in packages/footman/src/livery/footman/_registry.py
def task(
    self,
    fn: Task | None = None,
    *,
    name: str = "",
    pre: Sequence[Task] = (),
    post: Sequence[Task] = (),
    progress: bool = True,
    infinite: bool = False,
    shared: bool | None = None,
    confirm: str = "",
    interactive: bool = False,
    keep_going: bool | None = None,
    atomic: bool = False,
    timeout: float | None = None,
    retries: int = 0,
    cwd: str | Path = "",
    rel: str | Path = "",
    serial: bool = False,
    exclusive: bool = False,
    hidden: bool | None = None,
    expose: str | None = None,
    lanes: Sequence[Lane] = (),
    uses: Sequence[GlobalOption] = (),
) -> Task | Callable[[Task], Task]:
    """Register a function as a task.

    Usable bare (`@task`) or parameterised (`@task(name="build")`) to
    override the command name. `pre`/`post` declare dependency tasks (by
    reference) that run before/after this one — the scheduler runs
    independent prerequisites in parallel:

    ```python
    @task(pre=[format, lint, typecheck, test])
    def check(): ...
    ```

    Availability gating lives in the `@requires` decorators — stack
    `@requires`, `@requires_dep`, `@requires_tool`, or `@requires_env`
    above `@task` to list a task as unavailable (with a reason) where it
    can't run, rather than hide it.

    Three different things, worth keeping apart:

    * `hidden=True` — **out of the listings, callable as ever.** The
      task drops out of `--list`, `--tree` and group help (`--all`
      brings it back), while `fm <name>` runs it exactly as before,
      <kbd>Tab</kbd> completes it, and the did-you-mean index knows it:
      a listing is prose about the project, completion is help with a
      name you are already typing. For the tasks a machine calls and a
      human never types: a CI entry point, a release step another task
      drives. It is presentation only — prerequisites still run it, a
      group's empty-body fan-out still includes it, and `--json` reports
      it *marked* rather than missing, because a machine is who calls it.
      Unset inherits the enclosing group's answer, so
      `group("internal", hidden=True)` hides a whole subtree and a
      child can still say `hidden=False`.
    * `@requires…` — listed *with a reason* it can't run here.
    * `if sys.platform == "darwin": @task ...` — plain Python, and the
      task does not **exist**: nothing to list, nothing to call, no
      address at all. Reach for it when the task is meaningless on this
      machine, not when it is merely uninteresting to type.

    `progress=False` marks a task whose duration has no rhyme or
    reason (a REPL, a watcher, a network fetch): any run containing it
    never records timing history and never shows a determinate
    progress bar — the indeterminate pulse still does.

    `infinite=True` marks a task that runs until *stopped* — a dev
    server, a follow-mode tail. It implies `progress=False`, and the
    run swaps the status line for a one-time hint that Ctrl-C is how
    this ends. Listings and help carry the same note.

    `shared=False` says this task is **never shared**: every request for
    it runs. A run normally performs one execution per task and arguments,
    whoever asks — `pre=[build]` then `build()` in a body is one build —
    which is wrong for work whose whole point is to happen again, like a
    notification or a timestamp. One rule covers every spelling, so nobody
    has to remember whether a task was reached by declaration or by call:
    two dependents each get their own run, just as two calls do.

    Sharing is a property of the **request**, resolved by a ladder: this
    reference's own `.opts(shared=…)`, then the task's declaration, then
    whatever asked for it, then shared. It propagates *down* — an unshared
    request asks unshared for everything it needs, or the promise would be
    a half-truth — which is worth knowing before reaching for it, because
    one `shared=False` unshares that task's whole subtree. A step that
    genuinely is reusable pins itself with `shared=True`, which beats an
    inherited answer.

    `.opts(shared=False)` asks for one unshared run without changing the
    task, on a call or on a declared edge alike. Such a run gets its own
    value but never rewrites what the run already remembers: the first
    result stands, so later shared requests stay stable.

    `confirm="…"` gates the task on a yes/no answer asked *before* the
    task and its prerequisites run — deny and the task (and its
    subtree) is skipped; `--yes` auto-answers it. `interactive=True`
    hands the task the real terminal — no output capture, sole stdio —
    so its body can prompt or run a REPL; it can't run under `--json`, and
    because it owns the terminal, a run that contains an interactive task
    goes fully sequential — that task and everything else, one at a time.

    `cwd=` roots the task's working directory: a policy token (`"root"` —
    the highest cascade file's directory, `"taskfile"` — the file the task
    was defined in (the default), `"asinvoked"` — a pinned snapshot of the
    launch directory, `"unmanaged"` — footman stays out entirely) or an
    absolute path. `rel=` appends a relative suffix to the resolved base.
    `ctx.cwd` and every `run()`/tools subprocess follow it.
    """

    def register(fn: Callable[_P, _R_co]) -> TaskFn[_P, _R_co]:
        key = cli_name(name or task_name(fn))
        key = self._free_ephemeral_key(key)
        self._shadow_pulled(key)
        self._claim(key)
        task = _TaskFn(fn)  # one handle: registered *and* returned
        if key == "default":
            # The name *is* the mechanism: any task named `default` is its
            # group's default action — `@group.default` is sugar for this.
            # One validation path, so there are no second-class defaults.
            self._stamp_default(task, interactive)
        _apply_policy(
            task,
            pre=pre,
            post=post,
            progress=progress,
            infinite=infinite,
            shared=shared,
            confirm=confirm,
            interactive=interactive,
            keep_going=keep_going,
            atomic=atomic,
            timeout=timeout,
            retries=retries,
            cwd=cwd,
            rel=rel,
            serial=serial,
            exclusive=exclusive,
            hidden=hidden,
            expose=expose,
            lanes=lanes,
        )
        if uses:
            for used in uses:
                if not isinstance(used, GlobalOption):
                    raise RegistrationError(
                        f"@task(uses=...) on {key!r} takes GlobalOption "
                        f"singletons — got {type(used).__name__}"
                    )
            setattr(task, _USES, tuple(uses))
        if cli_name(task.__name__) != key:
            # Numbered by `_free_ephemeral_key`: report it under the name
            # it actually answers to, not the one it collided on.
            object.__setattr__(task, "__name__", key)
        previous = self.tasks.get(key)
        self.tasks[key] = task
        _note_if_ephemeral(self, key, previous)
        return cast("TaskFn[_P, _R_co]", task)

    return register(fn) if fn is not None else register

group

group(name: str, help: str = '', hidden: bool | None = None, expose: str | None = None) -> Group

Create and register a nested command group, returning it.

hidden=True keeps the whole subtree out of the human listings (--list, --tree, help — --all shows them) while leaving every address in it callable and completable — see @task(hidden=…).

expose="project_only" says the whole subtree belongs to a project: outside one it is not listed, not completed, and refused by name. "global_only" says the opposite, "always" says both. A child may still answer for itself — the same tri-state hidden has.

Source code in packages/footman/src/livery/footman/_registry.py
def group(
    self,
    name: str,
    help: str = "",
    hidden: bool | None = None,
    expose: str | None = None,
) -> Group:
    """Create and register a nested command group, returning it.

    `hidden=True` keeps the whole subtree out of the human listings
    (`--list`, `--tree`, help — `--all` shows them) while leaving every
    address in it callable and completable — see `@task(hidden=…)`.

    `expose="project_only"` says the whole subtree belongs to a project:
    outside one it is not listed, not completed, and refused by name.
    `"global_only"` says the opposite, `"always"` says both. A child may
    still answer for itself — the same tri-state `hidden` has.
    """
    key = cli_name(name)
    if key == "default":
        # `default` is a meaningful *task* name — the group's default
        # action. A group-typed default is incoherent (a bare `fm lint`
        # resolving to another bare group — turtles), so the name is
        # refused for groups at load time.
        raise RegistrationError(
            f"a group cannot be named 'default': the name means \"this "
            f"group's default action\" and belongs to a task — declare "
            f"@{self.name}.default, or name a task 'default'"
        )
    adopted = self.groups.get(key)
    if adopted is not None and adopted.mounted_from is not None:
        # A local definition over a *mounted* group adopts it rather than
        # evicting it: claiming the name means adding to it — exactly
        # what mounting after the definition produces. Local leaves still
        # shadow mounted ones (task-level `_shadow_pulled`), so definition
        # order stops mattering: either way the union, local wins per
        # leaf, and only the listing order follows the file.
        if help:
            adopted.help = help
        if hidden is not None:
            adopted.hidden = hidden
        if expose is not None:
            adopted.expose = expose
        return adopted
    self._shadow_pulled(key)
    self._claim(key)
    sub = Group(key, help, hidden, expose)
    self.groups[key] = sub
    return sub

pre_tasks

pre_tasks(fn: _F) -> _F

Register the once-per-invocation hook, run before anything else.

It happens after the whole tasks.py cascade is assembled and before availability gates, the manifest, and any task — the one single-threaded moment where the invocation is still editable. It is handed the Invocation:

@footman.pre_tasks
def gate_deploys(inv):
    audit = inv.tasks["audit"]
    for t in inv.tasks:
        if t.name.startswith("deploy"):
            t.add_pre(audit)

Its edits are part of the plan, never a runtime surprise: an added pre runs and shows in --dry-run, a disabled task drops out of listings and completion. Setting os.environ here is ordinary code — it is pre-DAG and single-threaded, so everything downstream sees it, including requires_env gates and env() parameter fallbacks. (Per-task environment is a different lane: ctx.env.)

Hooks run in cascade order — root's first, the folder nearest your cwd last, each seeing the previous ones' edits — the same "local overrides global" precedence the task cascade uses. Read and edit each task through TaskView, never the private _footman_* attributes.

It also runs in the detached child that rebuilds the completion manifest, so a gate that depends on what a hook sets is baked into completion too. That is why it must be quick and quiet, and why tree edits derive from files, config and environment — never from inv.cli, which the child does not have.

Source code in packages/footman/src/livery/footman/_registry.py
def pre_tasks(self, fn: _F) -> _F:
    """Register the once-per-invocation hook, run before anything else.

    It happens after the whole `tasks.py` cascade is assembled and *before*
    availability gates, the manifest, and any task — the one single-threaded
    moment where the invocation is still editable. It is handed the
    `Invocation`:

        @footman.pre_tasks
        def gate_deploys(inv):
            audit = inv.tasks["audit"]
            for t in inv.tasks:
                if t.name.startswith("deploy"):
                    t.add_pre(audit)

    Its edits are part of the plan, never a runtime surprise: an added `pre`
    runs and shows in `--dry-run`, a disabled task drops out of listings and
    completion. Setting `os.environ` here is ordinary code — it is pre-DAG
    and single-threaded, so everything downstream sees it, including
    `requires_env` gates and `env()` parameter fallbacks. (Per-*task*
    environment is a different lane: `ctx.env`.)

    Hooks run in cascade order — root's first, the folder nearest your cwd
    last, each seeing the previous ones' edits — the same "local overrides
    global" precedence the task cascade uses. Read and edit each task
    through `TaskView`, never the private `_footman_*` attributes.

    It also runs in the detached child that rebuilds the completion
    manifest, so a gate that depends on what a hook sets is baked into
    completion too. That is why it must be **quick and quiet**, and why
    tree edits derive from files, config and environment — never from
    `inv.cli`, which the child does not have.
    """
    _check_hook_arity("pre_tasks", fn, 1)
    self.contributions["pre_tasks"].append(fn)
    _note_contribution(fn, "pre_tasks", fn)
    return fn

pre_bind

pre_bind(fn: _F) -> _F

Register the before-binding hook: pre_bind(inv, task).

The earliest per-task moment: it fires before the task's parameters are bound, so what it writes into task.env reaches env() fallbacks, coercion, and check(fn) validators — the one moment a plugin can influence what the body will be handed:

@footman.pre_bind
def credentials(inv, task):
    task.env["DEPLOY_TOKEN"] = vault.read("deploy")

Because nothing is bound yet, task.args is not readable here — read the values in pre_task, the post-bind moment. Binding happens once per request: a request that then joins work the run already performed still bound first, so pre_bind may fire for a request whose row ends up shared.

Source code in packages/footman/src/livery/footman/_registry.py
def pre_bind(self, fn: _F) -> _F:
    """Register the before-binding hook: `pre_bind(inv, task)`.

    The earliest per-task moment: it fires before the task's parameters
    are bound, so what it writes into `task.env` reaches `env()`
    fallbacks, coercion, and `check(fn)` validators — the one moment a
    plugin can influence what the body will be handed:

        @footman.pre_bind
        def credentials(inv, task):
            task.env["DEPLOY_TOKEN"] = vault.read("deploy")

    Because nothing is bound yet, `task.args` is not readable here —
    read the values in `pre_task`, the post-bind moment. Binding happens
    once per *request*: a request that then joins work the run already
    performed still bound first, so `pre_bind` may fire for a request
    whose row ends up `shared`.
    """
    _check_hook_arity("pre_bind", fn, 2)
    self.contributions["pre_bind"].append(fn)
    _note_contribution(fn, "pre_bind", fn)
    return fn

post_tasks

post_tasks(fn: _F) -> _F

Register the once-per-invocation closing hook: post_tasks(inv).

The run report's moment, on the main thread, after every task has concluded and before the summary or the --json envelope prints — so a rewrite a hook makes through a result view is what gets reported. The invocation now carries the whole story:

@footman.post_tasks
def digest(inv):
    failed = [r for r in inv.results if not r.ok]
    slack.post(f"{len(failed)} failed of {len(inv.results)}, "
               f"{inv.total_ms:.0f} ms")

inv.results is every row, in the order the work was created, as result views — executions, shared rows, refusals, and skipped nodes (inv.skipped is that subset; a post_task-only reporter never sees what never ran, which is why this moment exists). Under --json anything a hook prints goes to stderr — the envelope owns stdout. Hooks run in cascade order; a raising hook is named and fails the invocation rather than passing silently.

Source code in packages/footman/src/livery/footman/_registry.py
def post_tasks(self, fn: _F) -> _F:
    """Register the once-per-invocation closing hook: `post_tasks(inv)`.

    The run report's moment, on the main thread, after every task has
    concluded and before the summary or the `--json` envelope prints —
    so a rewrite a hook makes through a result view is what gets
    reported. The invocation now carries the whole story:

        @footman.post_tasks
        def digest(inv):
            failed = [r for r in inv.results if not r.ok]
            slack.post(f"{len(failed)} failed of {len(inv.results)}, "
                       f"{inv.total_ms:.0f} ms")

    `inv.results` is every row, in the order the work was created, as
    result views —
    executions, `shared` rows, refusals, and `skipped` nodes
    (`inv.skipped` is that subset; a `post_task`-only reporter never
    sees what never ran, which is why this moment exists). Under
    `--json` anything a hook prints goes to stderr — the envelope owns
    stdout. Hooks run in cascade order; a raising hook is named and
    fails the invocation rather than passing silently.
    """
    _check_hook_arity("post_tasks", fn, 1)
    self.contributions["post_tasks"].append(fn)
    _note_contribution(fn, "post_tasks", fn)
    return fn

pre_reexec

pre_reexec(fn: _F) -> _F

Register a block for the moment this process replaces itself.

A verb that re-runs its own command line in a new process — a sync that installed the code the process is running, a handoff into another environment — loses everything the process held. A plugin with state worth keeping across that gets it here:

@footman.pre_reexec
@contextlib.contextmanager
def carry_the_trace():
    fragment = write_what_we_have()
    yield {"MY_PLUGIN_STATE": str(fragment)}
    fragment.unlink()  # still here, so nothing was replaced

The hook is a context manager taking nothing and yielding a mapping of environment entries for the successor, which the caller hands to execve or subprocess.run(env=…). What it yields is merged with every other subscriber's, and the caller's own entries win.

The block it wraps ends by not returning: an exec that works never comes back, and a handoff that waits for its replacement exits with its code. So a normal return means the replacement did not happen and whatever was written down should be taken back; an exception means it did, and the state stands. livery.footman.handing_off is the composer a re-execing verb calls.

Source code in packages/footman/src/livery/footman/_registry.py
def pre_reexec(self, fn: _F) -> _F:
    """Register a block for the moment this process replaces itself.

    A verb that re-runs its own command line in a new process — a sync
    that installed the code the process is running, a handoff into
    another environment — loses everything the process held. A plugin
    with state worth keeping across that gets it here:

        @footman.pre_reexec
        @contextlib.contextmanager
        def carry_the_trace():
            fragment = write_what_we_have()
            yield {"MY_PLUGIN_STATE": str(fragment)}
            fragment.unlink()  # still here, so nothing was replaced

    The hook is a context manager taking nothing and yielding a mapping
    of environment entries for the successor, which the caller hands to
    `execve` or `subprocess.run(env=…)`. What it yields is merged with
    every other subscriber's, and the caller's own entries win.

    The block it wraps ends by not returning: an exec that works never
    comes back, and a handoff that waits for its replacement exits with
    its code. So a *normal* return means the replacement did not happen
    and whatever was written down should be taken back; an exception
    means it did, and the state stands. `livery.footman.handing_off` is
    the composer a re-execing verb calls.
    """
    _check_hook_arity("pre_reexec", fn, 0)
    self.contributions["pre_reexec"].append(fn)
    _note_contribution(fn, "pre_reexec", fn)
    return fn

wrap_task

wrap_task(fn: _F) -> _F

Register a one-yield wrapper around the body: sugar over the pair.

Write the pre half, result = yield, then the post half — locals carry your state, and a try/finally around the yield closes even when the task fails:

@footman.wrap_task
def span(inv, task):
    s = tracer.start(task.name, dict(task.args))
    result = yield
    s.end(ok=result.ok)

It enters at the pre_task moment and is resumed with the ResultView at post_task — one engine, both spellings, so the rules are the pair's rules: per request (a request satisfied by an execution the run already performed is resumed with its shared row), unwound in reverse plugin order, a raising half failing the task, named. The one thing it never sees is a task that failed to bind — its anchor moment never fires; observe the bind boundary with @wrap_bind, which enters there.

Source code in packages/footman/src/livery/footman/_registry.py
def wrap_task(self, fn: _F) -> _F:
    """Register a one-yield wrapper around the body: sugar over the pair.

    Write the pre half, `result = yield`, then the post half — locals
    carry your state, and a `try/finally` around the yield closes even
    when the task fails:

        @footman.wrap_task
        def span(inv, task):
            s = tracer.start(task.name, dict(task.args))
            result = yield
            s.end(ok=result.ok)

    It enters at the `pre_task` moment and is resumed with the
    `ResultView` at `post_task` — one engine, both spellings, so the
    rules are the pair's rules: per request (a request satisfied by an
    execution the run already performed is resumed with its `shared`
    row), unwound in reverse plugin order, a raising half failing the
    task, named. The one thing it never sees is a task that failed to
    **bind** — its anchor moment never fires; observe the bind boundary
    with `@wrap_bind`, which enters there.
    """
    name = getattr(fn, "__name__", repr(fn))
    if not _isgeneratorfunction(fn):
        raise RegistrationError(
            f"@wrap_task {name!r} must be a generator function — write "
            f"`result = yield` where the body runs (a plain pair of "
            f"functions is @pre_task + @post_task)"
        )
    _check_hook_arity("wrap_task", fn, 2)
    key = f"__wrap_task_{name}"

    @functools.wraps(fn)
    def _pre(inv: object, task: Any) -> None:
        gen: Any = fn(inv, task)
        try:
            next(gen)  # the pre half, up to the yield
        except StopIteration:
            raise RuntimeError(
                f"@wrap_task {name!r} returned without yielding — exactly "
                f"one `result = yield` marks where the body runs"
            ) from None
        setattr(task.state, key, gen)

    @functools.wraps(fn)
    def _post(inv: object, task: Any, result: Any) -> None:
        gen = getattr(task.state, key, None)
        if gen is None:
            return  # the anchor never fired (a bind failure): no span open
        try:
            gen.send(result)  # the post half, to the end
        except StopIteration:
            return
        raise RuntimeError(
            f"@wrap_task {name!r} yielded a second time — one yield "
            f"exactly; @wrap_bind is the two-yield wrapper that enters at "
            f"the bind boundary"
        )

    self.contributions["pre_task"].append(_pre)
    self.contributions["post_task"].append(_post)
    _note_contribution(fn, "pre_task", _pre)
    _note_contribution(fn, "post_task", _post)
    return fn

wrap_bind

wrap_bind(fn: _F) -> _F

Register a two-yield wrapper spanning bind, body and all: sugar over pre_bind + pre_task + post_task, one generator per request.

The first yield sits at the bind boundary and receives the bound arguments; the second sits around the body and receives the ResultView:

@footman.wrap_bind
def audit(inv, task):
    started = clock()
    try:
        bound = yield      # after binding: the real values
        result = yield     # after the body: the outcome
    finally:
        log(task.name, clock() - started)

A failed bind arrives as the failure raised at the first yield, so a try/finally (or except) around it closes the span even then — the one span wrap_task cannot close. Everything else is the pair's rules, per request.

Source code in packages/footman/src/livery/footman/_registry.py
def wrap_bind(self, fn: _F) -> _F:
    """Register a two-yield wrapper spanning bind, body and all: sugar
    over `pre_bind` + `pre_task` + `post_task`, one generator per request.

    The first yield sits at the bind boundary and receives the bound
    arguments; the second sits around the body and receives the
    `ResultView`:

        @footman.wrap_bind
        def audit(inv, task):
            started = clock()
            try:
                bound = yield      # after binding: the real values
                result = yield     # after the body: the outcome
            finally:
                log(task.name, clock() - started)

    A failed **bind** arrives as the failure raised at the first yield,
    so a `try/finally` (or `except`) around it closes the span even
    then — the one span `wrap_task` cannot close. Everything else is the
    pair's rules, per request.
    """
    name = getattr(fn, "__name__", repr(fn))
    if not _isgeneratorfunction(fn):
        raise RegistrationError(
            f"@wrap_bind {name!r} must be a generator function — write "
            f"`bound = yield` then `result = yield` (a plain trio of "
            f"functions is @pre_bind + @pre_task + @post_task)"
        )
    _check_hook_arity("wrap_bind", fn, 2)
    key = f"__wrap_bind_{name}"

    @functools.wraps(fn)
    def _bind_pre(inv: object, task: Any) -> None:
        gen: Any = fn(inv, task)
        try:
            next(gen)  # up to the bind boundary
        except StopIteration:
            raise RuntimeError(
                f"@wrap_bind {name!r} returned without yielding — it "
                f"takes two: `bound = yield`, then `result = yield`"
            ) from None
        setattr(task.state, key, (gen, "binding"))

    @functools.wraps(fn)
    def _pre(inv: object, task: Any) -> None:
        pair = getattr(task.state, key, None)
        if pair is None:
            return
        gen, _ = pair
        try:
            gen.send(task.args)  # binding done: hand over the values
        except StopIteration:
            raise RuntimeError(
                f"@wrap_bind {name!r} finished after one yield — it "
                f"takes two: `bound = yield`, then `result = yield`"
            ) from None
        setattr(task.state, key, (gen, "running"))

    @functools.wraps(fn)
    def _post(inv: object, task: Any, result: Any) -> None:
        pair = getattr(task.state, key, None)
        if pair is None:
            return
        gen, phase = pair
        try:
            if phase == "binding":
                # Binding never completed: the failure arrives at the
                # first yield, so the author's try/finally closes the
                # span. Whatever propagates back out is the same failure
                # the task already reported.
                error = result.error
                if error is None:
                    error = RuntimeError("binding never completed")
                gen.throw(error)
            else:
                gen.send(result)  # the closing half, to the end
        except StopIteration:
            return
        except BaseException:
            if phase == "binding":
                return  # the thrown failure resurfacing: span closed
            raise
        raise RuntimeError(
            f"@wrap_bind {name!r} yielded again after the result — two "
            f"yields exactly"
        )

    self.contributions["pre_bind"].append(_bind_pre)
    self.contributions["pre_task"].append(_pre)
    self.contributions["post_task"].append(_post)
    _note_contribution(fn, "pre_bind", _bind_pre)
    _note_contribution(fn, "pre_task", _pre)
    _note_contribution(fn, "post_task", _post)
    return fn

pre_task

pre_task(fn: _F) -> _F

Register the before-each-task hook: pre_task(inv, task).

Runs on the task's worker thread — in parallel across tasks, for every request: a chain segment, a prerequisite, a fan-out member, a body call. Only the body is shared: a request satisfied by an execution the run already performed still gets the pair, opened here and closed by post_task with its shared row — so pairing never depends on sharing, and only a reporter that cares reads result.state. It fires after binding, so task.args holds the real values the body would receive:

@footman.pre_task
def open_span(inv, task):
    task.state.span = tracer.start(task.name, dict(task.args))

inv is the frozen invocation — read it freely, it cannot change under you. Per-plugin scratch goes on task.state (private to your plugin, one namespace per execution, delivered back to your post_task); per-task environment goes in task.env (the task's own overlay — never os.environ, which is shared with every parallel sibling). A raising hook fails the task like a failed prerequisite, named.

The return value is reserved: a future power for a pre that supplies the task's result and skips the body. Today a returned value is noted and ignored — state belongs on task.state.

Source code in packages/footman/src/livery/footman/_registry.py
def pre_task(self, fn: _F) -> _F:
    """Register the before-each-task hook: `pre_task(inv, task)`.

    Runs on the task's worker thread — in parallel across tasks, for
    every *request*: a chain segment, a prerequisite, a fan-out member, a
    body call. Only the body is shared: a request satisfied by an
    execution the run already performed still gets the pair, opened here
    and closed by `post_task` with its `shared` row — so pairing never
    depends on sharing, and only a reporter that cares reads
    `result.state`. It fires after binding, so `task.args` holds the
    real values the body would receive:

        @footman.pre_task
        def open_span(inv, task):
            task.state.span = tracer.start(task.name, dict(task.args))

    `inv` is the frozen invocation — read it freely, it cannot change under
    you. Per-plugin scratch goes on `task.state` (private to your plugin,
    one namespace per execution, delivered back to your `post_task`);
    per-task environment goes in `task.env` (the task's own overlay —
    never `os.environ`, which is shared with every parallel sibling).
    A raising hook fails the task like a failed prerequisite, named.

    The return value is **reserved**: a future power for a pre that
    supplies the task's result and skips the body. Today a returned value
    is noted and ignored — state belongs on `task.state`.
    """
    _check_hook_arity("pre_task", fn, 2)
    self.contributions["pre_task"].append(fn)
    _note_contribution(fn, "pre_task", fn)
    return fn

post_task

post_task(fn: _F) -> _F

Register the after-each-task hook: post_task(inv, task, result).

The task-finished event: once a request's ladder opened, it fires when the request concludes — an execution whatever its outcome, a bind refusal, or a request satisfied by an execution the run already performed (result.state == "shared"). It fires whether or not your plugin registered a pre, and however any pre fared. Posts unwind in reverse plugin order, so the first plugin in speaks last.

result reads everything (ok, code, returned, error, duration, output, steps) and writes one thing: set_returned, which rewrites the reported value — the summary and the --json envelope — never what a dependent or a body caller received. A raising hook fails an otherwise-green task, named: a reporter that crashed must not pass silently.

@footman.post_task
def close_span(inv, task, result):
    task.state.span.end(ok=result.ok)
Source code in packages/footman/src/livery/footman/_registry.py
def post_task(self, fn: _F) -> _F:
    """Register the after-each-task hook: `post_task(inv, task, result)`.

    The task-finished event: once a request's ladder opened, it fires
    when the request concludes — an execution whatever its outcome, a
    bind refusal, or a request satisfied by an execution the run already
    performed (`result.state == "shared"`). It fires whether or not your
    plugin registered a pre, and however any pre fared. Posts unwind in
    reverse plugin order, so the first plugin in speaks last.

    `result` reads everything (`ok`, `code`, `returned`, `error`,
    `duration`, `output`, `steps`) and writes one thing: `set_returned`,
    which rewrites the *reported* value — the summary and the `--json`
    envelope — never what a dependent or a body caller received. A raising
    hook fails an otherwise-green task, named: a reporter that crashed
    must not pass silently.

        @footman.post_task
        def close_span(inv, task, result):
            task.state.span.end(ok=result.ok)
    """
    _check_hook_arity("post_task", fn, 3)
    self.contributions["post_task"].append(fn)
    _note_contribution(fn, "post_task", fn)
    return fn

default

default(fn: Callable[_P, _R_co]) -> TaskFn[_P, _R_co]
default(fn: None = None, *, pre: Sequence[Task] = (), post: Sequence[Task] = (), progress: bool = True, infinite: bool = False, shared: bool | None = None, confirm: str = '', interactive: bool = False, keep_going: bool | None = None, atomic: bool = False, timeout: float | None = None, retries: int = 0, cwd: str | Path = '', rel: str | Path = '', serial: bool = False, exclusive: bool = False, hidden: bool | None = None, expose: str | None = None) -> Callable[[Callable[_P, _R_co]], TaskFn[_P, _R_co]]
default(fn: Task | None = None, *, pre: Sequence[Task] = (), post: Sequence[Task] = (), progress: bool = True, infinite: bool = False, shared: bool | None = None, confirm: str = '', interactive: bool = False, keep_going: bool | None = None, atomic: bool = False, timeout: float | None = None, retries: int = 0, cwd: str | Path = '', rel: str | Path = '', serial: bool = False, exclusive: bool = False, hidden: bool | None = None, expose: str | None = None) -> Task | Callable[[Task], Task]

Register fn as this group's default action — what a bare fm <group> runs, and what the group returns when called.

Usable bare (@group.default) or parameterised (@group.default(keep_going=True)). It takes the same orchestration options as @task — pre/post, progress, infinite, confirm, interactive, keep_going, atomic — with no name (the group already names it).

The function's signature is the group's whole CLI surface, positionals included: fm lint src/ hands src/ to the default the way any task takes an argument. A nested task always keeps its own dotted address (fm lint.python), so a bare word after the group is unambiguously the default's value — when a value happens to equal a child's name, the run carries a one-line stderr note pointing at the dotted spelling.

An empty-body default fans the group's own tasks out in parallel, so interactive=True on one is rejected — there is no single body to own the terminal. Give the default a real body to make it interactive.

The default registers as the child task named default — a fixed, well-known name, not the function's own (which stays private, so renaming it is free). The decorator you wrote is the address you type: @lint.default ↔ fm lint.default; bare fm lint stays the idiomatic spelling, the way GET / serves /index.html. The name is the mechanism — @group.default is sugar for a task named default.

Source code in packages/footman/src/livery/footman/_registry.py
def default(
    self,
    fn: Task | None = None,
    *,
    pre: Sequence[Task] = (),
    post: Sequence[Task] = (),
    progress: bool = True,
    infinite: bool = False,
    shared: bool | None = None,
    confirm: str = "",
    interactive: bool = False,
    keep_going: bool | None = None,
    atomic: bool = False,
    timeout: float | None = None,
    retries: int = 0,
    cwd: str | Path = "",
    rel: str | Path = "",
    serial: bool = False,
    exclusive: bool = False,
    hidden: bool | None = None,
    expose: str | None = None,
) -> Task | Callable[[Task], Task]:
    """Register *fn* as this group's default action — what a bare
    `fm <group>` runs, and what the group returns when called.

    Usable bare (`@group.default`) or parameterised
    (`@group.default(keep_going=True)`). It takes the same orchestration
    options as `@task` — `pre`/`post`, `progress`, `infinite`, `confirm`,
    `interactive`, `keep_going`, `atomic` — with no `name` (the group
    already names it).

    The function's signature *is* the group's whole CLI surface,
    positionals included: `fm lint src/` hands `src/` to the default the
    way any task takes an argument. A nested task always keeps its own
    dotted address (`fm lint.python`), so a bare word after the group is
    unambiguously the default's value — when a value happens to equal a
    child's name, the run carries a one-line stderr note pointing at the
    dotted spelling.

    An **empty-body** default fans the group's own tasks out in parallel, so
    `interactive=True` on one is rejected — there is no single body to own
    the terminal. Give the default a real body to make it interactive.

    The default registers as the child task named **`default`** — a
    fixed, well-known name, not the function's own (which stays private,
    so renaming it is free). The decorator you wrote is the address you
    type: `@lint.default` ↔ `fm lint.default`; bare `fm lint` stays the
    idiomatic spelling, the way `GET /` serves `/index.html`. The name is
    the mechanism — `@group.default` is sugar for a task named `default`.
    """

    def register(fn: Callable[_P, _R_co]) -> TaskFn[_P, _R_co]:
        self._claim("default")
        task = _TaskFn(fn)  # one handle: registered *and* returned
        self._stamp_default(task, interactive)
        _apply_policy(
            task,
            pre=pre,
            post=post,
            progress=progress,
            infinite=infinite,
            shared=shared,
            confirm=confirm,
            interactive=interactive,
            keep_going=keep_going,
            atomic=atomic,
            timeout=timeout,
            retries=retries,
            cwd=cwd,
            rel=rel,
            serial=serial,
            exclusive=exclusive,
            hidden=hidden,
            expose=expose,
        )
        self.tasks["default"] = task
        return cast("TaskFn[_P, _R_co]", task)

    return register(fn) if fn is not None else register

opts

opts(**overrides: Unpack[TaskOpts]) -> TaskFn[..., Any]

Per-use option overrides for this group's default action, the same .opts() a task has — pre=[lint.opts(keep_going=True)]. Overrides ride the group's default when it runs (bare, as a pre=, or called). The static type is a task reference with an untracked signature — Group doesn't carry its default's parameters the way TaskFn carries a task's.

Source code in packages/footman/src/livery/footman/_registry.py
def opts(self, **overrides: Unpack[TaskOpts]) -> TaskFn[..., Any]:
    """Per-use option overrides for this group's default action, the same
    `.opts()` a task has — `pre=[lint.opts(keep_going=True)]`. Overrides ride
    the group's default when it runs (bare, as a `pre=`, or called). The
    static type is a task reference with an untracked signature — `Group`
    doesn't carry its default's parameters the way `TaskFn` carries a
    task's."""
    return cast("TaskFn[..., Any]", _Opted(self, _opts_overrides(dict(overrides))))

__call__

__call__(*args: Any, **kwargs: Any) -> Any

Run this group's default action — the imperative mirror of a bare fm <group> and of pre=[group].

A runnable group (one with an @group.default) is callable from a task body the way a task is: a check task can call lint(fix=fix). It runs the default's action synchronously and in order — a custom body as written, or, for an empty-body default, the group's own tasks, each handed the arguments it declares (partial reach, by name). Like every body call it forwards arguments explicitly and runs to completion before the next statement; prerequisites and parallelism stay the scheduler's job — reach for a real chain, pre=, or parallel() for those.

Source code in packages/footman/src/livery/footman/_registry.py
def __call__(self, *args: Any, **kwargs: Any) -> Any:
    """Run this group's default action — the imperative mirror of a bare
    `fm <group>` and of `pre=[group]`.

    A runnable group (one with an `@group.default`) is callable from a task
    body the way a task is: a `check` task can call `lint(fix=fix)`. It runs
    the default's action synchronously and in order — a custom body as
    written, or, for an empty-body default, the group's own tasks, each
    handed the arguments it declares (partial reach, by name). Like every
    body call it forwards arguments explicitly and runs to completion before
    the next statement; prerequisites and parallelism stay the scheduler's
    job — reach for a real chain, `pre=`, or `parallel()` for those.
    """
    if self.default_task is None:
        raise TypeError(
            f"group {self.name!r} is not runnable: it has no "
            f"@{self.name}.default, so there is no action to call. Add a "
            f"default action, or call a task inside the group directly."
        )
    if not fans_out(self.default_task):
        return self.default_task(*args, **kwargs)  # custom body: as written
    # Empty-body default: fan out the group's own tasks, handing each only
    # the arguments it declares — the imperative echo of `fm <group>`.
    # Sequential, like any body call; wrap the call in parallel() to overlap.
    # The `default` child is the fan-out itself: excluded from its own set.
    from livery.footman._manifest import resolved_signature

    for name, child in self.tasks.items():
        if name == "default":
            continue
        accepts = set(resolved_signature(child).parameters)
        child(**{k: v for k, v in kwargs.items() if k in accepts})
    return None

livery.footman.expose

expose(where: str) -> Callable[[_F], _F]

Say where a task is offered: @expose("global_only").

The decorator spelling of @task(expose=…), for authors who prefer the gates above the signature — it sets the same one answer, so stacking it twice is a contradiction rather than an addition, unlike @requires_*.

@task
@expose("global_only")
def new(name: str): ...
Source code in packages/footman/src/livery/footman/_registry.py
def expose(where: str) -> Callable[[_F], _F]:
    """Say where a task is offered: `@expose("global_only")`.

    The decorator spelling of `@task(expose=…)`, for authors who prefer the
    gates above the signature — it sets the same one answer, so stacking it
    twice is a contradiction rather than an addition, unlike `@requires_*`.

    ```python
    @task
    @expose("global_only")
    def new(name: str): ...
    ```
    """
    checked = _checked_expose(where)

    def mark(fn: _F) -> _F:
        setattr(fn, _EXPOSE, checked)
        return fn

    return mark

livery.footman.root_group module-attribute

root_group: Final[Group] = Group('root')

livery.footman.task_tree

task_tree() -> dict[str, Any]

The composed task tree of this process, as --json --list reports it.

Every task and group the cascade and the plugins mounted into the running CLI, with each task's hidden flag and the extension that mounted it, in the shape the catalog envelope prints. A task that renders a listing of its own CLI reads this instead of running the CLI again: the tree is built before any task runs, and this is a copy of it. A tree is a process's own, made from the distributions on its path, so another directory's tree is listed by running that directory's CLI with --json --list. Outside a run the tree is the process registry's, which holds what was registered so far.

for name in footman.task_tree()["tasks"]:
    ...
Source code in packages/footman/src/livery/footman/_manifest.py
def task_tree() -> dict[str, Any]:
    """The composed task tree of this process, as ``--json --list`` reports it.

    Every task and group the cascade and the plugins mounted into the
    running CLI, with each task's ``hidden`` flag and the extension that
    mounted it, in the shape the catalog envelope prints. A task that
    renders a listing of its own CLI reads this instead of running the
    CLI again: the tree is built before any task runs, and this is a copy
    of it. A tree is a process's own, made from the distributions on its
    path, so another directory's tree is listed by running that
    directory's CLI with ``--json --list``. Outside a run the tree is the
    process registry's, which holds what was registered so far.

    ```python
    for name in footman.task_tree()["tasks"]:
        ...
    ```
    """
    if _served is not None:
        return copy.deepcopy(_served)
    from livery.footman import _registry
    from livery.footman._context import project_root

    tree: dict[str, Any] = build_manifest(
        _registry.root, project=project_root() is not None
    )["tree"]
    return tree

Availability gates

Stack these above @task to list a task as unavailable (with a reason) where it can't run. Every availability gate is evaluated live, and all failures are collected.

livery.footman.requires

requires(predicate: Callable[[], object], *, reason: str = '') -> Callable[[_F], _F]

Gate a task on a live predicate — available only while it is truthy.

The generic gate the three specialisations build on. A predicate that raises reads as unavailable, the exception named:

@task
@requires(lambda: Path("config.toml").exists(), reason="needs config.toml")
def publish(): ...
Source code in packages/footman/src/livery/footman/_registry.py
def requires(
    predicate: Callable[[], object], *, reason: str = ""
) -> Callable[[_F], _F]:
    """Gate a task on a live *predicate* — available only while it is truthy.

    The generic gate the three specialisations build on. A predicate that
    raises reads as unavailable, the exception named:

    ```python
    @task
    @requires(lambda: Path("config.toml").exists(), reason="needs config.toml")
    def publish(): ...
    ```
    """

    def check() -> str | None:
        try:
            ok = predicate()
        except Exception as exc:
            detail = f"{type(exc).__name__}: {exc}"
            return f"{reason} ({detail})" if reason else detail
        return None if ok else (reason or "unavailable here")

    return _gate(check)

livery.footman.requires_dep

requires_dep(*modules: str, reason: str = '') -> Callable[[_F], _F]

Gate a task on Python modules being importable (find_spec, no import).

Keep the real import in the body; this only checks availability, so a missing optional dependency lists as a clean reason, never an import crash.

Source code in packages/footman/src/livery/footman/_registry.py
def requires_dep(*modules: str, reason: str = "") -> Callable[[_F], _F]:
    """Gate a task on Python *modules* being importable (`find_spec`, no import).

    Keep the real `import` in the body; this only checks availability, so a
    missing optional dependency lists as a clean reason, never an import crash.
    """

    def check() -> str | None:
        missing = [m for m in modules if not _importable(m)]
        if not missing:
            return None
        return reason or f"requires {', '.join(missing)}"

    return _gate(check)

livery.footman.requires_tool

requires_tool(*commands: str, reason: str = '') -> Callable[[_F], _F]

Gate a task on command-line tools being on PATH (shutil.which).

Source code in packages/footman/src/livery/footman/_registry.py
def requires_tool(*commands: str, reason: str = "") -> Callable[[_F], _F]:
    """Gate a task on command-line tools being on `PATH` (`shutil.which`)."""

    def check() -> str | None:
        import shutil

        missing = [c for c in commands if shutil.which(c) is None]
        if not missing:
            return None
        return reason or f"requires {', '.join(missing)} on PATH"

    return _gate(check)

livery.footman.requires_env

requires_env(*names: str, reason: str = '') -> Callable[[_F], _F]

Gate a task on environment variables being set (in os.environ).

Source code in packages/footman/src/livery/footman/_registry.py
def requires_env(*names: str, reason: str = "") -> Callable[[_F], _F]:
    """Gate a task on environment variables being set (`in os.environ`)."""

    def check() -> str | None:
        missing = [v for v in names if v not in os.environ]
        if not missing:
            return None
        return reason or f"set {', '.join(missing)}"

    return _gate(check)

Running commands

livery.footman.run

run(cmd: str | list[str] | Callable[..., Any], *args: Any, nofail: bool = False, recorded: bool = True, capture: bool = True, input: str | bytes | None = None, timeout: float | None = None, title: str | None = None, pre_record: Callable[[ResultView], None] | None = None, env: dict[str, str] | None = None, color: str = 'auto', cwd: str | Path | None = None, rel: str | Path | None = None, encoding: str | None = 'utf-8', shell: bool | str = False, strict: bool = False, clean: bool = False, view: CommandView | None = None) -> Result

Run a command or a Python callable in the current task's context.

Subprocess output is decoded as UTF-8 by default; pass encoding= for a tool that speaks another code page, or encoding=None for the locale default. Ignored for callables (in-process, no bytes boundary).

input= feeds the child's standard input and closes it — the one lane a payload can't take through argv (uv pip install -r - reads its requirements there). A string, encoded the way the capture is decoded (encoding=). Bytes go as they are, in a binary lane: no newline translation on any platform, and the captured streams are decoded with surrogateescape, so stdout.encode(encoding, "surrogateescape") gives a binary tool's bytes back exactly. The read side of the process boundary is a task parameter marked stdin; this is the write side, so a task can sit in the middle of a pipeline without a shell between it and either neighbour. An in-process tool has no standard input to feed — input= on one is a taught TypeError.

cwd= roots this one call somewhere other than the task's directory; rel= appends a relative suffix to the base in force (ctx.cwd, or the explicit cwd=), so run("npm run build", rel="web") is the ergonomic spelling of cwd=ctx.cwd / "web". cwd="unmanaged" opts this one call out instead — the task-level token, per call: a subprocess spawns inheriting the live process cwd, an in-process callable runs under it — for a call that touches no paths while its task keeps ctx.cwd everywhere else.

color= decides what this one child emits: "always" forces the colour variables into its environment, "never" writes NO_COLOR and removes any inherited force variables (a tool reading mere presence would honour one straight past NO_COLOR), and the default "auto" follows the run's own decision. Explicit beats ambient, so color="always" holds under an exported NO_COLOR. It merges on top of env= when both are given, and the in-process lane's overlay reads it too — so a per-call colour reaches both halves of a tool's colour, its flags and its environment, through one door. footman's own chrome (the step lines) stays on the run-wide decision: this is about the child's bytes, not the frame around them.

recorded=False runs this call off the record. A call is a step by default: it earns a receipt line, a row in --json, a recording() entry, and its output joins the task's block. Some calls aren't part of the task's story, though — they are how a task knows something (git rev-parse HEAD in a release task). Those return their Result and report nothing: no record, no receipt, no output replayed. The one reader they reach is a profile: while the run keeps a trace, the call is timed as a section named for its command, so the trace shows where a task's time went; without --profile nothing is kept of it.

Everything else still applies, because the call is not unmanaged — only unreported. It runs in ctx.cwd with ctx.env, inside the task's lane, with colour resolved the same way, it is terminated with the rest on a fail-fast, and it still raises unless nofail=True. It also executes under recording(), where a step would be faked — unless the recording carries a scripted answer for it (recording(answers=…)), in which case the script wins: a value read is not the story being recorded, and faking it would corrupt the story that is — the real steps downstream would record whatever a blank answer produced.

pre_record= reviews the record before it is sealed. Some tools speak exit codes that need interpreting — djlint --reformat exits 1 when it changed files, which is success for a formatting gate. The reviewer receives the draft (ResultView) after the work ran: it reads what was captured and may set title and code; the receipt, the record, and the raise-on-nonzero decision all read what the review leaves behind, so the call site writes no nofail=. A reviewer that raises fails the call with its own error — a broken reviewer is a broken gate — and the record keeps what the work honestly produced. Dry-run never reviews (nothing ran, nothing captured), and a recorded=False call has no record to review (a note, not an error).

In-process work is a step now: run() runs commands. Lift a callable instead — @step / step(fn, title=…) builds an item that earns a receipt, and with step("…"): records a block where it stands. A tool wrapper's in-process lane is the one exception: a callable with a view runs in-process, as the wrapper's own spelling of a command.

view is a tool wrapper's structured view of the call (CommandView), so the shown command line can be normalised and role-coloured while execution runs whatever the tool needs. An explicit title still wins; a direct run([...]) is unaffected.

Source code in packages/footman/src/livery/footman/_context.py
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
def run(
    cmd: str | list[str] | Callable[..., Any],
    *args: Any,
    nofail: bool = False,
    recorded: bool = True,
    capture: bool = True,
    input: str | bytes | None = None,
    timeout: float | None = None,
    title: str | None = None,
    pre_record: Callable[[ResultView], None] | None = None,
    env: dict[str, str] | None = None,
    color: str = "auto",
    cwd: str | Path | None = None,
    rel: str | Path | None = None,
    encoding: str | None = "utf-8",
    shell: bool | str = False,
    strict: bool = False,
    clean: bool = False,
    view: CommandView | None = None,
) -> Result:
    """Run a command or a Python callable in the current task's context.

    Subprocess output is decoded as UTF-8 by default; pass `encoding=` for a
    tool that speaks another code page, or `encoding=None` for the locale
    default. Ignored for callables (in-process, no bytes boundary).

    `input=` feeds the child's standard input and closes it — the one lane a
    payload can't take through argv (`uv pip install -r -` reads its
    requirements there). A string, encoded the way the capture is decoded
    (`encoding=`). Bytes go as they are, in a binary lane: no newline
    translation on any platform, and the captured streams are decoded with
    `surrogateescape`, so `stdout.encode(encoding, "surrogateescape")`
    gives a binary tool's bytes back exactly. The *read* side of the process
    boundary is a task parameter marked `stdin`; this is the write side, so a
    task can sit in
    the middle of a pipeline without a shell between it and either
    neighbour. An in-process tool has no standard input to feed — `input=`
    on one is a taught `TypeError`.

    `cwd=` roots this one call somewhere other than the task's directory;
    `rel=` appends a relative suffix to the base in force (`ctx.cwd`, or the
    explicit `cwd=`), so `run("npm run build", rel="web")` is the ergonomic
    spelling of `cwd=ctx.cwd / "web"`. `cwd="unmanaged"` opts this one call
    out instead — the task-level token, per call: a subprocess spawns
    inheriting the live process cwd, an in-process callable runs under it —
    for a call that touches no paths while its task keeps `ctx.cwd`
    everywhere else.

    `color=` decides what this one child emits: `"always"` forces the colour
    variables into its environment, `"never"` writes `NO_COLOR` and *removes*
    any inherited force variables (a tool reading mere presence would honour
    one straight past `NO_COLOR`), and the default `"auto"` follows the run's
    own decision. Explicit beats ambient, so `color="always"` holds under an
    exported `NO_COLOR`. It merges on top of `env=` when both are given, and
    the in-process lane's overlay reads it too — so a per-call colour reaches
    both halves of a tool's colour, its flags and its environment, through
    one door. footman's own chrome (the step lines) stays on the run-wide
    decision: this is about the child's bytes, not the frame around them.

    **`recorded=False` runs this call off the record.** A call is a *step*
    by default: it earns a receipt line, a row in `--json`, a `recording()`
    entry, and its output joins the task's block. Some calls aren't part of
    the task's story, though — they are how a task *knows* something (`git
    rev-parse HEAD` in a release task). Those return their `Result` and
    report nothing: no record, no receipt, no output replayed. The one
    reader they reach is a profile: while the run keeps a trace, the call
    is timed as a section named for its command, so the trace shows where
    a task's time went; without `--profile` nothing is kept of it.

    Everything else still applies, because the call is not unmanaged — only
    unreported. It runs in `ctx.cwd` with `ctx.env`, inside the task's lane,
    with colour resolved the same way, it is terminated with the rest on a
    fail-fast, and it still raises unless `nofail=True`. It also *executes*
    under `recording()`, where a step would be faked — unless the recording
    carries a scripted answer for it (`recording(answers=…)`), in which case
    the script wins: a value read is not the story being recorded, and
    faking it would corrupt the story that is —
    the real steps downstream would record whatever a blank answer produced.

    **`pre_record=` reviews the record before it is sealed.** Some tools
    speak exit codes that need interpreting — `djlint --reformat` exits 1
    when it changed files, which is success for a formatting gate. The
    reviewer receives the draft (`ResultView`) after the work ran: it reads
    what was captured and may set `title` and `code`; the receipt, the
    record, and the raise-on-nonzero decision all read what the review
    leaves behind, so the call site writes no `nofail=`. A reviewer that
    raises fails the call with its own error — a broken reviewer is a
    broken gate — and the record keeps what the work honestly produced.
    Dry-run never reviews (nothing ran, nothing captured), and a
    `recorded=False` call has no record to review (a note, not an error).

    In-process work is a **step** now: `run()` runs commands. Lift a
    callable instead — `@step` / `step(fn, title=…)` builds an item that
    earns a receipt, and `with step("…"):` records a block where it
    stands. A tool wrapper's in-process lane is the one exception: a
    callable with a `view` runs in-process, as the wrapper's own spelling
    of a command.

    `view` is a tool wrapper's structured view of the call (`CommandView`),
    so the shown command line can be normalised and role-coloured while
    execution runs whatever the tool needs. An explicit `title` still wins;
    a direct `run([...])` is unaffected.
    """
    ctx = current()
    if args and not callable(cmd):
        # The subprocess-style spelling this door does not have. The extra
        # arguments only ever reached the *label*, so the child ran without
        # them and said so in green: `run("echo", "hi")` printed nothing and
        # passed, `run("sh", "-c", "exit 1")` ran a bare shell that sat on
        # the caller's terminal. Silence is the one thing that must not
        # happen here, so it is a refusal naming the spelling that works.
        meant = [cmd, *args] if isinstance(cmd, str) else [*cmd, *args]
        spelled = ", ".join(repr(str(token)) for token in meant)
        raise TypeError(
            f"run() takes one command — a string, or a list of tokens — and "
            f"the {len(args)} after it would be dropped rather than passed "
            f"to it. Put them in the list: run([{spelled}])"
        )
    if color not in ("auto", "never", "always"):
        raise ValueError(
            f"run(color={color!r}) expects one of auto|never|always — "
            f"auto follows the run's own decision"
        )
    if color != "auto":
        # The per-call twin of the run boundary's publish: the same tri-state
        # applied to this one child's environment — a private dict, no process
        # global, so it is thread-safe by construction. Off means REMOVING the
        # inherited force variables, never writing "0": some tools honour mere
        # presence straight past NO_COLOR.
        painted_env = dict(env) if env is not None else dict(ctx.env)
        for key in _COLOR_VARS:
            painted_env.pop(key, None)
        painted_env.update(color_env(color == "always"))
        env = painted_env
    if (strict or clean) and not shell:
        # strict/clean harden a *shell* run — they mean nothing shell-free, and a
        # silent no-op would be exactly the surprise footman avoids elsewhere.
        which = "strict" if strict else "clean"
        raise ValueError(
            f"run({which}=True) only applies with a shell — it hardens a shell "
            f"run. Pass shell=True (or a shell name), or drop {which}."
        )
    if callable(cmd) and view is None:
        raise TypeError(
            "run() runs commands; in-process work is a step. Lift the "
            "callable — @step on a def, step(fn, title='…') around one you "
            "didn't write, or `with step('…'):` over inline code — and it "
            "earns a real receipt."
        )
    if input is not None and callable(cmd):
        # Reached only through toolroom's in-process lane: a
        # subprocess has a stdin to feed, a Python call does not.
        raise TypeError(
            "run(input=…) feeds a subprocess's standard input, and an "
            "in-process tool has none — spawn it (in_process=False) to "
            "feed it, or pass the value as an argument"
        )
    out = sys.stdout
    paint = _colored(ctx)
    if view is not None and title is None:
        # `label` (recorded as .command, and the step-line receipt) is always
        # the normalised form, so a recording() assertion never depends on
        # --verbose. Only the live "about to / now running" line switches to
        # the exact spelling under --verbose; .raw always carries it.
        label = view.text(exact=False)
        raw = view.text(exact=True)
        # A bridged call arrives already rendered to strings, so no `Secret`
        # survives the crossing for `_shown` to find — the tool library owns
        # that half of the redaction.
        show_label, show_title = label, None
        shown = view.painted(color=paint, exact=ctx.verbose)
        shown_plain = view.text(exact=ctx.verbose)
        # The bridge already separated the argv; keep it for `to_argv()`.
        tokens = tuple(view.exact)
    else:
        label = title or _label(cmd, args)
        raw = _exact(cmd, args)
        show_label, show_title = _shown(cmd, args, title)
        shown = _dim(show_label, paint)
        shown_plain = show_label
        # A list `run()` has its tokens apart; a command *string* does not,
        # and splitting one back is platform-dependent guesswork — `to_argv()`
        # teaches that rather than guessing.
        tokens = (
            () if callable(cmd) or isinstance(cmd, str) else tuple(argv_tokens(cmd))
        )

    # A scripted answer is looked up before the recording branch decides,
    # because an explicit match wins even for an off-record call (below).
    # The lookup itself may raise: an exception value, or a sequence run dry.
    scripted = _scripted_answer(ctx, label) if ctx.dry_run else None
    if ctx.dry_run and (recorded or scripted is not None):
        # Record the step even when not executing: `dry_run` + `quiet` is the
        # silent-capture mode `footman.testing` builds on. The recorded label
        # is normalised; only the shown line colours or (under -v) goes exact.
        #
        # A non-step call runs anyway. It is not the story being recorded — it
        # is how the task learns something — and faking it would corrupt the
        # story that *is*: the real steps downstream would go on to record
        # whatever a blank answer produced (`git tag ` for a missing sha).
        # Unless the test scripted that very answer: a value read the table
        # names is intercepted, off the record or not — the author declaring
        # the world beats honest execution — and only unmatched reads run.
        addr = _child_address(ctx, _addr_leaf(show_title, show_label))
        # What the call *would* have seen — the same choice the live lane
        # makes below — kept on the record so a recording can assert on it.
        would_env = dict(env) if env is not None else dict(ctx.env)
        try:
            would_cwd = _target_cwd(ctx, cwd, rel)
        except ValueError:
            would_cwd = None  # the live lane refuses it; a rehearsal records
        if scripted is None:
            result = Result(
                0,
                command=label,
                raw=raw,
                shown=show_label,
                address=addr,
                tokens=tokens,
                env=would_env,
                cwd=would_cwd,
            )
            ctx.steps.append(result)
            if not ctx.quiet:
                out.write(f"$ {shown if paint else shown_plain}\n")
            return result
        code, out_s, err_s = scripted
        # A scripted answer is a draft like a live one: reviewers see it —
        # an adjudicator is tested *against* scripted exits — and a
        # non-zero takes the real failing lane. The audit says so.
        audit: tuple[AuditEntry, ...] = (_audit_entry("body", show_label, code),)
        if pre_record is not None and recorded:
            code, label, show_label, audit = _reviewed(
                ctx,
                pre_record,
                cmd,
                args,
                label,
                show_label,
                code,
                out_s,
                err_s,
                0.0,
                raw,
                tokens,
                addr,
                audit,
                False,
                None,
            )
        result = Result(
            code,
            command=label,
            stdout=out_s,
            stderr=err_s,
            raw=raw,
            shown=show_label,
            address=addr,
            audit=audit,
            tokens=tokens,
            env=would_env,
            cwd=would_cwd,
        )
        if recorded:
            ctx.steps.append(result)
            if not ctx.quiet:
                out.write(f"$ {shown if paint else shown_plain}\n")
        if code != 0 and not nofail:
            raise RunFailed(result)
        return result

    if title is not None and not recorded:
        # Not an error: `.opts()` merges along a chain, so a shared tool may
        # carry a title from where it was configured while a call site adds
        # `recorded=False` — neither author wrote the contradiction. Say it once.
        from livery.footman import _globals as _pg_note

        _pg_note._note(
            "recorded-title",
            f"title= is ignored on a recorded=False call ({show_label}): there is "
            f"no receipt to label.",
        )

    if pre_record is not None and not recorded:
        # Same shape as the title note: `.opts()` merges along a chain, so a
        # shared tool may carry a reviewer while one call site goes off the
        # record — neither author wrote the contradiction. Say it once.
        from livery.footman import _globals as _pg_note2

        _pg_note2._note(
            "pre-record-recorded",
            f"pre_record is ignored on a recorded=False call ({show_label}): "
            f"there is no record to review.",
        )

    show = recorded and not ctx.quiet and (ctx.verbose or not capture)
    # `ctx.tty` means "this output dresses for a terminal" (colour, marks);
    # liveness is `sink is None`. A captured block styles for the terminal
    # it will replay onto, but in-place rewrites and the announce line stay
    # live-only: control bytes must never land in a capture buffer.
    live = ctx.sink is None
    if show:
        # The arrow announces what is *running now* — worth a line only
        # while output is live (a TTY rewrites it in place; a streamed CI
        # log may wait minutes under it). A captured block flushes when
        # the task is already done, where "starting X" directly above
        # "finished X" says nothing — the completion line carries it all.
        if ctx.tty and live:
            out.write(f"→ {_name_col(ctx)}{shown}")
            out.flush()
        elif live:
            out.write(f"→ {_name_col(ctx)}{shown_plain}\n")
            out.flush()

    start = time.perf_counter()
    # Bound before the branch: the in-process path never spawns, so it keeps
    # this call's own (refused below if given), while the subprocess path
    # narrows it to whatever the enclosing task has left.
    spawn_timeout = timeout
    if callable(cmd):
        if timeout is not None:
            # A Python callable cannot be interrupted safely — there is no
            # process to signal and no safe way to unwind another thread — so
            # a bound footman cannot honour is refused rather than ignored.
            # toolroom demotes an in-process *tool* to its subprocess
            # twin instead, exactly as it does for a foreign cwd.
            raise ValueError(
                "run(timeout=…) needs a process to bound, and this call runs "
                "in-process. Spawn it (a list/str command, or "
                ".opts(in_process=False) on a tool), or drop the timeout."
            )
        code, out_s, err_s = _run_callable(
            cmd, args, capture=capture, env=env, cwd=_target_cwd(ctx, cwd, rel)
        )
        timed_out = False
    else:
        argv: list[str] | str
        shell_kind = ""
        if shell:
            # An explicit shell: run the whole string through the resolved
            # interpreter — `[bash, -c, "<cmd>"]` — so pipes/redirects/globs
            # work. A list is the shell-free form; it can't be a shell script.
            if not isinstance(cmd, str):
                raise ValueError(
                    "run(shell=…) runs a command *string* through a shell; pass a "
                    "str, not a list (a list is the shell-free form)."
                )
            exe, run_flag = _resolve_shell(shell, ctx.shell_default or "posix")
            shell_kind = _shell_kind_of(exe)
            clean_flags, script = _shell_prep(
                shell_kind, cmd, strict=strict, clean=clean
            )
            argv = [exe, *clean_flags, run_flag, script]
        elif isinstance(cmd, str):
            if (op := _shell_operator(cmd)) is not None:
                raise ValueError(
                    f"run({cmd!r}): {op!r} is a shell operator, but run() does not "
                    f"use a shell, so it would be passed as a literal argument (the "
                    f"pipeline/redirect would silently not happen). Ask for a shell "
                    f"— run(..., shell=True) or shell='bash' — split into separate "
                    f"run() steps, or pass a list to use {op!r} as a literal argument."
                )
            # POSIX shells split on shlex rules; Windows command lines are a
            # single string (CreateProcess) and shlex would mangle backslash
            # paths — hand the string straight to subprocess there.
            argv = cmd if sys.platform == "win32" else shlex.split(cmd)
        else:
            # Tokens as given, with a bare container refused rather than
            # stringified into the one token `"['a', 'b']"` — `*cmd` and
            # `cmd.posix()` are the two meant spellings.
            argv = argv_tokens(cmd)
        # `env=` is the child's environment, exactly as `subprocess` means it —
        # what you pass is what it gets. Otherwise the task's own, which
        # already carries the run-wide colour decision published at the run
        # boundary (`color_environment`) and anything the body has set or
        # deleted. To add rather than replace, say so: `{**os.environ, …}` —
        # inside a task `os.environ` *is* this environment, so the copy is
        # exact rather than approximate.
        run_env = dict(env) if env is not None else dict(ctx.env)
        # A clean POSIX shell means no startup files: `--norc`/`--noprofile`
        # cover interactive/login rc, but bash/sh also source $BASH_ENV/$ENV for
        # a non-interactive `-c`, so drop those from the child env too.
        if clean and shell_kind in ("bash", "sh", "zsh"):
            run_env = {k: v for k, v in run_env.items() if k not in ("BASH_ENV", "ENV")}
        # `unmanaged` spawns with cwd=None (inherit the live process cwd),
        # task-level or per-call; a per-call cwd=/rel= override wins — see
        # `_target_cwd`.
        cwd_path = _target_cwd(ctx, cwd, rel)
        # The enclosing task's deadline bounds this spawn too, whichever is
        # tighter. A task that says `timeout=5` means the whole task, so a
        # `run()` with no bound of its own inherits what is left, and one
        # with a longer bound of its own cannot outlive the task. The
        # subprocess sees only a duration — the task's instant is converted
        # here, at the last moment, so time spent queueing is not charged
        # twice.
        if (left := ctx.time_left()) is not None:
            spawn_timeout = left if timeout is None else min(timeout, left)
        code, out_s, err_s, timed_out = _run_subprocess(
            argv,
            run_env,
            cwd_path,
            capture,
            encoding,
            input=input,
            timeout=spawn_timeout,
            killable=not ctx.atomic,
            # An interactive task owns the real terminal: keep its child in
            # footman's group so it keeps its controlling tty (and its Ctrl-C).
            isolate=not ctx.atomic and not ctx.interactive,
            # Tag the child with its task's policy: a fail-fast failure elsewhere
            # reaps this tree only if the task is fail-fast, not keep-going.
            keep_going=ctx.keep_going,
            # A captured child writes to pipes, so it needs no console of its
            # own; an uncaptured or interactive one is reaching for the real
            # terminal on purpose.
            no_window=capture and not ctx.interactive,
        )
    duration = time.perf_counter() - start
    if timed_out:
        # 124 is the shell convention for "killed by a timeout", so a code
        # travelling out through --json or a branded CLI reads as the thing it
        # is rather than a sentinel of footman's own invention. A Result *is*
        # its exit code, so this is chosen here, not assigned afterwards.
        code = 124
    # The address label is the stable identity — a title names the record,
    # the address names the node (`_addr_leaf` for the naming rule). Minted
    # from the *shown* label: an address is a name, printed wherever the
    # record is, and a name has no business carrying a secret.
    addr = _child_address(ctx, _addr_leaf(show_title, show_label))
    # The audit: the verdict's provenance. The body entry is always present
    # and carries what the work itself produced; review entries follow. The
    # body actor names the work, which is the command line — so it is the
    # shown one, for the same reason the address is: a name is printed
    # wherever the record travels.
    audit = (_audit_entry("body", show_label, code),)
    if pre_record is not None and recorded:
        code, label, show_label, audit = _reviewed(
            ctx,
            pre_record,
            cmd,
            args,
            label,
            show_label,
            code,
            out_s,
            err_s,
            duration,
            raw,
            tokens,
            addr,
            audit,
            timed_out,
            start,
        )
    result = Result(
        code,
        command=label,
        stdout=out_s,
        stderr=err_s,
        duration=duration,
        raw=raw,
        shown=show_label,
        timed_out=timed_out,
        address=addr,
        audit=audit,
        tokens=tokens,
        started=start,
    )
    if recorded:
        ctx.steps.append(result)  # what --json, the report and recording() read
    else:
        # Off the record, by contract: no receipt, no row, no recording()
        # entry. A profile is the one reader it may reach, and only while
        # the run keeps a trace: a value read still spent the time, and a
        # trace that hides it shows a blank task where the time went.
        from livery.footman import profile

        if profile.keeping():
            ctx.sections.append(Section(show_label, start, duration))

    # Task grain at normal verbosity: a step's receipt shows under
    # --verbose (and for uncaptured, live steps, whose output needs its
    # label) — and ALWAYS when it failed. Green is collapsible; failure is
    # never hidden.
    if (
        recorded
        and not ctx.quiet
        and not ctx.machine_read
        and (ctx.verbose or not capture or code != 0)
    ):
        ok = code == 0
        prefix = "\r\033[K" if ctx.tty and live else ""
        out.write(f"{prefix}{_step_line(ctx, ok, show_label, duration)}")
        # Join the two streams only to *display* them (stdout then stderr);
        # nothing merged is stored — the Result keeps them apart.
        combined = out_s + err_s
        if capture and combined and (not ok or ctx.verbose):
            out.write(combined if combined.endswith("\n") else combined + "\n")
        if not ok and len(result.audit) > 1:
            # The verdict's story, when anyone touched it: who acted, what
            # they set — the audit, one dim line under the failure.
            trail = " → ".join(
                f"{e.moment} {e.actor}" + (f" {e.code}" if e.code is not None else "")
                for e in result.audit
            )
            out.write(_dim(f"     audit: {trail}", _colored(ctx)) + "\n")
        out.flush()

    if code != 0 and not nofail:
        if result.timed_out:
            # The bound that actually applied: this call's own, or what the
            # enclosing `@task(timeout=…)` had left when the spawn started.
            # Reporting the call's own would print `0s` for a task-imposed
            # deadline, which reads as a bug in the timeout rather than a
            # deadline being enforced.
            raise RunTimeout(result, effective_timeout(timeout, ctx))
        raise RunFailed(result)
    return result

livery.footman.Result

Bases: int

The outcome of one run() call — and the value run() returns.

A Result is the exit code: it subclasses int, so code = run(...), if run(...), and run(...) == 0 all keep working. It also carries the captured output, split by stream, and the command that produced it — so run("git rev-parse HEAD").stdout.strip() reads the hash without the stderr noise glued on. stdout/stderr are separated for both subprocess and in-process runs; a streamed run (capture=False) leaves them empty.

Methods:

Name Description
__new__
to_argv

What this call ran, as the tokens it was spawned from.

__setattr__

Attributes:

Name Type Description
command str

The command line that ran, normalised for reading — options in

shown str

command as it is safe to print — every argument that arrived

stdout str

Captured standard output; empty when the step streamed instead.

stderr str

Captured standard error; empty when the step streamed instead.

duration float

Wall-clock seconds the step took.

started float | None

When the step began, on the run's monotonic clock — the same clock

raw str

The exact command line executed, shell-quoted — the bytes footman

timed_out bool

Whether timeout= expired and footman killed the tree. The code

address str

The record's tree-derived name: the requester's path, this

audit tuple[AuditEntry, ...]

The verdict's provenance: every lifecycle moment that acted on

env dict[str, str] | None

The environment this call would have run in — the task's own, or

cwd Path | None

The directory this call would have run in — the task's resolved

code int

The exit code (0 is success) — the same value the Result itself is.

ok bool

Whether the command succeeded (exit code 0).

output str

stdout then stderr, concatenated — a convenience for "show me

failed_at str | None

The lifecycle moment the failure came from, None on success — a

work_code int | None

The code the record carried when the failing moment began — a

command property

command: str

The command line that ran, normalised for reading — options in separated form, values shell-quoted. What recording() asserts against, and what a dependent reads back.

shown property

shown: str

command as it is safe to print — every argument that arrived as a Secret replaced by ***, everything else identical.

Equal to command unless the call carried a secret, so a record is the same string on both sides in the ordinary case. Every surface footman shows a command line on reads this one: the step line, the --verbose announce, --json, a profile span, the message a RunFailed carries. The record keeps the real value, because a dependent, recording(), and the caller who passed it all read command and none of them are a display.

stdout property

stdout: str

Captured standard output; empty when the step streamed instead.

stderr property

stderr: str

Captured standard error; empty when the step streamed instead.

duration property

duration: float

Wall-clock seconds the step took.

started property

started: float | None

When the step began, on the run's monotonic clock — the same clock a task row's started reads, so a step places inside its task's span. None for a record that never ran (a dry-run's rehearsal).

raw property

raw: str

The exact command line executed, shell-quoted — the bytes footman handed the tool, which may spell an option --flag=value where command shows --flag value. What --verbose prints. Equal to command when there is nothing to normalise.

timed_out property

timed_out: bool

Whether timeout= expired and footman killed the tree. The code is 124 — the shell convention — and stdout/stderr hold whatever the command managed to say first, which on a hang is the only clue there is.

address property

address: str

The record's tree-derived name: the requester's path, this record's label, and an ordinal once a label repeats among siblings — counted in request order as written, so it is deterministic across runs and hosts. Empty outside a managed context.

audit property

audit: tuple[AuditEntry, ...]

The verdict's provenance: every lifecycle moment that acted on it, in execution order — the body entry with what the work itself produced, a review entry per pre_record reviewer. Empty for a record that executed nothing (a dry-run plan line).

env property

env: dict[str, str] | None

The environment this call would have run in — the task's own, or the env= handed to the call — kept on a recorded step only, so a recording() can assert what a command would have seen (assert "UV_TOOL_DIR" not in steps[0].env). None on a record that ran: a live environment can hold secrets, and a record travels into --json and the report.

cwd property

cwd: Path | None

The directory this call would have run in — the task's resolved one, or the call's cwd=/rel= — kept on a recorded step only, like env. None on a record that ran, and for a call that opted out with cwd="unmanaged".

code property

code: int

The exit code (0 is success) — the same value the Result itself is.

ok property

ok: bool

Whether the command succeeded (exit code 0).

output property

output: str

stdout then stderr, concatenated — a convenience for "show me everything". NOT interleaved in real time (each stream is captured whole); when the order across the two streams matters, read stdout and stderr separately.

failed_at property

failed_at: str | None

The lifecycle moment the failure came from, None on success — a derived reading of the audit: the last moment that wrote the verdict. A red tool reviewed green reads None (the record succeeded); a green tool failed by its reviewer reads "review".

work_code property

work_code: int | None

The code the record carried when the failing moment began — a derived reading of the audit, None on success or when nothing came before the failure. A green build failed in review keeps its 0 here, visible rather than inferred.

__new__

__new__(code: int, *, command: str = '', stdout: str = '', stderr: str = '', duration: float = 0.0, raw: str = '', shown: str = '', timed_out: bool = False, address: str = '', audit: tuple[AuditEntry, ...] = (), tokens: tuple[str, ...] = (), started: float | None = None, env: dict[str, str] | None = None, cwd: Path | None = None) -> Result
Source code in packages/footman/src/livery/footman/_context.py
def __new__(
    cls,
    code: int,
    *,
    command: str = "",
    stdout: str = "",
    stderr: str = "",
    duration: float = 0.0,
    raw: str = "",
    shown: str = "",
    timed_out: bool = False,
    address: str = "",
    audit: tuple[AuditEntry, ...] = (),
    tokens: tuple[str, ...] = (),
    started: float | None = None,
    env: dict[str, str] | None = None,
    cwd: Path | None = None,
) -> Result:
    self = super().__new__(cls, code)
    object.__setattr__(self, "_env", env)
    object.__setattr__(self, "_cwd", cwd)
    object.__setattr__(self, "_timed_out", timed_out)
    object.__setattr__(self, "_address", address)
    object.__setattr__(self, "_started", started)
    object.__setattr__(self, "_command", command)
    object.__setattr__(self, "_stdout", stdout)
    object.__setattr__(self, "_stderr", stderr)
    object.__setattr__(self, "_duration", duration)
    object.__setattr__(self, "_raw", raw or command)
    # What every surface that *prints* this call reads, so the record can
    # keep the value the caller passed while nothing shows it. Falls back
    # to the command itself, which is what it is for a call with no
    # `Secret` in it — the overwhelming majority.
    object.__setattr__(self, "_shown", shown or command)
    object.__setattr__(self, "_audit", audit)
    # The argv as separate tokens, kept so `to_argv()` can re-quote for a
    # shell the caller names. `_raw` cannot stand in: it is quoted for the
    # local platform, and `shlex` cannot reliably take a `list2cmdline`
    # string apart again.
    object.__setattr__(self, "_tokens", tokens)
    return self

to_argv

to_argv() -> Argv

What this call ran, as the tokens it was spawned from.

.raw shows the command line quoted for the machine footman is standing on, which is right for a --verbose line and wrong the moment the string is sent somewhere else. This returns the same command as an Argv — raw tokens, re-quotable for whichever shell will actually parse them:

r = git.commit(m="ship 1.2.0")
r.to_argv()          # ["git", "commit", "-m", "ship 1.2.0"]
r.to_argv().posix()  # "git commit -m 'ship 1.2.0'"

Named apart from toolroom's .argv builders on purpose: this one describes a call that has already run, so git.push().argv(…) — meaning to build a command line — is an AttributeError rather than a push that quietly happened. For the same reason the two can differ by one token: what ran may carry a forced-colour switch (git's -c color.ui=always) that a line built to be sent elsewhere does not.

Source code in packages/footman/src/livery/footman/_context.py
def to_argv(self) -> Argv:
    """What this call ran, as the tokens it was spawned from.

    `.raw` shows the command line quoted for the machine footman is
    standing on, which is right for a `--verbose` line and wrong the
    moment the string is sent somewhere else. This returns the same
    command as an `Argv` — raw tokens, re-quotable for whichever shell
    will actually parse them:

        r = git.commit(m="ship 1.2.0")
        r.to_argv()          # ["git", "commit", "-m", "ship 1.2.0"]
        r.to_argv().posix()  # "git commit -m 'ship 1.2.0'"

    Named apart from toolroom's `.argv` builders on purpose: this one describes
    a call that has **already run**, so `git.push().argv(…)` — meaning to
    *build* a command line — is an `AttributeError` rather than a push
    that quietly happened. For the same reason the two can differ by one
    token: what ran may carry a forced-colour switch (git's
    `-c color.ui=always`) that a line built to be sent elsewhere does not.
    """
    if not self._tokens:
        raise ValueError(
            f"to_argv(): no argv was recorded for `{self._shown}`. Only a "
            f"spawned command has separable tokens — an in-process call, a "
            f"Python callable, or a `run()` given a command *string* never "
            f"had them apart. Pass a list (`run(['git', 'push'])`) or use "
            f"a toolroom handle, whose calls always record their argv."
        )
    return Argv(self._tokens)

__setattr__

__setattr__(name: str, value: Any) -> None
Source code in packages/footman/src/livery/footman/_context.py
def __setattr__(self, name: str, value: Any) -> None:
    raise AttributeError(
        f"Result.{name} is sealed — a committed record is immutable. "
        f"Amend verdicts in the review window (pre_record), or veto "
        f"with fail(reason, code) from an observer."
    )

livery.footman.ResultView

ResultView(*, title: str, code: int, stdout: str, stderr: str, duration: float, raw: str, command: str, returned: Any = None)

A step's record, in the review window: the draft a pre_record reviewer receives after the work ran and before the record is sealed.

The verdict is still open — title and code are plain writable attributes, and the raise-on-nonzero decision reads the code the review leaves behind, so "fail by this tool's definition of failure" needs no nofail= at the call site. Everything the run captured is read-only: review sees what the run kept, never edits it — an uncaptured (capture=False) call reviews the code alone. ok derives from code, so the two can never disagree.

Methods:

Name Description
set_returned

Rewrite the reported value — the summary line and the --json

Attributes:

Name Type Description
__slots__
title str

The receipt's label. Starts as the shown command (or the call's

code int

The verdict. What the review leaves here is the step's exit code —

ok bool

Whether the code, as it stands, is success — derives from code.

stdout str

Captured standard output; empty when the call streamed instead.

stderr str

Captured standard error; empty when the call streamed instead.

output str

stdout then stderr, concatenated — the same convenience the

duration float

Wall-clock seconds the work took — machinery-owned, read-only.

raw str

The exact command line executed — the review can read what really

command str

The normalised command line as it stood before review.

returned Any

What the body returned, when this draft is a task's row — None by

Source code in packages/footman/src/livery/footman/_context.py
def __init__(
    self,
    *,
    title: str,
    code: int,
    stdout: str,
    stderr: str,
    duration: float,
    raw: str,
    command: str,
    returned: Any = None,
) -> None:
    self._title = title
    self._code = code
    self._stdout = stdout
    self._stderr = stderr
    self._duration = duration
    self._raw = raw
    self._command = command
    self._returned = returned
    self._touched: set[str] = set()

__slots__ class-attribute instance-attribute

__slots__ = ('_code', '_command', '_duration', '_raw', '_returned', '_stderr', '_stdout', '_title', '_touched')

title property writable

title: str

The receipt's label. Starts as the shown command (or the call's title=); what the review leaves here is what the report shows.

code property writable

code: int

The verdict. What the review leaves here is the step's exit code — the raise decision and the receipt both read it. The audit records whether a reviewer wrote it or left it alone.

ok property

ok: bool

Whether the code, as it stands, is success — derives from code.

stdout property

stdout: str

Captured standard output; empty when the call streamed instead.

stderr property

stderr: str

Captured standard error; empty when the call streamed instead.

output property

output: str

stdout then stderr, concatenated — the same convenience the sealed Result offers.

duration property

duration: float

Wall-clock seconds the work took — machinery-owned, read-only.

raw property

raw: str

The exact command line executed — the review can read what really ran while retitling what the report shows.

command property

command: str

The normalised command line as it stood before review.

returned property

returned: Any

What the body returned, when this draft is a task's row — None by circumstance elsewhere (a subprocess step has no return value).

set_returned

set_returned(value: Any) -> None

Rewrite the reported value — the summary line and the --json envelope — never what a dependent or a body caller received: that was snapshotted the moment the body handed it over. The review window is this write's home: reviewed, attributed in the audit, before the record seals.

Source code in packages/footman/src/livery/footman/_context.py
def set_returned(self, value: Any) -> None:
    """Rewrite the *reported* value — the summary line and the `--json`
    envelope — never what a dependent or a body caller received: that was
    snapshotted the moment the body handed it over. The review window is
    this write's home: reviewed, attributed in the audit, before the
    record seals."""
    self._returned = value
    self._touched.add("returned")

livery.footman.AuditEntry

Bases: NamedTuple

One entry of a record's audit: a lifecycle moment that acted on the verdict — who acted, and what they set.

The body entry is always present and carries what the work itself produced; a review entry names the reviewer, with code None when it was involved without writing the verdict (a reviewer that only set the title). Entries are in execution order.

Attributes:

Name Type Description
moment str

Where in the record's lifecycle this happened: "body" for the work

actor str

Who acted: the command line for the body, the hook's name for a

code int | None

The code this moment left, or None for involvement without a verdict

moment instance-attribute

moment: str

Where in the record's lifecycle this happened: "body" for the work itself, "review" for a pre_record reviewer.

actor instance-attribute

actor: str

Who acted: the command line for the body, the hook's name for a reviewer.

code instance-attribute

code: int | None

The code this moment left, or None for involvement without a verdict write.

livery.footman.Argv

Bases: list[str]

A command line built but not run — what Result.to_argv() hands back (and what a builder like toolroom's git.push.argv(force=True) makes).

An ordinary list[str] everywhere in Python: it indexes, slices, iterates, compares and prints exactly like the list it is, and run(cmd) spawns it as-is. Always the raw tokens — the one shape of a command with no shell in it. Passing the tokens on is plain Python: run(cmd) runs them, a wrapper takes them splatted (uv.run("--", *cmd)), and stdlib helpers take the list directly (shlex.join(cmd)).

The moment the line is about to cross into a shell, name that shell:

  • .posix() — one string, shlex-quoted for sh/bash/zsh.
  • .windows() — one string, quoted the way CreateProcess parses.

Naming it is the caller's job because footman cannot know it: the same handle can target different hosts across calls, the OS does not determine the shell, and the payload may reach no shell at all. The quoting is the destination's, never this machine's — a line built on Windows for a Linux box still comes back POSIX-quoted (which is why neither method is the local-platform _shell_quote).

Lives here beside Result because run() accepts one and Result.to_argv() returns one. toolroom carries its own twin of this class on purpose — the seam between the packages speaks plain list[str], so neither ever imports the other's.

Methods:

Name Description
posix

This command as one string, quoted for a POSIX shell.

windows

This command as one string, quoted the way CreateProcess parses.

Attributes:

Name Type Description
__slots__

__slots__ class-attribute instance-attribute

__slots__ = ()

posix

posix() -> str

This command as one string, quoted for a POSIX shell.

What an ssh payload wants: ssh joins its remaining arguments with spaces and hands the remote shell one string to re-split, so the only argument boundaries that survive are the ones quoted into it.

cmd = git.commit.argv(m="ship 1.2.0")
ssh("deploy@host", cmd.posix())

Quoting a built line that already carries a .posix() payload quotes it once more, which is exactly what each further hop needs.

Source code in packages/footman/src/livery/footman/_context.py
def posix(self) -> str:
    """This command as one string, quoted for a POSIX shell.

    What an `ssh` payload wants: ssh joins its remaining arguments with
    spaces and hands the remote shell **one string** to re-split, so the
    only argument boundaries that survive are the ones quoted into it.

        cmd = git.commit.argv(m="ship 1.2.0")
        ssh("deploy@host", cmd.posix())

    Quoting a built line that already carries a `.posix()` payload quotes
    it once more, which is exactly what each further hop needs.
    """
    return shlex.join(self)

windows

windows() -> str

This command as one string, quoted the way CreateProcess parses.

The Windows counterpart of .posix(), for a payload headed to a Windows box — subprocess.list2cmdline quoting, which cmd and PowerShell both read. Chosen by the caller, never sniffed from the machine footman happens to be standing on.

Source code in packages/footman/src/livery/footman/_context.py
def windows(self) -> str:
    """This command as one string, quoted the way `CreateProcess` parses.

    The Windows counterpart of `.posix()`, for a payload headed to a
    Windows box — `subprocess.list2cmdline` quoting, which `cmd` and
    PowerShell both read. Chosen by the caller, never sniffed from the
    machine footman happens to be standing on.
    """
    return subprocess.list2cmdline(self)

livery.footman.RunFailed

RunFailed(result: Result)

Bases: Exception

A run() command exited non-zero (and nofail was not set).

The message names the command the way every other surface does — with any Secret argument redacted — because a failure line is a display, and the one place it most reliably lands is somebody's CI log. The record it carries, .result, is untouched: .result.command is the real command line, for the handler that reads rather than prints.

Attributes:

Name Type Description
result
Source code in packages/footman/src/livery/footman/_context.py
def __init__(self, result: Result) -> None:
    self.result = result
    super().__init__(f"`{result.shown}` exited with code {result.code}")

result instance-attribute

result = result

livery.footman.RunTimeout

RunTimeout(result: Result, timeout: float)

Bases: RunFailed

A run(timeout=…) expired and the process tree was killed.

A RunFailed, so every except RunFailed keeps catching it; catch this to tell a hang from an ordinary non-zero exit — the distinction a version or help probe branches on.

Attributes:

Name Type Description
result
timeout
Source code in packages/footman/src/livery/footman/_context.py
def __init__(self, result: Result, timeout: float) -> None:
    self.result = result
    self.timeout = timeout
    Exception.__init__(
        self, f"`{result.shown}` timed out after {timeout:g}s and was killed"
    )

result instance-attribute

result = result

timeout instance-attribute

timeout = timeout

livery.footman.parallel

parallel(*, keep_going: bool = False) -> Fanout
parallel(*calls: WorkItem[Any] | StepFn[..., Any] | TaskFn[..., Any] | Group, keep_going: bool = False) -> list[Result]
parallel(*calls: WorkItem[Any] | StepFn[..., Any] | TaskFn[..., Any] | Group, keep_going: bool = False) -> Fanout | list[Result]

Run tasks and steps concurrently; wait; fail if any fail.

Each one runs in a child of the current context with its own output buffer, flushed atomically on completion so concurrent output never interleaves. Pass task functions directly (parallel(lint, typecheck)) and built step items for everything else — parallel(convert(images)), or parallel(step(fn)(args)) for a function you didn't write. A bare zero-argument maker is welcome too: parallel(clean) builds and runs clean().

Nothing anonymous runs: footman only schedules, records, and safely cancels work it owns, and a bare callable is a stranger — no name for the report, no place in the plan, no way to stop it cleanly. The lift is one word, and it buys the step a receipt.

With no arguments it is a block instead, and the calls inside it are the fan-out — written as ordinary calls, with their values afterwards:

with parallel() as p:
    build("web")
    p(step(shutil.rmtree)(tmp, ignore_errors=True))
web, cleaned = p.results

Inside the block a task call is queued, so it has no value there (using one is a taught error); a built step item joins through p(item); everything runs when the block ends, under the same rules — sharing, hooks, -s/-j.

Source code in packages/footman/src/livery/footman/_context.py
def parallel(
    *calls: _step.WorkItem[Any]
    | _step.StepFn[..., Any]
    | _registry_t.TaskFn[..., Any]
    | _registry_t.Group,
    keep_going: bool = False,
) -> Fanout | list[Result]:
    """Run tasks and steps concurrently; wait; fail if any fail.

    Each one runs in a child of the current context with its own output
    buffer, flushed atomically on completion so concurrent output never
    interleaves. Pass task functions directly (`parallel(lint, typecheck)`)
    and built step items for everything else — `parallel(convert(images))`,
    or `parallel(step(fn)(args))` for a function you didn't write. A bare
    zero-argument maker is welcome too: `parallel(clean)` builds and runs
    `clean()`.

    Nothing anonymous runs: footman only schedules, records, and safely
    cancels work it owns, and a bare callable is a stranger — no name for
    the report, no place in the plan, no way to stop it cleanly. The lift
    is one word, and it buys the step a receipt.

    With no arguments it is a **block** instead, and the calls inside it are
    the fan-out — written as ordinary calls, with their values afterwards:

        with parallel() as p:
            build("web")
            p(step(shutil.rmtree)(tmp, ignore_errors=True))
        web, cleaned = p.results

    Inside the block a task call is *queued*, so it has no value there (using
    one is a taught error); a built step item joins through `p(item)`;
    everything runs when the block ends, under the same rules — sharing,
    hooks, `-s`/`-j`.
    """
    from livery.footman import _step

    if not calls:
        # Nothing to run: the block form, which is also an empty list of exit
        # codes — so `parallel(*items)` over an empty sequence is unchanged.
        return Fanout(keep_going=keep_going)

    from livery.footman import _registry as _registry

    accepted: list[Callable[[], Any]] = []
    for c in calls:
        if isinstance(c, _step.StepFn):
            # A zero-argument maker is welcome bare: build its item here, so
            # `parallel(covered)` and `parallel(covered())` mean the same.
            c = c()
        if isinstance(c, _step.WorkItem):
            accepted.append(c)
            continue
        if getattr(c, "_footman_pre", None) is not None or isinstance(
            c, _registry.Group
        ):
            accepted.append(c)  # a task, an opted reference, a runnable group
            continue
        label = _call_name(c) if callable(c) else type(c).__name__
        raise TypeError(
            f"parallel() runs tasks and steps — {label!r} is neither. "
            f"footman only schedules, records, and safely cancels work it "
            f"owns, and a bare callable is a stranger. Lift it and it earns "
            f"a receipt too: parallel(step(fn)(…)), or step(fn, "
            f"title='…') to name a lambda."
        )
    return _run_thunks(accepted, keep_going=keep_going)

livery.footman.step

step(target: Callable[P, Generator[None, ResultView, R]], /, *, title: str | None = None) -> StepFn[P, R]
step(target: Callable[P, R], /, *, title: str | None = None) -> StepFn[P, R]
step(target: str) -> _StepBlock
step(target: Any = None, /, *, title: str | None = None) -> Any

One name, three positions: @step on a def, with step("title"): over a block, step(fn, title=…) around a function you didn't write.

Decorator and expression positions are the same expression, so both return the maker — calling it builds the item; nothing runs until something executes it (parallel(), or calling the built item).

Source code in packages/footman/src/livery/footman/_step.py
def step(target: Any = None, /, *, title: str | None = None) -> Any:
    """One name, three positions: `@step` on a def, `with step("title"):`
    over a block, `step(fn, title=…)` around a function you didn't write.

    Decorator and expression positions are the same expression, so both
    return the maker — calling it builds the item; nothing runs until
    something executes it (`parallel()`, or calling the built item).
    """
    if isinstance(target, str):
        if title is not None:
            raise TypeError(
                "step('title') is the block form — pass the title once, "
                "positionally; title= belongs to the decorator/expression "
                "forms (step(fn, title=…))"
            )
        return _StepBlock(target)
    if target is None:
        raise TypeError(
            "step() needs its subject: a function to lift (@step / "
            "step(fn, title=…)) or a title string for the block form "
            "(with step('…'):)"
        )
    if not callable(target):
        raise TypeError(
            f"step() lifts a callable or opens a titled block; got "
            f"{type(target).__name__}"
        )
    opts: dict[str, Any] = {}
    if title is not None:
        opts["title"] = title
    return StepFn(target, opts)

livery.footman.pre_record

pre_record(hook: Callable[[Any], None]) -> Callable[[_F], _F]

Attach a reviewer to a task: @pre_record(fn) stacked on the def.

The reviewer receives the task's record while it is still a draft — after the body concluded, before the record is sealed, observed, or reported. It reads the draft (a ResultView) and may set title and code; the row's verdict follows what the review leaves behind, and the record's audit names the reviewer and what it did.

Reviewers run from the inside out: the hook written closest to the function sees the draft first, and each one above it sees what the previous reviewers left. Stacks above or below @task alike — the decorated function (and a TaskFn when stacked above the lifter) keeps its static type. A reviewer that raises fails the task with its own error: a broken reviewer is a broken gate.

Source code in packages/footman/src/livery/footman/_registry.py
def pre_record(hook: Callable[[Any], None]) -> Callable[[_F], _F]:
    """Attach a reviewer to a task: `@pre_record(fn)` stacked on the `def`.

    The reviewer receives the task's record while it is still a draft — after
    the body concluded, before the record is sealed, observed, or reported.
    It reads the draft (a `ResultView`) and may set `title` and `code`; the
    row's verdict follows what the review leaves behind, and the record's
    audit names the reviewer and what it did.

    Reviewers run from the inside out: the hook written closest to the
    function sees the draft first, and each one above it sees what the
    previous reviewers left. Stacks above or below `@task` alike — the
    decorated function (and a `TaskFn` when stacked above the lifter) keeps
    its static type. A reviewer that raises fails the task with its own
    error: a broken reviewer is a broken gate.
    """

    def decorate(fn: _F) -> _F:
        setattr(fn, _PRE_RECORD, [*getattr(fn, _PRE_RECORD, ()), hook])
        return fn

    return decorate

livery.footman.passthrough

passthrough() -> list[str]

Arguments after -- on the command line, for the running task.

Source code in packages/footman/src/livery/footman/_context.py
def passthrough() -> list[str]:
    """Arguments after `--` on the command line, for the running task."""
    return list(current().passthrough)

livery.footman.inherited

inherited() -> Callable[..., Any]

The task this one shadows in the cascade — footman's super().

A nearer tasks.py overriding a task by name usually wants to extend it, not replace it. Call this inside the overriding task's body to get the task it shadows, then call that like the plain function it is:

# svc/api/tasks.py — the root also defines `check`
@task
def check(fix: bool = False, contracts: bool = True):
    inherited()(fix=fix)          # arguments are forwarded explicitly
    if contracts:
        run("./verify-contracts.sh")

Forwarding is deliberately manual: the two signatures are independent (a leaf usually adds a parameter), so automatic forwarding could only drop arguments silently or fail at run time — where spelling the call out shows you the mismatch as you type it. Being an ordinary call, it also runs to completion before the next statement — and composes with parallel(inherited(), extra) when you want otherwise.

fm --where <task> lists the whole shadow chain; fm --help <task> shows the inherited task's options, so you can read the forwarding call straight off it.

Source code in packages/footman/src/livery/footman/_context.py
def inherited() -> Callable[..., Any]:
    """The task this one shadows in the cascade — footman's `super()`.

    A nearer `tasks.py` overriding a task by name usually wants to *extend*
    it, not replace it. Call this inside the overriding task's body to get
    the task it shadows, then call that like the plain function it is:

    ```python
    # svc/api/tasks.py — the root also defines `check`
    @task
    def check(fix: bool = False, contracts: bool = True):
        inherited()(fix=fix)          # arguments are forwarded explicitly
        if contracts:
            run("./verify-contracts.sh")
    ```

    Forwarding is deliberately manual: the two signatures are independent
    (a leaf usually adds a parameter), so automatic forwarding could only
    drop arguments silently or fail at run time — where spelling the call
    out shows you the mismatch as you type it. Being an ordinary call,
    it also runs to completion
    before the next statement — and composes with `parallel(inherited(),
    extra)` when you want otherwise.

    `fm --where <task>` lists the whole shadow chain; `fm --help <task>`
    shows the inherited task's options, so you can read the forwarding
    call straight off it.
    """
    from livery.footman import _discover

    fn = current().fn
    if fn is None:
        raise RuntimeError(
            "inherited() works inside a running task — footman resolves the "
            "task being shadowed from the one currently running"
        )
    previous = _discover.shadowed(fn)
    if previous is None:
        name = current().task or getattr(fn, "__name__", "this task")
        raise RuntimeError(
            f"{name} does not shadow an inherited task — nothing above it in "
            f"the cascade defines that name (fm --where {name} lists the chain)"
        )

    @functools.wraps(previous)
    def call_inherited(*args: Any, **kwargs: Any) -> Any:
        # Point the context at the task being called, so an `inherited()`
        # inside *it* walks one level further up instead of resolving to
        # itself — a three-deep cascade would otherwise recurse forever.
        from livery.footman import _registry as registry

        ctx = current()
        saved = ctx.fn
        ctx.fn = previous
        try:
            # The shadowed *body*, run inside this task: an override chain, the
            # way `super()` is — not a second task. It shares this task's
            # context, result, and reported duration, and never becomes a unit
            # of the run in its own right.
            return registry.task_body(previous)(*args, **kwargs)
        finally:
            ctx.fn = saved

    return call_inherited

Failing on purpose

livery.footman.fail

fail(reason: str = '', *, code: int = 1) -> NoReturn

Fail the current task with a reason (and exit code, default 1).

The blessed way to stop a task deliberately: fail("no open PR to act on"), or fail("reserved branch", code=3) to pick the exit code too. A function, not a raise, on purpose — a task lives in your repo under your linter, and raise SomeError("a literal") trips flake8-errmsg (EM101) and tryceratops (TRY003) at the call site, every failure. A call trips neither, the same reason sys.exit() and pytest.fail() are functions. return N still spells a bare code; sys.exit(...) still works — fail() is just the footman-native one, with a reason and a code together.

fail() means failure, so code=0 — success — is a contradiction it refuses rather than a corner it interprets: return 0 (or a plain return) spells stopping early with success.

Source code in packages/footman/src/livery/footman/_context.py
def fail(reason: str = "", *, code: int = 1) -> NoReturn:
    """Fail the current task with a *reason* (and exit *code*, default 1).

    The blessed way to stop a task deliberately: `fail("no open PR to act on")`,
    or `fail("reserved branch", code=3)` to pick the exit code too. A *function*,
    not a `raise`, on purpose — a task lives in your repo under your linter, and
    `raise SomeError("a literal")` trips flake8-errmsg (EM101) and tryceratops
    (TRY003) at the call site, every failure. A call trips neither, the same
    reason `sys.exit()` and `pytest.fail()` are functions. `return N` still
    spells a bare code; `sys.exit(...)` still works — `fail()` is just the
    footman-native one, with a reason and a code together.

    `fail()` means failure, so `code=0` — success — is a contradiction it
    refuses rather than a corner it interprets: `return 0` (or a plain
    `return`) spells stopping early with success.
    """
    if code == 0:
        raise ValueError(
            "fail() means failure and exit code 0 is success — return 0 "
            "(or just return) spells stopping early with success"
        )
    raise Failed(reason, code=code)

livery.footman.Failed

Failed(reason: str = '', *, code: int = 1)

Bases: Exception

A task chose to fail — the exception footman.fail() raises.

A deliberate stop with a reason (and optional exit code): the user-facing sibling of RunFailed (which is a command's failure). Carries .reason and .code; footman renders the reason verbatim — no type prefix — in the failure line and the --json error field. Exported so a task can except footman.Failed:, but fail() is the blessed way to raise it.

Attributes:

Name Type Description
reason
code
Source code in packages/footman/src/livery/footman/_context.py
def __init__(self, reason: str = "", *, code: int = 1) -> None:
    self.reason = reason
    self.code = code
    super().__init__(reason)

reason instance-attribute

reason = reason

code instance-attribute

code = code

livery.footman.TimedOut

TimedOut(task: str, timeout: float, *, after: str = 'stopped', body: str = '', at: float = 0.0, not_retried: bool = False)

Bases: Failed

A task's @task(timeout=…) deadline expired.

A Failed, so except footman.Failed: keeps catching it and the reason renders verbatim in the failure line and the --json error field.

Carries .timeout (the declared seconds) and .after — what became of the work: stopped (footman issued a stop before the body returned) or completed (no stop was issued and the body finished on its own, just late). An open set: TaskResult.after_deadline explains which further values are designed and why they are not shipped.

The message never pretends the work did not happen. Where the body completed, it says so and says what the body's own verdict was, then states that the deadline governs — the receipt tells the whole truth while the task still fails on its contract (notes/20260807-timeout-and-retry.md).

Attributes:

Name Type Description
timeout
after
not_retried
Source code in packages/footman/src/livery/footman/_context.py
def __init__(
    self,
    task: str,
    timeout: float,
    *,
    after: str = "stopped",
    body: str = "",
    at: float = 0.0,
    not_retried: bool = False,
) -> None:
    self.timeout = timeout
    self.after = after
    self.not_retried = not_retried
    said = f"{task} exceeded its {timeout:g}s deadline"
    if after == "completed":
        # Report the outcome being discarded rather than presenting this
        # as work that never finished.
        when = f" at {at:g}s" if at else ""
        verdict = f" with {body}" if body else ""
        said += f"; the body completed{when}{verdict} — the deadline governs"
    else:
        said += " and was stopped"
    if not_retried:
        # The diagnosis the author needs is "this body has no
        # checkpoint", and it is only inferable if this reads
        # differently from ordinary retry exhaustion.
        said += " — not retried"
    super().__init__(said, code=124)

timeout instance-attribute

timeout = timeout

after instance-attribute

after = after

not_retried instance-attribute

not_retried = not_retried

Checking the runner

What fm doctor prints is findings: footman's own checks of the runner's directories and scratch, then every doctor an installed package registers under the footman.doctors entry-point group. A doctor returns these; --fix runs each one's repair and checks again.

livery.footman.Finding

Bases: NamedTuple

One answer of a doctor: what was checked, what is wrong, how to fix it.

def doctor(**facts):
    missing = [p for p in views() if not p.exists()]
    if not missing:
        return [footman.Finding("views: whole")]
    return [footman.Finding("views", f"{len(missing)} missing", "sync", mend)]

Attributes:

Name Type Description
what str

The check and its answer, short, the way a receipt names a step.

found str

What is wrong; empty for a healthy check, which prints what alone.

fix str

The words a person acts on when the finding stands.

repair Callable[[], None] | None

An action that mends it, run under --fix; None when only a person can.

what instance-attribute

what: str

The check and its answer, short, the way a receipt names a step.

found class-attribute instance-attribute

found: str = ''

What is wrong; empty for a healthy check, which prints what alone.

fix class-attribute instance-attribute

fix: str = ''

The words a person acts on when the finding stands.

repair class-attribute instance-attribute

repair: Callable[[], None] | None = None

An action that mends it, run under --fix; None when only a person can.

Progress

livery.footman.progress

progress(done: int, total: int = 0) -> None

Report this task's own progress: done of total units.

Some work knows exactly how far along it is — 23 of 150 migrations, bytes of a download — and that is better evidence than any duration history. A reporting task's counts drive the live bar directly (counted beats estimated), so the bar is honest on the very first run, where the estimator would still be guessing.

@task
def migrate():
    for i, record in enumerate(records, 1):
        apply(record)
        progress(i, len(records))

A total of 0 (or less) clears the report, returning the run to its estimate. Outside a run, or with no live status line, this is a no-op — plain calls and captured runs cost nothing.

Source code in packages/footman/src/livery/footman/_context.py
def progress(done: int, total: int = 0) -> None:
    """Report this task's own progress: *done* of *total* units.

    Some work knows exactly how far along it is — 23 of 150 migrations,
    bytes of a download — and that is better evidence than any duration
    history. A reporting task's counts drive the live bar directly
    (counted beats estimated), so the bar is honest on the very first
    run, where the estimator would still be guessing.

    ```python
    @task
    def migrate():
        for i, record in enumerate(records, 1):
            apply(record)
            progress(i, len(records))
    ```

    A `total` of 0 (or less) clears the report, returning the run to its
    estimate. Outside a run, or with no live status line, this is a
    no-op — plain calls and captured runs cost nothing.
    """
    status = active_status()
    if status is None:
        return
    ctx = current()
    name = ctx.task or "task"
    if total > 0:
        status.unit_counted(name, max(done, 0), total)
    else:  # a cleared report: back to the estimate
        with contextlib.suppress(Exception):
            status.counted.pop(name, None)

livery.footman.track

track(iterable: Iterable[_T], total: int | None = None) -> Iterator[_T]

Iterate iterable, reporting progress as it goes.

The ergonomic form of progress(): the total comes from len() when the iterable has one, or from total when you know it for a generator. Without either, iteration still works — the run simply keeps whatever progress it had.

@task
def migrate():
    for record in track(load_records()):
        apply(record)
Source code in packages/footman/src/livery/footman/_context.py
def track(iterable: Iterable[_T], total: int | None = None) -> Iterator[_T]:
    """Iterate *iterable*, reporting progress as it goes.

    The ergonomic form of `progress()`: the total comes from `len()` when
    the iterable has one, or from *total* when you know it for a
    generator. Without either, iteration still works — the run simply
    keeps whatever progress it had.

    ```python
    @task
    def migrate():
        for record in track(load_records()):
            apply(record)
    ```
    """
    if total is None:
        total = len(iterable) if isinstance(iterable, Sized) else 0
    done = 0
    try:
        for item in iterable:
            yield item
            done += 1
            if total:
                progress(done, total)
    finally:
        if total:  # leaving early (a break, an exception) resets the report
            progress(0, 0)

Profiling from inside a task

livery.footman.section

section(name: str) -> _SectionTimer

Time a section of the running task — with footman.section("resolve"):.

Records onto the task's own timeline, subdividing its span; nested blocks nest. For work that overlaps — several waits in flight at once — use stream(), where overlap is legal.

Source code in packages/footman/src/livery/footman/_context.py
def section(name: str) -> _SectionTimer:
    """Time a section of the running task — `with footman.section("resolve"):`.

    Records onto the task's own timeline, subdividing its span; nested
    blocks nest. For work that overlaps — several waits in flight at once —
    use `stream()`, where overlap is legal."""
    return _SectionTimer(_profiled_ctx("section()"), name, "")

livery.footman.mark

mark(name: str) -> None

Record an instant on the running task's timeline — a moment worth a label, no duration.

Source code in packages/footman/src/livery/footman/_context.py
def mark(name: str) -> None:
    """Record an instant on the running task's timeline — a moment worth a
    label, no duration."""
    ctx = _profiled_ctx("mark()")
    ctx.sections.append(Section(name, time.perf_counter(), 0.0))

livery.footman.stream

stream(name: str) -> Stream

A named parallel timeline under the running task — see Stream.

Source code in packages/footman/src/livery/footman/_context.py
def stream(name: str) -> Stream:
    """A named parallel timeline under the running task — see `Stream`."""
    if not name:
        raise ValueError(
            "stream(''): the empty name is the task's own timeline — "
            "sections land there via footman.section()"
        )
    return Stream(_profiled_ctx("stream()"), name)

livery.footman.Stream

Stream(ctx: Context, name: str)

A named parallel timeline of sections under the running task.

Made in the task body (ci = footman.stream("ci")); the handle remembers its task, so a helper thread the body spawned may record through it. Sections on a stream may overlap — that is what a stream is for.

Methods:

Name Description
section

A section on this stream: bracketing (with ci.section("poll"):)

Attributes:

Name Type Description
__slots__
name str
Source code in packages/footman/src/livery/footman/_context.py
def __init__(self, ctx: Context, name: str) -> None:
    self._ctx = ctx
    self.name = name

__slots__ class-attribute instance-attribute

__slots__ = ('_ctx', 'name')

name instance-attribute

name: str = name

section

section(name: str) -> _SectionTimer
section(name: str, *, start: datetime | float, end: datetime | float) -> None
section(name: str, *, start: datetime | float | None = None, end: datetime | float | None = None) -> _SectionTimer | None

A section on this stream: bracketing (with ci.section("poll"):) or retroactive — ci.section("build", start=t0, end=t1) records a window learned after the fact (a CI check's real run, reported by its API), placed by wall clock.

Source code in packages/footman/src/livery/footman/_context.py
def section(
    self,
    name: str,
    *,
    start: datetime | float | None = None,
    end: datetime | float | None = None,
) -> _SectionTimer | None:
    """A section on this stream: bracketing (`with ci.section("poll"):`)
    or retroactive — `ci.section("build", start=t0, end=t1)` records a
    window learned after the fact (a CI check's real run, reported by
    its API), placed by wall clock."""
    if (start is None) != (end is None):
        raise ValueError(
            "Stream.section(): give both start= and end=, or neither — "
            "half a window places nothing"
        )
    if start is None:
        return _SectionTimer(self._ctx, name, self.name)
    assert end is not None
    begin = _run_clock(start, "start")
    finish = _run_clock(end, "end")
    if finish < begin:
        raise ValueError(
            f"Stream.section({name!r}): end is before start — the window "
            f"is {begin - finish:.3f}s inside out"
        )
    self._ctx.sections.append(Section(name, begin, finish - begin, self.name))
    return None

livery.footman.Section dataclass

Section(name: str, started: float, duration: float, stream: str = '')

One recorded interval of a task's time — what the --json envelope carries and a profile renders. stream is "" for the task's own timeline (these nest and never overlap, by construction); a named stream is its own parallel timeline, where overlap is legal. A mark() is a section with no duration.

Attributes:

Name Type Description
name str
started float
duration float
stream str

name instance-attribute

name: str

started instance-attribute

started: float

duration instance-attribute

duration: float

stream class-attribute instance-attribute

stream: str = ''

Asking the person running it

livery.footman.prompt

prompt(message: str = ..., *, default: str | None = ..., secret: bool = ...) -> str
prompt(message: str = ..., *, type: type[_T], default: _T | None = ..., secret: bool = ...) -> _T
prompt(message: str = ..., *, type: Any, default: Any = ..., secret: bool = ...) -> Any
prompt(message: str = '', *, type: Any = str, default: Any = None, secret: bool = False) -> Any

Ask the person running the task for a line of input.

A bare input() doesn't work in a task: its prompt goes to stdout, which footman buffers per task so parallel output never interleaves (and --json stays one envelope), so the prompt is swallowed and the task looks hung. prompt() writes to the real terminal on stderr instead — never captured — and serialises concurrent prompts.

Usable only inside an @task(interactive=True) task; called in an ordinary task body it raises a taught error naming the two fixes. Off a terminal, under --no-input or --dry-run, or when it would otherwise block, it returns default if given, else raises — an unattended run fails loudly, and a rehearsal is unattended by nature. For a value a script must supply, take it as a task parameter (a CLI flag) instead.

type= reuses the parameter type language as the validator: the answer runs through the same coercion pipeline a flag does — int, Path, an enum, Literal[…], a union, or Annotated[…] carrying between() / check() / exists — and a bad answer is taught and re-asked rather than raised. An empty answer takes default (returned as given, uncoerced), and an unattended run takes it the same way. One value per prompt: collections, and the markers that decide how a parameter gets filled (ask(), env(), suggest(), …), are refused by name — declare a parameter, or reach for select().

secret=True hides the typing (getpass) and returns a Secret, so the answer redacts in tracebacks and structured output the same way ask(secret=True) does — hiding a value while it is typed and then printing it in the first traceback would be a strange kind of secret. A default returned unattended is wrapped too: where the value came from doesn't change what it is. A secret is text by nature, so secret=True with a non-str type= is refused — ask(secret=True) on a typed parameter is that spelling.

Source code in packages/footman/src/livery/footman/_context.py
def prompt(
    message: str = "",
    *,
    type: Any = str,
    default: Any = None,
    secret: bool = False,
) -> Any:
    """Ask the person running the task for a line of input.

    A bare `input()` doesn't work in a task: its prompt goes to stdout, which
    footman buffers per task so parallel output never interleaves (and `--json`
    stays one envelope), so the prompt is swallowed and the task looks hung.
    `prompt()` writes to the real terminal on stderr instead — never captured —
    and serialises concurrent prompts.

    Usable only inside an `@task(interactive=True)` task; called in an ordinary
    task body it raises a taught error naming the two fixes. Off a terminal,
    under `--no-input` or `--dry-run`, or when it would otherwise block, it
    returns `default` if given, else raises — an unattended run fails loudly,
    and a rehearsal is unattended by nature. For a value a
    script must supply, take it as a task parameter (a CLI flag) instead.

    `type=` reuses the parameter type language as the validator: the answer
    runs through the same coercion pipeline a flag does — `int`, `Path`, an
    enum, `Literal[…]`, a union, or `Annotated[…]` carrying `between()` /
    `check()` / `exists` — and a bad answer is taught and re-asked rather
    than raised. An empty answer takes `default` (returned as given,
    uncoerced), and an unattended run takes it the same way. One value per
    prompt: collections, and the markers that decide how a *parameter* gets
    filled (`ask()`, `env()`, `suggest()`, …), are refused by name — declare
    a parameter, or reach for `select()`.

    `secret=True` hides the typing (getpass) *and* returns a `Secret`, so the
    answer redacts in tracebacks and structured output the same way
    `ask(secret=True)` does — hiding a value while it is typed and then
    printing it in the first traceback would be a strange kind of secret.
    A default returned unattended is wrapped too: where the value came from
    doesn't change what it is. A secret is text by nature, so `secret=True`
    with a non-`str` `type=` is refused — `ask(secret=True)` on a typed
    parameter is that spelling.
    """
    from livery.footman._params import Secret

    if secret and type is not str:
        raise ValueError(
            "prompt(): a secret answer is text — drop type=, or declare the "
            "value as a typed parameter with ask(secret=True)"
        )
    ctx = _guard_interactive("prompt()")
    peeled = None
    if type is not str:
        # Refuse a bad type= before the unattended branch can paper over it
        # with the default: a wrong annotation is a programming error, and
        # those fail the same way attended or not.
        from livery.footman import _coerce

        peeled = _coerce.peel(type)
        _refuse_prompt_markers(peeled)
        if peeled.multiple or peeled.mapping:
            raise ValueError(
                "prompt() takes one value — for several, use "
                "select(multiple=True) or declare a parameter (Many[…])"
            )
    if ctx.no_input or ctx.dry_run:
        if default is not None:
            return Secret(default) if secret else default
        why = "--no-input is set" if ctx.no_input else "a dry-run is unattended"
        raise RuntimeError(
            f"prompt(): {why}, so nothing can be asked. Pass a "
            f"default, or supply the value as a task parameter (a CLI flag)."
        )
    if peeled is None:
        answer = _prompt_core(message, default=default, secret=secret)
        return Secret(answer) if secret else answer

    from livery.footman._executor import _coerce_extra

    err = real_stderr()
    while True:
        # An empty answer means the default when one exists, so hand
        # _prompt_core "" as its degrade value too: off a terminal the same
        # default comes back through the same door.
        raw = _prompt_core(message, default="" if default is not None else None)
        if raw == "" and default is not None:
            return default
        try:
            # ask()'s own pipeline for a token the splitter never saw:
            # strict coercion, then choices / bounds / path / check(fn).
            return _coerce_extra(raw, peeled, "the answer")
        except ValueError as exc:
            err.write(_scrub(f"  {exc}") + "\n")
            err.flush()

livery.footman.confirm

confirm(message: str, *, default: bool = False) -> bool

Ask a yes/no question. --yes auto-answers yes; Enter alone takes default; off a terminal or under --no-input/--dry-run the answer is default. Guarded like prompt() — interactive tasks only.

Source code in packages/footman/src/livery/footman/_context.py
def confirm(message: str, *, default: bool = False) -> bool:
    """Ask a yes/no question. `--yes` auto-answers yes; Enter alone takes
    `default`; off a terminal or under `--no-input`/`--dry-run` the answer
    is `default`. Guarded like `prompt()` — interactive tasks only."""
    ctx = _guard_interactive("confirm()")
    if ctx.assume_yes:
        return True
    if ctx.no_input or ctx.dry_run:
        return default
    reply = _prompt_core(
        f"{message} {'[Y/n]' if default else '[y/N]'} ",
        default="y" if default else "n",
    )
    return reply.strip().lower() in ("y", "yes")

livery.footman.select

select(message: str, options: Sequence[str], *, multiple: Literal[True], default: list[str] = ...) -> list[str]
select(message: str, options: Sequence[str], *, multiple: Literal[False] = False, default: str = ...) -> str
select(message: str, options: Sequence[str | tuple[str, _V]], *, multiple: Literal[True], default: list[str | _V] = ...) -> list[str | _V]
select(message: str, options: Sequence[str | tuple[str, _V]], *, multiple: Literal[False] = False, default: str | _V = ...) -> str | _V
select(message: str, options: Sequence[Any], *, multiple: bool = False, default: Any = _UNSET) -> Any

Let the person pick from a runtime-computed list — the one interactive case a flag can't cover, because the options aren't known until the task runs (which changed packages to release, which stale branches to delete).

options are strings, or (label, value) pairs to show one thing and return another. multiple=True returns the chosen subset as a list; otherwise one value is returned. Guarded like prompt() (interactive tasks only), and off a terminal or under --no-input/--dry-run it returns default, or raises if none was given.

Source code in packages/footman/src/livery/footman/_context.py
def select(
    message: str,
    options: Sequence[Any],
    *,
    multiple: bool = False,
    default: Any = _UNSET,
) -> Any:
    """Let the person pick from a runtime-computed list — the one interactive
    case a flag can't cover, because the options aren't known until the task
    runs (which changed packages to release, which stale branches to delete).

    `options` are strings, or `(label, value)` pairs to show one thing and
    return another. `multiple=True` returns the chosen subset as a list;
    otherwise one value is returned. Guarded like `prompt()` (interactive tasks
    only), and off a terminal or under `--no-input`/`--dry-run` it returns
    `default`, or raises if none was given.
    """
    ctx = _guard_interactive("select()")
    return _select_core(
        message,
        options,
        multiple=multiple,
        default=default,
        no_input=ctx.no_input or ctx.dry_run,
    )

livery.footman.attended

attended() -> bool

Whether a prompt would reach a human: stdin is a real terminal and the run was not declared unattended (--no-input, --dry-run).

The question prompt()/confirm()/select() already answer for themselves by degrading to their defaults — attended() is for changing the shape of a run instead: skip an optional wizard outright, take the quiet path in CI. --yes deliberately does not count as unattended: it auto-answers confirm() gates but forbids nothing.

Readable anywhere, but it licenses nothing: a mid-body prompt still requires @task(interactive=True), because owning the terminal under parallelism is a separate question from someone being there to answer.

Source code in packages/footman/src/livery/footman/_context.py
def attended() -> bool:
    """Whether a prompt would reach a human: stdin is a real terminal and the
    run was not declared unattended (`--no-input`, `--dry-run`).

    The question `prompt()`/`confirm()`/`select()` already answer for
    themselves by degrading to their defaults — `attended()` is for changing
    the *shape* of a run instead: skip an optional wizard outright, take the
    quiet path in CI. `--yes` deliberately does not count as unattended: it
    auto-answers `confirm()` gates but forbids nothing.

    Readable anywhere, but it licenses nothing: a mid-body prompt still
    requires `@task(interactive=True)`, because owning the terminal under
    parallelism is a separate question from someone being there to answer.
    """
    ctx = current()
    return not (ctx.no_input or ctx.dry_run) and _stdin_is_tty()

livery.footman.tty

tty() -> bool

Whether this run's output lands on a live terminal, colour policy aside: the real stdout is a terminal (on Windows, one that interprets ANSI) and output is not captured into a --json envelope. NO_COLOR and --color do not change the answer — a person with colour turned off is still watching, so gate pagers and live displays here and colour on colored(). False outside a run: the scheduler stamps it per task.

Source code in packages/footman/src/livery/footman/_context.py
def tty() -> bool:
    """Whether this run's output lands on a live terminal, colour policy
    aside: the real stdout is a terminal (on Windows, one that interprets
    ANSI) and output is not captured into a `--json` envelope. `NO_COLOR` and
    `--color` do not change the answer — a person with colour turned off is
    still watching, so gate pagers and live displays here and colour on
    `colored()`. `False` outside a run: the scheduler stamps it per task."""
    return current().terminal

livery.footman.colored

colored() -> bool

Whether this task's own output should dress for colour — the same never/always/auto cascade footman's own chrome follows: --color=never (or NO_COLOR, or a dumb terminal) says no, --color=always forces colour even into a pipe (but never into a --json envelope), and auto follows the terminal.

Source code in packages/footman/src/livery/footman/_context.py
def colored() -> bool:
    """Whether this task's own output should dress for colour — the same
    `never`/`always`/`auto` cascade footman's own chrome follows:
    `--color=never` (or `NO_COLOR`, or a dumb terminal) says no,
    `--color=always` forces colour even into a pipe (but never into a
    `--json` envelope), and `auto` follows the terminal."""
    return _colored(current())

Painting output

wants_color(stream) answers whether to paint text for a stream, following --color, NO_COLOR and the stream's own tty-ness, and styled(text, style, on=…) paints it.

livery.footman.wants_color

wants_color(stream: Any, mode: str = 'auto') -> bool

Whether to paint output for stream under a resolved colour mode.

"always"/"never" are the explicit tri-state answers (--color=…, config, FORCE_COLOR/NO_COLOR); "auto" (the default) falls back to the stream's own tty-ness, honouring NO_COLOR and a dumb terminal.

Source code in packages/footman/src/livery/footman/_describe.py
def wants_color(stream: Any, mode: str = "auto") -> bool:
    """Whether to paint output for *stream* under a resolved colour *mode*.

    `"always"`/`"never"` are the explicit tri-state answers (`--color=…`, config,
    `FORCE_COLOR`/`NO_COLOR`); `"auto"` (the default) falls back to the stream's
    own tty-ness, honouring `NO_COLOR` and a dumb terminal.
    """
    if mode == "never":
        return False
    if mode == "always":
        return True
    import os as _os

    return (
        ansi_capable(stream)
        and "NO_COLOR" not in _os.environ
        and _os.environ.get("TERM") != "dumb"
    )

livery.footman.styled

styled(text: str, style: str = 'bold', *, on: bool = True) -> str

text in style when on, else as it is: bold, dim, cyan, bold-cyan or red.

Pass on=wants_color(stream) so a pipe or NO_COLOR gets plain text; inside a task, colored() answers the same question for its output.

Raises:

Type Description
ValueError

for a style STYLES does not name.

Source code in packages/footman/src/livery/footman/_describe.py
def styled(text: str, style: str = "bold", *, on: bool = True) -> str:
    """*text* in *style* when *on*, else as it is: bold, dim, cyan, bold-cyan or red.

    Pass `on=wants_color(stream)` so a pipe or `NO_COLOR` gets plain text;
    inside a task, `colored()` answers the same question for its output.

    Raises:
        ValueError: for a style `STYLES` does not name.
    """
    paint = STYLES.get(style)
    if paint is None:
        raise ValueError(f"no style {style!r}: the styles are {', '.join(STYLES)}")
    return paint(text, on)

The process boundary

stdin binds to typed parameters, and a Stdout[T] return owns stdout. The full contract lives on Pipelines and JSON output.

livery.footman.Stdin module-attribute

Stdin = Annotated[_T, stdin]

Shorthand for Annotated[T, stdin], in the Arg/Forward mould:

def review(diff: Stdin[str] = ""): ...

The bare-marker form only — the call forms (stdin("field"), stdin(lines=True)) are spelled inside Annotated, like env("VAR").

livery.footman.stdin

stdin(field: str | None = None, *, lines: bool = False)

Bind this parameter from the process's standard input, via Annotated:

def review(diff: Annotated[str, stdin] = ""): ...
# git diff | fm review     AND     fm review < changes.patch

The annotation decides how the bytes are interpreted: str reads the stream as UTF-8 text (universal newlines), bytes reads it raw. Two call forms refine that:

  • stdin("prompt") binds one top-level field of a JSON document on stdin — the value flows through the same coercion and validation as a CLI token.
  • stdin(lines=True) binds a list parameter from lines of text — each line is coerced like one CLI token, so list[int] and list[Path] work as they would as repeated flags.

Precedence is CLI > stdin > env > default > prompt, so an explicit option always wins and one signature serves both fm process file.txt and cat file.txt | fm process. The stream is read once, fully, at the boundary — never inside a task body, so the parallel-stdin guard is never in play — and the same payload serves every parameter that asks. A terminal on stdin means "not provided": the parameter falls back to its default, and a required parameter refuses with a taught message rather than blocking on a read.

Attributes:

Name Type Description
__slots__
field str | None
lines bool
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, field: str | None = None, *, lines: bool = False) -> None:
    if field is not None and lines:
        raise ValueError(
            "stdin(field) and stdin(lines=True) are exclusive — a field "
            "binds one JSON value, lines bind a list of tokens"
        )
    self.field = field
    self.lines = lines

__slots__ class-attribute instance-attribute

__slots__ = ('field', 'lines')

field instance-attribute

field: str | None = field

lines instance-attribute

lines: bool = lines

livery.footman.Stdout module-attribute

Stdout = Annotated[_T, stdout]

Shorthand for Annotated[T, stdout] on a return annotation:

def wordcount(text: Stdin[str] = "") -> Stdout[int]: ...

Stdout[dict | None] is the house spelling for a filter that sometimes has nothing to say (marker outermost, like NoSplit[list[X] | None]); Stdout[dict] | None means the same thing. See stdout.

livery.footman.stdout module-attribute

stdout: Final[StdoutMarker] = StdoutMarker()

Declare that a task's return value is the document on stdout, via the return annotation:

@task
def status() -> Stdout[dict]: ...
# fm status | jq .branch

The task is then a Unix filter by declaration — no flag at any call site. The return type decides the bytes, mirroring stdin: Stdout[str] emits the string verbatim (plus a trailing newline), Stdout[bytes] writes raw bytes, anything structured is JSON — pretty-printed on a terminal, one compact line into a pipe, dataclasses and Secret redaction handled by the same encoder --json uses — so a Secret inside a structured document serialises as ***, and a task that means to emit one says token.reveal(). A Stdout[str] built by formatting is unaffected: string operations on a Secret yield a plain str, which is how the print-a-credential filter (eval "$(fm env-export)") works without a switch to disarm redaction everywhere else.

The rules that keep it honest: an explicit --json wins (the document rides inside results[].returned); only the addressed task emits (a declaring task reached as a pre=/post= dependency or a fan-out member is suppressed, not refused); two declaring tasks in one chain is a plan-time refusal; None means empty stdout, exit 0; a failed task emits nothing; everything that is not the document — prints, run() output — replays on stderr. A bare -> int stays the exit-code channel; declaring Stdout[int] makes the int the document instead. A body call is unaffected: status() from another task just returns the value.

livery.footman.real_stderr

real_stderr() -> TextIO

The underlying stderr, bypassing the routing proxy.

Source code in packages/footman/src/livery/footman/_context.py
def real_stderr() -> TextIO:
    """The underlying stderr, bypassing the routing proxy."""
    return _err_router.real if _err_router is not None else sys.stderr

The working directory & lanes

livery.footman.cwd

cwd() -> Path

The current task's working directory, always concrete.

ctx.cwd as the policy ladder resolved it — the blessed base for a task body's own path arithmetic (footman.cwd() / "dist"), instead of relative paths against the process cwd, which belongs to no one in a parallel run. Outside a run it is simply the process cwd.

Source code in packages/footman/src/livery/footman/_context.py
def cwd() -> Path:
    """The current task's working directory, always concrete.

    `ctx.cwd` as the policy ladder resolved it — the blessed base for a task
    body's own path arithmetic (`footman.cwd() / "dist"`), instead of
    relative paths against the process cwd, which belongs to no one in a
    parallel run. Outside a run it is simply the process cwd.
    """
    resolved = current().cwd
    return resolved if resolved is not None else Path.cwd()

livery.footman.chdir

chdir(target: str | Path | None = None, *, rel: str | Path | None = None) -> Generator[None]

Really change the process directory — inside a serial/exclusive task.

The sugar for bodies that own the globals: the default target is the task's own ctx.cwd; arguments follow the marker grammar exactly — a policy token (root, taskfile, asinvoked) or an absolute path, with rel= for a relative suffix; a bare relative path is the same taught error the markers give. Performs a real os.chdir, keeps ctx.cwd in sync (so a nested run() roots where the block does), restores both on exit. In a parallel task it is a taught error — the cwd belongs to no one there.

Source code in packages/footman/src/livery/footman/_context.py
@contextlib.contextmanager
def chdir(
    target: str | Path | None = None, *, rel: str | Path | None = None
) -> Generator[None]:
    """Really change the process directory — inside a serial/exclusive task.

    The sugar for bodies that own the globals: the default target is the
    task's own `ctx.cwd`; arguments follow the marker grammar exactly — a
    policy token (`root`, `taskfile`, `asinvoked`) or an absolute path, with
    `rel=` for a relative suffix; a bare relative path is the same taught
    error the markers give. Performs a real `os.chdir`, keeps `ctx.cwd` in
    sync (so a nested `run()` roots where the block does), restores both on
    exit. In a parallel task it is a taught error — the cwd belongs to no
    one there.
    """
    ctx = current()
    if ctx.in_task and not ctx.serial_active:
        raise RuntimeError(
            f"task {ctx.task or '?'} calls footman.chdir() in a parallel "
            f"task — the process directory belongs to no one there. The "
            f"ladder: build paths from footman.cwd() (no chdir at all); or "
            f"claim lanes=(cwd_lane,) if the real directory only needs to "
            f"*be* the task's cwd for the duration; or mark the task serial "
            f"(or exclusive) to own the real globals — footman.chdir() is "
            f"legal there."
        )
    base: Path
    if target is None:
        base = ctx.cwd if ctx.cwd is not None else Path(_globals.real_getcwd())
    elif isinstance(target, str) and target == "root" and ctx.root_dir:
        base = Path(ctx.root_dir)
    elif isinstance(target, str) and target == "asinvoked" and ctx.invoked_dir:
        base = Path(ctx.invoked_dir)
    elif isinstance(target, str) and target == "taskfile":
        from livery.footman._discover import defining_dir

        home = defining_dir(ctx.fn) if ctx.fn is not None else None
        base = Path(home) if home else Path(_globals.real_getcwd())
    elif isinstance(target, str) and target == "unmanaged":
        raise TypeError("chdir(cwd='unmanaged') has no directory to change to")
    else:
        base = Path(target)
        if not base.is_absolute():
            raise TypeError(
                f"chdir({str(target)!r}) is relative — chdir takes a policy "
                f"token or an absolute path; a relative suffix goes in rel=…"
            )
    if rel is not None:
        rel_suffix = Path(rel)
        if rel_suffix.is_absolute() or rel_suffix.anchor:
            raise TypeError(
                f"rel={str(rel)!r} is absolute — rel is a suffix appended "
                f"to the resolved base; an absolute directory goes first."
            )
        base = base / rel
    saved_fs, saved_ctx = _globals.real_getcwd(), ctx.cwd
    _globals.real_chdir(base)
    ctx.cwd = base
    try:
        yield
    finally:
        with contextlib.suppress(OSError):
            _globals.real_chdir(saved_fs)
        ctx.cwd = saved_ctx

livery.footman.Lane

Lane(name: str, reason: str | None)

A serialised claim on one named resource: one holder at a time, contending only with claimants of the SAME lane — unrelated work runs untouched (nothing drains; that is exclusive=, a different regime).

Made by footman.lane() and claimed by handing the handle to a task's or a step maker's lanes=: the import system is the registry, so a misspelt lane is an undefined name, and sharing a resource across modules is importing its binding. footman itself ships exactly two — cwd_lane and console_lane — built with the same call.

Methods:

Name Description
__repr__

Attributes:

Name Type Description
__slots__
name str

The resource's one name — what the live line shows a wait on.

reason str | None

Optional documentation on the declaration.

Source code in packages/footman/src/livery/footman/_globals.py
def __init__(self, name: str, reason: str | None) -> None:
    self.name = name
    self.reason = reason

__slots__ class-attribute instance-attribute

__slots__ = ('name', 'reason')

name instance-attribute

name: str = name

The resource's one name — what the live line shows a wait on.

reason instance-attribute

reason: str | None = reason

Optional documentation on the declaration.

__repr__

__repr__() -> str
Source code in packages/footman/src/livery/footman/_globals.py
def __repr__(self) -> str:
    return f"<lane {self.name}>"

livery.footman.lane

lane(name: str, *, reason: str | None = None) -> Lane

Declare a named resource to serialise on. One binding per resource: re-declaring a taken name is a refusal naming both sites — reuse is spelled by importing the handle, never by re-declaring. (The same site re-executing — a module re-imported — is the same declaration.)

Source code in packages/footman/src/livery/footman/_globals.py
def make_lane(name: str, *, reason: str | None = None) -> Lane:
    """Declare a named resource to serialise on. One binding per resource:
    re-declaring a taken name is a refusal naming both sites — reuse is
    spelled by importing the handle, never by re-declaring. (The same
    site re-executing — a module re-imported — is the same declaration.)
    """
    # `sys._getframe`, not `inspect.stack()`: the site is one filename and one
    # line number, and `inspect.stack()` builds a whole FrameInfo for every
    # frame below — reading source files to do it. Measured at 2.1 ms a call
    # from a tasks file, against 1.1 µs here, and footman declares two lanes
    # at import time, so it was ~6 ms on the execution path before anything
    # ran. Same answer, two thousand times cheaper.
    frame = sys._getframe(1)
    site = f"{frame.f_code.co_filename}:{frame.f_lineno}"
    taken = _lane_sites.get(name)
    if taken is not None and taken != site:
        raise ValueError(
            f"lane {name!r} is already declared at {taken} — one binding per "
            f"resource. Share it by importing that handle; a second "
            f"declaration would make two lanes that never contend."
        )
    _lane_sites[name] = site
    return Lane(name, reason)

livery.footman.cwd_lane module-attribute

cwd_lane: Lane = make_lane('cwd', reason='the one real working directory')

livery.footman.console_lane module-attribute

console_lane: Lane = make_lane('console', reason='the one terminal')

Where a task keeps things

Two folders footman writes, both created on access. cache_dir() is derived data the collector sweeps by age; data_dir() is durable and machine-local — credentials, tokens, generated assets — and is never collected. The rest are places footman reads, created by nobody but you: config_dir() and config_file() are your user-level settings, user_tasks_file() the personal rung riding every project, and project_root() the top of this invocation's cascade (None outside a project). fm self.path is the same set from the command line. Where each one lands is the CLI's business, not the task's; see Custom CLIs.

livery.footman.cache_dir

cache_dir() -> Path

This CLI's cache directory, created if it isn't there yet.

Derived data, safe to delete: footman's collector sweeps this folder by age, so put nothing here you would mind losing.

(footman.cache_dir() / "index.json").write_text(payload)

Where it lands is the branded CLI's business — its own folder, or ~/.cache/<name> by default. A task asks for the kind of folder it wants and gets one that exists.

Source code in packages/footman/src/livery/footman/_context.py
def cache_dir() -> Path:
    """This CLI's cache directory, created if it isn't there yet.

    Derived data, safe to delete: footman's collector sweeps this folder by
    age, so put nothing here you would mind losing.

    ```python
    (footman.cache_dir() / "index.json").write_text(payload)
    ```

    Where it lands is the branded CLI's business — its own folder, or
    `~/.cache/<name>` by default. A task asks for the kind of folder it
    wants and gets one that exists.
    """
    from livery.footman import _paths

    return _make(_paths.footman_cache_dir())

livery.footman.scratch_dir

scratch_dir(label: str) -> Path

A fresh directory for this process's scratch, swept once the process is gone.

Under cache_dir(), in scratch/, named <label>-<pid>-<random>: the owner's pid is in the name, so footman's collector can tell a directory a killed or replaced process left from one still in use. Remove it yourself when the work ends; what an exit without handlers leaves, a kill or an exec, goes when the collector next runs and finds the owner's pid gone, in the daily child or fm janitor. A pid the operating system has given to a new process keeps the directory until that process ends too.

scratch = footman.scratch_dir("replay")
try:
    build(scratch)
finally:
    shutil.rmtree(scratch, ignore_errors=True)

Parameters:

Name Type Description Default
label str

What the directory is for: letters, digits, dots, hyphens and underscores. It names the directory for a reader of the cache; the collector reads only the pid after it.

required

Raises:

Type Description
ValueError

when label is empty or carries another character.

Source code in packages/footman/src/livery/footman/_context.py
def scratch_dir(label: str) -> Path:
    """A fresh directory for this process's scratch, swept once the process is gone.

    Under `cache_dir()`, in ``scratch/``, named ``<label>-<pid>-<random>``:
    the owner's pid is in the name, so footman's collector can tell a
    directory a killed or replaced process left from one still in use.
    Remove it yourself when the work ends; what an exit without handlers
    leaves, a kill or an exec, goes when the collector next runs and finds
    the owner's pid gone, in the daily child or `fm janitor`. A pid the
    operating system has given to a new process keeps the directory until
    that process ends too.

    ```python
    scratch = footman.scratch_dir("replay")
    try:
        build(scratch)
    finally:
        shutil.rmtree(scratch, ignore_errors=True)
    ```

    Args:
        label: What the directory is for: letters, digits, dots, hyphens
            and underscores. It names the directory for a reader of the
            cache; the collector reads only the pid after it.

    Raises:
        ValueError: when *label* is empty or carries another character.
    """
    import re
    import tempfile

    from livery.footman import _gc

    if not re.fullmatch(r"[A-Za-z0-9._-]+", label):
        raise ValueError(
            f"a scratch label is letters, digits, '.', '-' and '_': {label!r}"
        )
    room = _make(cache_dir() / _gc.SCRATCH)
    return Path(tempfile.mkdtemp(prefix=f"{label}-{os.getpid()}-", dir=room))

livery.footman.alive

alive(pid: int) -> bool

Whether a process with pid exists.

The one probe for every pid a task or a plugin writes down: a daemon's pid file, a scratch directory's owner, a lock's holder. A pid of zero or less is nobody's. On POSIX a signal of zero asks without sending, and a process that refuses the asking exists. On Windows the kernel is asked for a handle, since os.kill there ends the process for any signal it does not special-case, and a handle whose exit code is set is a process that ended and is not yet reaped.

if not footman.alive(int(pid_file.read_text())):
    pid_file.unlink()
Source code in packages/footman/src/livery/footman/_gc.py
def alive(pid: int) -> bool:
    """Whether a process with *pid* exists.

    The one probe for every pid a task or a plugin writes down: a daemon's
    pid file, a scratch directory's owner, a lock's holder. A pid of zero
    or less is nobody's. On POSIX a signal of zero asks without sending,
    and a process that refuses the asking exists. On Windows the kernel is
    asked for a handle, since ``os.kill`` there ends the process for any
    signal it does not special-case, and a handle whose exit code is set
    is a process that ended and is not yet reaped.

    ```python
    if not footman.alive(int(pid_file.read_text())):
        pid_file.unlink()
    ```
    """
    if pid <= 0:
        return False
    if sys.platform == "win32":
        return _alive_windows(pid)
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        return True
    return True

livery.footman.data_dir

data_dir() -> Path

This CLI's data directory, created if it isn't there yet.

Durable and machine-local — credentials, tokens, generated assets. The collector never touches it, which is the whole difference from cache_dir(). Created owner-only (0o700), like ~/.ssh, because credentials are exactly what it is documented to hold.

(footman.data_dir() / "credentials.json").write_text(token)
Source code in packages/footman/src/livery/footman/_context.py
def data_dir() -> Path:
    """This CLI's data directory, created if it isn't there yet.

    Durable and machine-local — credentials, tokens, generated assets. The
    collector never touches it, which is the whole difference from
    `cache_dir()`. Created owner-only (`0o700`), like `~/.ssh`, because
    credentials are exactly what it is documented to hold.

    ```python
    (footman.data_dir() / "credentials.json").write_text(token)
    ```
    """
    from livery.footman import _paths

    return _make(_paths.footman_data_dir(), mode=0o700)

livery.footman.config_dir

config_dir() -> Path

This CLI's config directory — your writing, never footman's.

The user-level config file and the user-level tasks file live here and travel together. Unlike cache_dir() and data_dir() this one is not created on demand: an empty config directory says something different from a missing one, and inventing it would be footman writing where only you should.

Source code in packages/footman/src/livery/footman/_context.py
def config_dir() -> Path:
    """This CLI's config directory — *your* writing, never footman's.

    The user-level config file and the user-level tasks file live here and
    travel together. Unlike `cache_dir()` and `data_dir()` this one is
    **not** created on demand: an empty config directory says something
    different from a missing one, and inventing it would be footman
    writing where only you should.
    """
    from livery.footman import _paths

    return _paths.footman_config_dir()

livery.footman.config_file

config_file() -> Path

The user-level config file — ~/.config/<brand>/config.toml by default. May not exist; a runner with no config is the ordinary case.

Source code in packages/footman/src/livery/footman/_context.py
def config_file() -> Path:
    """The user-level config file — `~/.config/<brand>/config.toml` by
    default. May not exist; a runner with no config is the ordinary case."""
    from livery.footman import _paths

    return _paths.footman_config_file()

livery.footman.user_tasks_file

user_tasks_file() -> Path

The user-level tasks file: the cascade's outermost writable rung, riding every project. May not exist.

Source code in packages/footman/src/livery/footman/_context.py
def user_tasks_file() -> Path:
    """The user-level tasks file: the cascade's outermost writable rung,
    riding every project. May not exist."""
    from livery.footman import _paths

    return _paths.user_tasks_file(_paths.tasks_file_name())

livery.footman.project_root

project_root() -> Path | None

The top of this invocation's task cascade, or None outside a project.

The same answer --json reports and the root cwd policy resolves against — never a guess from the current directory, which may be anywhere beneath it.

Source code in packages/footman/src/livery/footman/_context.py
def project_root() -> Path | None:
    """The top of this invocation's task cascade, or `None` outside a
    project.

    The same answer `--json` reports and the `root` cwd policy resolves
    against — never a guess from the current directory, which may be
    anywhere beneath it.
    """
    root = current().root_dir
    return Path(root) if root else None

Which CLI is running

For output that has to call the CLI back — a generated CI workflow, a README line — so a branded runner emits its own name instead of fm. prog() is the command someone types, dist() the package that ships it (None when the brand never declared one). Inside a task body ctx.prog says the same and is the better reach: it is the invocation's own answer rather than process state.

livery.footman.prog

prog() -> str

The command this CLI is invoked as — fm, or a branded CLI's own.

For output that has to call the CLI back: a generated CI workflow, a README line, a task that writes prose naming the command someone will type. A branded runner must emit its own name, or the file it writes tells the reader to run a command they do not have.

(root / ".github/workflows/ci.yml").write_text(
    f"      - run: {footman.prog()} check\n"
)

Inside a task body, prefer ctx.prog — declare a ctx: Context parameter and read it. That is the invocation's own answer rather than process state, and it is what footman's own taskdocs plugin uses. This accessor exists for the code that never receives a context: a plugin building its tree at mount time, a helper called from anywhere.

Source code in packages/footman/src/livery/footman/_context.py
def prog() -> str:
    """The command this CLI is invoked as — `fm`, or a branded CLI's own.

    For output that has to *call the CLI back*: a generated CI workflow, a
    README line, a task that writes prose naming the command someone will
    type. A branded runner must emit its own name, or the file it writes
    tells the reader to run a command they do not have.

    ```python
    (root / ".github/workflows/ci.yml").write_text(
        f"      - run: {footman.prog()} check\\n"
    )
    ```

    Inside a task body, prefer `ctx.prog` — declare a `ctx: Context`
    parameter and read it. That is the invocation's own answer rather than
    process state, and it is what footman's own taskdocs plugin uses. This
    accessor exists for the code that never receives a context: a plugin
    building its tree at mount time, a helper called from anywhere.
    """
    from livery.footman import _paths

    return _paths.prog()

livery.footman.dist

dist() -> str | None

The distribution that ships this CLI, or None if it never said.

The name someone would pip install — what the uv handoffs reason about, and what self.install puts on a PATH. App(dist=…) sets it; stock footman answers "footman".

None is a real answer, not a gap: declaring a distribution is opt-in for a branded CLI, and saying "footman" for a brand that never declared one would name the wrong package.

Source code in packages/footman/src/livery/footman/_context.py
def dist() -> str | None:
    """The distribution that ships this CLI, or `None` if it never said.

    The name someone would `pip install` — what the uv handoffs reason
    about, and what `self.install` puts on a PATH. `App(dist=…)` sets it;
    stock footman answers `"footman"`.

    `None` is a real answer, not a gap: declaring a distribution is opt-in
    for a branded CLI, and saying `"footman"` for a brand that never
    declared one would name the wrong package.
    """
    from livery.footman import _paths

    return _paths.declared_dist()

livery.footman.builtins

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

The plugin families this footman mounts in every project, by entry point name.

A branded app declares them (App(builtin=…)); stock footman declares none.

Source code in packages/footman/src/livery/footman/_paths.py
def builtins() -> tuple[str, ...]:
    """The plugin families this footman mounts in every project, by entry point name.

    A branded app declares them (`App(builtin=…)`); stock footman declares
    none.
    """
    return builtin()

livery.footman.directory_variable

directory_variable(name: str) -> str

The environment variable a footman directory is read from.

directory_variable("DATA_DIR") is FOOTMAN_DATA_DIR for stock footman and ACME_DATA_DIR for a brand whose prefix is ACME.

Source code in packages/footman/src/livery/footman/_paths.py
def directory_variable(name: str) -> str:
    """The environment variable a footman directory is read from.

    `directory_variable("DATA_DIR")` is `FOOTMAN_DATA_DIR` for stock footman
    and `ACME_DATA_DIR` for a brand whose prefix is `ACME`.
    """
    return env_var(name)

livery.footman.tasks_file_name

tasks_file_name() -> str

The brand's tasks filename, as configure/configure_child set it.

The refresh child reads it here: child_args hands the resolved value over on spawn, so a branded default IS knowable in the child — the old peek at the cached manifest's baked tasks_file predated that handoff.

Source code in packages/footman/src/livery/footman/_paths.py
def tasks_file_name() -> str:
    """The brand's tasks filename, as `configure`/`configure_child` set it.

    The refresh child reads it here: `child_args` hands the resolved value
    over on spawn, so a branded default IS knowable in the child — the old
    peek at the cached manifest's baked `tasks_file` predated that handoff.
    """
    return _tasks_file

Fetching

livery.footman.fetch

fetch(url: str, *, into: Path | str | None = None, sha256: str = '', backend: str = '', refresh: bool = False) -> Path

Download url (cached), returning the path to the local file.

A second call for the same URL revalidates with the server (ETag / Last-Modified) rather than re-downloading; a 304 Not Modified costs one round trip and keeps "cached" honest. Pass refresh to skip revalidation and fetch unconditionally.

@task
def deps():
    "Fetch the toolchain."
    archive = fetch(TOOLCHAIN_URL, sha256="9f86d0…")
    run(["tar", "-xzf", archive, "-C", "vendor"])

into copies the cached file to a path of your choosing (and returns that path). sha256 verifies what arrived and refuses a mismatch — the way to make a build reproducible. backend overrides the configured one for this call.

Under --dry-run nothing is downloaded: the step is recorded and the would-be cache path returned, so a plan can be inspected safely.

Source code in packages/footman/src/livery/footman/_fetch.py
def fetch(
    url: str,
    *,
    into: Path | str | None = None,
    sha256: str = "",
    backend: str = "",
    refresh: bool = False,
) -> Path:
    """Download *url* (cached), returning the path to the local file.

    A second call for the same URL revalidates with the server (ETag /
    Last-Modified) rather than re-downloading; a `304 Not Modified`
    costs one round trip and keeps "cached" honest. Pass *refresh* to
    skip revalidation and fetch unconditionally.

    ```python
    @task
    def deps():
        "Fetch the toolchain."
        archive = fetch(TOOLCHAIN_URL, sha256="9f86d0…")
        run(["tar", "-xzf", archive, "-C", "vendor"])
    ```

    *into* copies the cached file to a path of your choosing (and
    returns that path). *sha256* verifies what arrived and refuses a
    mismatch — the way to make a build reproducible. *backend* overrides
    the configured one for this call.

    Under `--dry-run` nothing is downloaded: the step is recorded and
    the would-be cache path returned, so a plan can be inspected safely.
    """
    ctx = context.current()
    label = f"fetch {url}"
    manifest = _manifest_path(url)
    meta = _load_meta(manifest)
    body = _cached_body(url, meta)
    # `refresh` skips revalidation, not the cache: the download goes out
    # unconditional, but a cached copy keeps its say as the fallback when
    # that download dies — the documented offline behaviour.
    validators = {} if refresh else meta

    if ctx.dry_run:
        ctx.steps.append(context.Result(0, command=label, raw=label))
        if not ctx.quiet:
            print(f"$ {label}")
        # The cached path when there is one; otherwise the key's nominal
        # stem — a stable placeholder for the plan, never a real file.
        nominal = body or cache_dir() / f"{_key(url)}.bin"
        return Path(into) if into is not None else nominal

    chosen = _resolve_backend(backend or _configured_backend(ctx))
    started = time.perf_counter()
    cache_dir().mkdir(parents=True, exist_ok=True)
    incoming = _scratch(manifest)
    try:
        downloaded, fresh = _download(
            chosen, url, incoming, validators if body is not None else {}
        )
        if downloaded:
            # The data file is content-addressed and immutable: a fresh
            # download lands under a fresh name, so no reader's path is
            # ever replaced underneath them — two cold fetches of one URL
            # publish the same name from the same bytes, and a changed
            # upstream publishes a different one. Only the manifest moves.
            digest = _digest(incoming)
            final = cache_dir() / _data_name(url, digest)
            if final.exists():
                # Same content already published: the bytes are identical
                # by construction, so the part is a duplicate — and not
                # replacing means a Windows reader's open handle is safe.
                incoming.unlink()
            else:
                os.replace(incoming, final)
            body = final
            _publish(
                manifest,
                {"url": url, "data": final.name, "sha256": digest, **(fresh or {})},
            )
    except FetchError:
        if body is not None:  # a cached copy beats a failed refresh
            _touch(manifest, body)
            _record(ctx, label, started, cached=True)
            return _deliver(body, _destination(into, body), sha256, url)
        raise
    finally:
        with contextlib.suppress(OSError):
            incoming.unlink(missing_ok=True)
    if body is None:
        raise FetchError(f"fetch: {url} — nothing downloaded and nothing cached")
    if not downloaded:
        if fresh:
            # A revalidation may hand back fresh validators for the same
            # bytes (a rotated ETag): same data file, updated manifest.
            _publish(manifest, {**meta, **fresh})
        # A serve is a use: the collector's idle rule reads the manifest's
        # mtime, and a 304 writes nothing of its own — untouched, a
        # daily-fetched file would age out and force a pointless re-download.
        _touch(manifest, body)
    _record(ctx, label, started, cached=not downloaded)
    return _deliver(body, _destination(into, body), sha256, url)

livery.footman.FetchError

Bases: Exception

A download failed, or arrived wrong (checksum, missing backend).

The task context

given() answers whether the caller supplied a parameter or footman filled it in — the difference between asking for the default and having no opinion, which the value alone cannot tell you.

livery.footman.Context dataclass

Context(address: str = '', _labels: dict[str, int] = dict(), notes: list[Any] = list(), env: dict[str, str] = (lambda: base_env())(), cwd: Path | None = None, cwd_policy: str = '', root_dir: str = '', invoked_dir: str = '', cwd_unmanaged: bool = False, serial_active: bool = False, dry_run: bool = False, quiet: bool = False, verbose: bool = False, no_color: bool = False, force_color: bool = False, machine_read: bool = False, prog: str = 'fm', sequential: bool = False, assume_yes: bool = False, no_input: bool = False, fetch_backend: str = '', shell_default: str = '', jobs: int = 0, task: str = '', fn: Any = None, given: frozenset[str] = frozenset(), name_width: int = 0, passthrough: list[str] = list(), tty: bool = False, terminal: bool = False, sink: TextIO | None = None, err_sink: TextIO | None = None, interactive: bool = False, atomic: bool = False, keep_going: bool = False, deadline: float | None = None, timeout_declared: float | None = None, shared: bool = True, in_task: bool = False, unit_pending: bool = False, answers: Any = None, steps: list[Result] = list(), sections: list[Section] = list())

State for one running task: environment, flags, passthrough, output.

Methods:

Name Description
time_left

Seconds until this task's deadline, or None when it has none.

overdue

Has this task's deadline passed? False when there is no deadline.

child

One birth for every child context — a body callee's, a

Attributes:

Name Type Description
address str

This context's place in the run's tree — the path of requests that

notes list[Any]

The notes this task fired (_notes.Note records) — what the level

env dict[str, str]

This task's environment — a complete one, not a diff.

cwd Path | None

Where run() executes — resolved once per task by the policy ladder

cwd_policy str

[tool.footman] cwd — the run-wide default policy token (or absolute

root_dir str

The root token's target: the highest cascade task file's directory

invoked_dir str

The asinvoked token's target: the process cwd where fm was

cwd_unmanaged bool

cwd="unmanaged": footman stays out — subprocesses spawn with

serial_active bool

This task holds (or inherited, through a fan-out) the serial or

dry_run bool

--dry-run: run() prints and records the command, executes

quiet bool

--quiet: suppress step lines and the per-task summary.

verbose bool

--verbose: replay captured run() output even on success.

no_color bool

--no-color / --color=never (or NO_COLOR): never emit ANSI styling.

force_color bool

--color=always (or FORCE_COLOR): colour even when output is not a

machine_read bool

--json: the envelope is the report. footman's own receipt chrome —

prog str

The invoking CLI's command name — a branded CLI's own prog, so

sequential bool

The user asked for one-at-a-time (-s or config) — parallel()

assume_yes bool

--yes: every confirm() gate auto-answers yes, for CI and scripts.

no_input bool

--no-input: never prompt — a required prompt errors instead of

fetch_backend str

[fetch] backend from the config ladder — which engine fetch()

shell_default str

[shell] default from the config ladder — what run(shell=True) resolves

jobs int

The effective parallel width (-j/--jobs, config jobs, or the

task str

Who is running, for the step lines' name column: the scheduler

fn Any

The running task's own function — what inherited() reads to find

given frozenset[str]

The parameter names the caller supplied — named on the command line,

name_width int

The widest sibling task name, so step-line columns align.

passthrough list[str]

Everything after -- on the command line, verbatim.

tty bool

Output dresses for a terminal (colour, marks). Live in-place

terminal bool

The run's real stdout is a terminal (on Windows, one that interprets

sink TextIO | None

Where this task's stdout goes: a capture buffer in buffered

err_sink TextIO | None

Where this task's stderr goes. At task level it is the same buffer as

interactive bool

@task(interactive=True): the task owns the real terminal — output is

atomic bool

@task(atomic=True): this task's subprocesses opt out of fail-fast's

keep_going bool

This task's resolved (per-subtree) failure policy, tagged onto the

deadline float | None

@task(timeout=…), resolved to a time.perf_counter() instant when

timeout_declared float | None

The seconds the author wrote in @task(timeout=…), kept beside the

shared bool

Whether an execution the run has already performed may satisfy this

in_task bool

True while a task body runs (the scheduler sets it around the call),

unit_pending bool

A live-progress unit is already counted for this call, and unclaimed:

answers Any

The scripted answers a recording(answers=…) block carries — the

steps list[Result]

Every run() this task made, in order — what recording() and

sections list[Section]

Task-authored profiling: what section(), stream() and mark()

address class-attribute instance-attribute

address: str = ''

This context's place in the run's tree — the path of requests that led here. Every record made under it derives its own address from this one.

notes class-attribute instance-attribute

notes: list[Any] = field(default_factory=list)

The notes this task fired (_notes.Note records) — what the level system resolved, where each came from, and what the boundary verdict and the --json envelope read. A task's own, never inherited.

env class-attribute instance-attribute

env: dict[str, str] = field(default_factory=lambda: _globals.base_env())

This task's environment — a complete one, not a diff.

Starts as a copy of the run's pinned environment, and is what os.environ answers from inside the task, what every child footman spawns receives, and what run(env=…) replaces. Because it is a whole value rather than an overlay, del os.environ["FOO"] is ordinary: it removes the key from this task's environment and from the children it goes on to spawn, while a sibling's copy is untouched.

cwd class-attribute instance-attribute

cwd: Path | None = None

Where run() executes — resolved once per task by the policy ladder (.opts(cwd=) / @task(cwd=) / config cwd, default taskfile), so it is concrete inside a run. A preset value (tests, use_context) wins. None means unresolved (plain calls outside a footman run).

cwd_policy class-attribute instance-attribute

cwd_policy: str = ''

[tool.footman] cwd — the run-wide default policy token (or absolute path) the ladder bottoms out on. Empty means taskfile.

root_dir class-attribute instance-attribute

root_dir: str = ''

The root token's target: the highest cascade task file's directory (files[0].parent), pinned by discovery. Empty outside a real run.

invoked_dir class-attribute instance-attribute

invoked_dir: str = ''

The asinvoked token's target: the process cwd where fm was launched, pinned as a snapshot at startup.

cwd_unmanaged class-attribute instance-attribute

cwd_unmanaged: bool = False

cwd="unmanaged": footman stays out — subprocesses spawn with cwd=None (inherit the live process cwd) even though ctx.cwd records the process cwd at task start for the body to read.

serial_active class-attribute instance-attribute

serial_active: bool = False

This task holds (or inherited, through a fan-out) the serial or exclusive lane: it owns the real process globals — the environ router, the Popen injection, and the os guards all pass through. Set by the executor around a serial=/exclusive= body; parallel() children inherit it, because a lineage extends a hold.

dry_run class-attribute instance-attribute

dry_run: bool = False

--dry-run: run() prints and records the command, executes nothing, and reports success.

quiet class-attribute instance-attribute

quiet: bool = False

--quiet: suppress step lines and the per-task summary.

verbose class-attribute instance-attribute

verbose: bool = False

--verbose: replay captured run() output even on success.

no_color class-attribute instance-attribute

no_color: bool = False

--no-color / --color=never (or NO_COLOR): never emit ANSI styling.

force_color class-attribute instance-attribute

force_color: bool = False

--color=always (or FORCE_COLOR): colour even when output is not a terminal — so run() forces the tools it spawns to colour and the shown command line paints, for a pipe into less -R. Gated off under capture (--json), where ANSI would corrupt the envelope. Never sets the live cursor affordances tty governs — those still need a real terminal.

machine_read class-attribute instance-attribute

machine_read: bool = False

--json: the envelope is the report. footman's own receipt chrome — the step line, the replayed output block, the audit trail — is left out of the buffer, because every one of those already has a field on the step's own row. Task output still lands there: a body's prints are what the buffer is for.

prog class-attribute instance-attribute

prog: str = 'fm'

The invoking CLI's command name — a branded CLI's own prog, so tasks (the taskdocs plugin, say) can speak the brand's name.

sequential class-attribute instance-attribute

sequential: bool = False

The user asked for one-at-a-time (-s or config) — parallel() honours it too. Deliberately not set by the scheduler's own single-node routing, which is presentation, not a request to serialise task bodies.

assume_yes class-attribute instance-attribute

assume_yes: bool = False

--yes: every confirm() gate auto-answers yes, for CI and scripts.

no_input class-attribute instance-attribute

no_input: bool = False

--no-input: never prompt — a required prompt errors instead of asking, so an unattended run fails loudly rather than hanging.

fetch_backend class-attribute instance-attribute

fetch_backend: str = ''

[fetch] backend from the config ladder — which engine fetch() downloads with. Empty means the default (stdlib urllib).

shell_default class-attribute instance-attribute

shell_default: str = ''

[shell] default from the config ladder — what run(shell=True) resolves to. Empty means posix (a POSIX shell everywhere: bash, then sh).

jobs class-attribute instance-attribute

jobs: int = 0

The effective parallel width (-j/--jobs, config jobs, or the cores-minus-one default) — caps parallel() pools in task bodies. 0 means unset (plain calls outside a run): no cap.

task class-attribute instance-attribute

task: str = ''

Who is running, for the step lines' name column: the scheduler sets the dotted task name, parallel() its child's name. Empty outside runs.

fn class-attribute instance-attribute

fn: Any = None

The running task's own function — what inherited() reads to find the task this one shadows. None outside a run.

given class-attribute instance-attribute

given: frozenset[str] = frozenset()

The parameter names the caller supplied — named on the command line, passed as a keyword by a body call, or answered at an ask() prompt. What the given() function reads.

Its complement is everything footman inferred rather than was told: an env() fallback, a default(fn), the declared default. That split is the whole point — a value and the fact that someone asked for it are two different things, and only the second can distinguish --profile (write the default file) from no --profile at all (write nothing).

Empty outside a run, and never inherited: a child task's set is its own, stamped where its context is built.

name_width class-attribute instance-attribute

name_width: int = 0

The widest sibling task name, so step-line columns align.

passthrough class-attribute instance-attribute

passthrough: list[str] = field(default_factory=list)

Everything after -- on the command line, verbatim.

tty class-attribute instance-attribute

tty: bool = False

Output dresses for a terminal (colour, marks). Live in-place rewrites additionally require output to be uncaptured.

terminal class-attribute instance-attribute

terminal: bool = False

The run's real stdout is a terminal (on Windows, one that interprets ANSI) and output is not captured into a --json envelope — tty with the colour policy left out. What the tty() reader answers: NO_COLOR turns tty off because dressed output would be wrong, but the person is still there.

sink class-attribute instance-attribute

sink: TextIO | None = None

Where this task's stdout goes: a capture buffer in buffered (parallel) mode, None for the real stdout (live mode).

err_sink class-attribute instance-attribute

err_sink: TextIO | None = None

Where this task's stderr goes. At task level it is the same buffer as sink (so the atomic parallel flush keeps stdout/stderr in order); a run() capturing an in-process callable temporarily points the two at separate buffers to split the step's streams for its Result.

interactive class-attribute instance-attribute

interactive: bool = False

@task(interactive=True): the task owns the real terminal — output is not captured and it holds sole stdio, so its body may prompt or run a REPL. Mid-body prompt()/confirm()/select() are allowed only here.

atomic class-attribute instance-attribute

atomic: bool = False

@task(atomic=True): this task's subprocesses opt out of fail-fast's kill — they run to completion so a mid-write can't be truncated. Total on purpose: the child is unregistered and not group-isolated, so a stop signal to footman's own pid (timeout, docker stop) ends the run and leaves the child to finish; a terminal's Ctrl-C reaches it only because the kernel signals the whole foreground group itself.

keep_going class-attribute instance-attribute

keep_going: bool = False

This task's resolved (per-subtree) failure policy, tagged onto the subprocesses it spawns so a fail-fast failure elsewhere reaps only the fail-fast trees in a mixed run, sparing a keep-going task's.

deadline class-attribute instance-attribute

deadline: float | None = None

@task(timeout=…), resolved to a time.perf_counter() instant when the body starts — an instant rather than a duration because everything downstream asks "how long is left?", and a duration would have to be re-based at each hand-off.

It is the fail-fast event scoped to one task: past it, no new work starts, in-flight subprocess trees are terminated, and generator steps unwind at their next checkpoint. Inherited by the steps and run() calls a body makes, so a subprocess is bounded by whatever the task has left rather than by its own timeout alone.

timeout_declared class-attribute instance-attribute

timeout_declared: float | None = None

The seconds the author wrote in @task(timeout=…), kept beside the resolved deadline so a failure line can name the declared number rather than the remainder that happened to be left when a call started.

shared class-attribute instance-attribute

shared: bool = True

Whether an execution the run has already performed may satisfy this request. False means it gets its own run, and so does everything it asks for, unless that task declares its own answer. Resolved per node by the scheduler and per call by the cell layer — the sharing twin of keep_going's per-subtree policy.

in_task class-attribute instance-attribute

in_task: bool = False

True while a task body runs (the scheduler sets it around the call), so the interactive primitives tell a guarded mid-body call from the framework's own up-front ask() resolution.

unit_pending class-attribute instance-attribute

unit_pending: bool = False

A live-progress unit is already counted for this call, and unclaimed: parallel() counts every child it is handed, then the first task request inside that child claims the unit instead of counting a second one. A thunk that runs no task keeps it; a thunk that is only a wrapper around one call (the lambda: build("web") spelling) shows as the single piece of work it is. Cleared on claim, so the requests after it — and anything the callee itself asks for — count their own.

answers class-attribute instance-attribute

answers: Any = None

The scripted answers a recording(answers=…) block carries — the normalised table, shared by reference with every child context so an ordered sequence is consumed in one place. None outside a scripted recording; a raw mapping handed to Context(answers=…) is normalised on first use.

steps class-attribute instance-attribute

steps: list[Result] = field(default_factory=list)

Every run() this task made, in order — what recording() and the --json envelope read.

sections class-attribute instance-attribute

sections: list[Section] = field(default_factory=list)

Task-authored profiling: what section(), stream() and mark() recorded while this task ran, on the run's clock. Rides the task's result row; a parallel() child's records fold into its requester's, the way steps do.

time_left

time_left() -> float | None

Seconds until this task's deadline, or None when it has none.

Clamped at zero rather than going negative: callers hand it to subprocess.communicate(timeout=…) and to their own comparisons, and a negative bound reads as "no bound" to some of them. Zero means the deadline has passed and the caller should not start the work.

Source code in packages/footman/src/livery/footman/_context.py
def time_left(self) -> float | None:
    """Seconds until this task's deadline, or `None` when it has none.

    Clamped at zero rather than going negative: callers hand it to
    `subprocess.communicate(timeout=…)` and to their own comparisons,
    and a negative bound reads as "no bound" to some of them. Zero means
    the deadline has passed and the caller should not start the work.
    """
    if self.deadline is None:
        return None
    return max(0.0, self.deadline - time.perf_counter())

overdue

overdue() -> bool

Has this task's deadline passed? False when there is no deadline.

Source code in packages/footman/src/livery/footman/_context.py
def overdue(self) -> bool:
    """Has this task's deadline passed? False when there is no deadline."""
    return self.deadline is not None and time.perf_counter() > self.deadline

child

child(label: str, **overrides: Any) -> Context

One birth for every child context — a body callee's, a parallel() child's — so the sites can never drift on which fields reset.

Identity is fresh: the address and sibling labels, the step and section records, the unit flag. The environment is a COPY — a child's writes are its own, which is the router's "children see it, siblings don't" made structural. Everything else inherits until overrides says otherwise. given deliberately inherits here: the futures layer stamps the callee's own set where binding computes it, and a step child has no binding to compute one.

Source code in packages/footman/src/livery/footman/_context.py
def child(self, label: str, **overrides: Any) -> Context:
    """One birth for every child context — a body callee's, a
    `parallel()` child's — so the sites can never drift on which fields
    reset.

    Identity is fresh: the address and sibling labels, the step and
    section records, the unit flag. The environment is a COPY — a
    child's writes are its own, which is the router's "children see it,
    siblings don't" made structural. Everything else inherits until
    *overrides* says otherwise. `given` deliberately inherits here: the
    futures layer stamps the callee's own set where binding computes
    it, and a step child has no binding to compute one.
    """
    born = replace(
        self,
        address=_child_address(self, label),
        _labels={},
        env=dict(self.env),
        steps=[],
        sections=[],
        notes=[],
        task=label,
        unit_pending=False,
    )
    for name, value in overrides.items():
        setattr(born, name, value)
    return born

livery.footman.current

current() -> Context

The context of the running task (a fresh default one outside a run).

Source code in packages/footman/src/livery/footman/_context.py
def current() -> Context:
    """The context of the running task (a fresh default one outside a run)."""
    ctx = _current.get()
    return ctx if ctx is not None else Context()

livery.footman.given

given(name: str) -> bool

Whether the caller supplied name, as opposed to footman inferring it.

@task
def build(*, profile: Path = Path("build-profile.json")):
    if given("profile"):   # `fm build --profile` writes the default file;
        trace_to(profile)  # `fm build` writes nothing at all

True when the parameter was named on the command line (with or without a value — --profile alone means its default, and means it on purpose), passed as a keyword by a body call, or answered at an ask() prompt. False when the value came from an env() fallback, a default(fn), or the declared default, because nobody asked for those.

That distinction is the only way to tell "the default one, please" from "no opinion", which a value alone cannot express: both hand you the same path.

name is the parameter name, not its flag spelling — dry_run, not --dry-run. Naming something the running task has no parameter for is an error rather than a silent False, since a typo would otherwise read as a perfectly ordinary "not given".

Source code in packages/footman/src/livery/footman/_context.py
def given(name: str) -> bool:
    """Whether the caller supplied *name*, as opposed to footman inferring it.

    ```python
    @task
    def build(*, profile: Path = Path("build-profile.json")):
        if given("profile"):   # `fm build --profile` writes the default file;
            trace_to(profile)  # `fm build` writes nothing at all
    ```

    True when the parameter was named on the command line (with or without a
    value — `--profile` alone means its default, and means it on purpose),
    passed as a keyword by a body call, or answered at an `ask()` prompt. False
    when the value came from an `env()` fallback, a `default(fn)`, or the
    declared default, because nobody asked for those.

    That distinction is the only way to tell "the default one, please" from "no
    opinion", which a value alone cannot express: both hand you the same path.

    *name* is the **parameter** name, not its flag spelling — `dry_run`, not
    `--dry-run`. Naming something the running task has no parameter for is an
    error rather than a silent `False`, since a typo would otherwise read as a
    perfectly ordinary "not given".
    """
    ctx = _current.get()
    if ctx is None or not ctx.in_task or ctx.fn is None:
        raise RuntimeError(
            f"given({name!r}) has no answer here — presence is decided when a "
            f"task's arguments are bound, so call it inside a task body during "
            f"a run"
        )
    from livery.footman import _manifest

    known = {
        p.name
        for p in _manifest.call_signature(ctx.fn).parameters.values()
        if p.kind is not inspect.Parameter.VAR_KEYWORD
    }
    if name not in known:
        listed = ", ".join(sorted(known)) or "(none)"
        dashed = name.replace("-", "_")
        hint = (
            f" — did you mean {dashed!r}?" if dashed != name and dashed in known else ""
        )
        raise ValueError(
            f"given({name!r}): {ctx.task or 'this task'} has no parameter "
            f"{name!r}{hint} (it has: {listed})"
        )
    return name in ctx.given

livery.footman.use_context

use_context(ctx: Context | None = None) -> Generator[Context]

Install ctx as the current run context for the duration of the block.

The public seam for calling tasks from other Python code — tests included: run() and hosted toolroom calls inside the block read this context instead of a fresh default. footman.testing.recording builds on it.

with use_context(Context(env={"CI": "1"})) as ctx:
    deploy()
assert ctx.steps[0].code == 0
Source code in packages/footman/src/livery/footman/_context.py
@contextlib.contextmanager
def use_context(ctx: Context | None = None) -> Generator[Context]:
    """Install *ctx* as the current run context for the duration of the block.

    The public seam for calling tasks from other Python code — tests included:
    `run()` and hosted toolroom calls inside the block read this context
    instead of a fresh default. `footman.testing.recording` builds on it.

    ```python
    with use_context(Context(env={"CI": "1"})) as ctx:
        deploy()
    assert ctx.steps[0].code == 0
    ```
    """
    installed = ctx if ctx is not None else Context()
    token = _current.set(installed)
    try:
        yield installed
    finally:
        _current.reset(token)

Composing tasks

livery.footman.include

include(source: str | ModuleType | Group, /, *, into: str | Group | None = None, only: tuple[str, ...] | list[str] = (), exclude: tuple[str, ...] | list[str] = (), override: bool = False) -> Group

Mount a task tree from an importable module — modules only; for an installed package's advertised tasks use plugin().

include("shared_tasks")                    # everything, at root
include("shared_tasks", only=["lint"])     # cherry-pick a child
include("mytasks.lint")                    # one group out of a module
include("mkdocs_helpers.tasks", into="docs")  # namespaced: fm docs.…

The longest importable prefix is imported under a registry capture (the provider's decorators can't leak into your tree); the rest of the string walks the captured tree. Collisions are loud (RegistrationError) unless override=True; your own definitions silently win. Included tasks run from your file's directory — a shared lint task lints this project. A Group or imported module may be passed programmatically (tests, generated trees). Returns the group grafted into.

Source code in packages/footman/src/livery/footman/_compose.py
def include(
    source: str | ModuleType | Group,
    /,
    *,
    into: str | Group | None = None,
    only: tuple[str, ...] | list[str] = (),
    exclude: tuple[str, ...] | list[str] = (),
    override: bool = False,
) -> Group:
    """Mount a task tree from an importable module — **modules only**; for an
    installed package's advertised tasks use `plugin()`.

    ```python
    include("shared_tasks")                    # everything, at root
    include("shared_tasks", only=["lint"])     # cherry-pick a child
    include("mytasks.lint")                    # one group out of a module
    include("mkdocs_helpers.tasks", into="docs")  # namespaced: fm docs.…
    ```

    The longest importable prefix is imported under a registry capture (the
    provider's decorators can't leak into your tree); the rest of the string
    walks the captured tree. Collisions are loud (`RegistrationError`)
    unless `override=True`; your own definitions silently win. Included
    tasks run from *your* file's directory — a shared lint task lints this
    project. A `Group` or imported module may be passed programmatically
    (tests, generated trees). Returns the group grafted into.
    """
    node: Group | Task
    if isinstance(source, Group):
        identity, node = source.name, source
        landing = source.name
    elif isinstance(source, ModuleType):
        identity, node = source.__name__, _tree_of_module(source)
        landing = source.__name__
    else:
        identity, node = _resolve_module(source)
        landing = source.rsplit(".", 1)[-1]
    return _mount(
        "include",
        identity,
        node,
        into=into,
        only=only,
        exclude=exclude,
        override=override,
        landing_name=landing,
    )

livery.footman.plugin

plugin(source: str, /, *, into: str | Group | None = None, only: tuple[str, ...] | list[str] = (), exclude: tuple[str, ...] | list[str] = (), override: bool = False) -> Group

Mount a task tree from an installed package's footman.tasks entry point — entry points only; for your own modules use include().

plugin("acme.devkit")                      # the import *: every group, top level
plugin("acme.devkit.lint")                 # from acme_devkit import lint
plugin("acme.ci", exclude=["deploy"])      # everything but one child
plugin("footman.docs", into="footman")     # built-ins are ordinary plugins
plugin("acme.linters.default", into="lint")  # adopt a provider's default

The longest installed entry-point name is the identity (consumed at resolve time, retained as provenance); the rest of the string walks the advertised tree. The mounted node lands under its own name — into= (a dotted address, created on demand) is the consumer's placement, and there is no rename. Returns the group grafted into.

Source code in packages/footman/src/livery/footman/_compose.py
def plugin(
    source: str,
    /,
    *,
    into: str | Group | None = None,
    only: tuple[str, ...] | list[str] = (),
    exclude: tuple[str, ...] | list[str] = (),
    override: bool = False,
) -> Group:
    """Mount a task tree from an installed package's `footman.tasks` entry
    point — **entry points only**; for your own modules use `include()`.

    ```python
    plugin("acme.devkit")                      # the import *: every group, top level
    plugin("acme.devkit.lint")                 # from acme_devkit import lint
    plugin("acme.ci", exclude=["deploy"])      # everything but one child
    plugin("footman.docs", into="footman")     # built-ins are ordinary plugins
    plugin("acme.linters.default", into="lint")  # adopt a provider's default
    ```

    The longest installed entry-point name is the *identity* (consumed at
    resolve time, retained as provenance); the rest of the string walks the
    advertised tree. The mounted node lands under its **own name** — `into=`
    (a dotted address, created on demand) is the consumer's placement, and
    there is no rename. Returns the group grafted into.
    """
    identity, node = _resolve_plugin(source)
    return _mount(
        "plugin",
        identity,
        node,
        into=into,
        only=only,
        exclude=exclude,
        override=override,
        landing_name=source.rsplit(".", 1)[-1],
    )

livery.footman.capture

capture() -> Generator[Group]

Redirect module-level @task/group registration into a fresh tree.

The seam include() uses to import a provider module without letting its decorators land in the current registry: root.tasks/root.groups are swapped for fresh dicts for the duration and the captured tree is yielded. Reentrant — a provider may itself include() another provider.

Source code in packages/footman/src/livery/footman/_registry.py
@contextlib.contextmanager
def capture() -> Generator[Group]:
    """Redirect module-level `@task`/`group` registration into a fresh tree.

    The seam `include()` uses to import a provider module without letting its
    decorators land in the current registry: `root.tasks`/`root.groups` are
    swapped for fresh dicts for the duration and the captured tree is yielded.
    Reentrant — a provider may itself `include()` another provider.
    """
    captured = Group("root")
    saved_tasks, saved_groups = root.tasks, root.groups
    saved_contributions = root.contributions
    root.tasks, root.groups = captured.tasks, captured.groups
    root.contributions = captured.contributions
    try:
        yield captured
    finally:
        root.tasks, root.groups = saved_tasks, saved_groups
        root.contributions = saved_contributions

Installed entry points

One scan of every installed distribution per process, shared by footman's plugin loader and anything built on footman.

livery.footman.installed_entry_points

installed_entry_points(group: str | None = None) -> tuple[EntryPoint, ...]

The installed entry points of group, or of every group when None.

The first call scans every installed distribution; every later call in the process answers from that scan. A process that installs a distribution and must see it calls livery.footman.rescan_entry_points first.

Source code in packages/footman/src/livery/footman/_entries.py
def installed_entry_points(group: str | None = None) -> tuple[EntryPoint, ...]:
    """The installed entry points of *group*, or of every group when None.

    The first call scans every installed distribution; every later call
    in the process answers from that scan. A process that installs a
    distribution and must see it calls
    [livery.footman.rescan_entry_points][] first.
    """
    global _SCAN
    if _SCAN is None:
        _SCAN = _scan()
    if group is None:
        return _SCAN
    return tuple(entry for entry in _SCAN if entry.group == group)

livery.footman.rescan_entry_points

rescan_entry_points() -> None

Forget the scan, so the next question reads the installed metadata again.

Source code in packages/footman/src/livery/footman/_entries.py
def rescan_entry_points() -> None:
    """Forget the scan, so the next question reads the installed metadata again."""
    global _SCAN
    _SCAN = None

livery.footman.project_builtins

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

The plugin families root's own dependencies offer, by entry point name.

The footman.builtin names of the distributions root's pyproject.toml depends on directly, in its [project] dependencies and its [dependency-groups]; a dependency of a dependency offers nothing.

Source code in packages/footman/src/livery/footman/_config.py
def project_builtins(root: Path) -> tuple[str, ...]:
    """The plugin families *root*'s own dependencies offer, by entry point name.

    The ``footman.builtin`` names of the distributions *root*'s
    ``pyproject.toml`` depends on directly, in its ``[project]
    dependencies`` and its ``[dependency-groups]``; a dependency of a
    dependency offers nothing.
    """
    return project_builtin(root)

Shell completion

Completion answers from a manifest cached per directory. A program that changes which tasks a directory offers, by installing a distribution that brings new ones, calls refresh_completion to start the rebuild of that directory's manifest, so the next Tab there offers them. See Shell completion.

livery.footman.refresh_completion

refresh_completion(directory: str | Path) -> None

Start the detached rebuild of directory's completion manifest and return.

A program that has just changed which tasks directory offers calls this, for example after it installed a distribution that brings new tasks. Without it, the next Tab there answers from the manifest the last run wrote, until another run there or until the manifest is older than completion.max-age. The rebuild is the one a stale manifest starts after a Tab press: the same detached child, run in directory, builds the tree a run there serves, in this CLI's own cache.

Starts nothing when no person is there to press Tab, as in CI or a run without a terminal: livery.footman.attended answers, and it knows --no-input and --dry-run too. Nobody completes there, and on Windows a detached child can hold files of the environment open while a later step replaces them. Starts nothing when the configuration that applies in directory sets completion.max-age to off, which asks for no background rebuilds, and nothing when that configuration cannot be read. Prints nothing and never raises: when the child cannot start, nothing starts, and the caller's own outcome stands.

Parameters:

Name Type Description Default
directory str | Path

The directory whose manifest to rebuild. A manifest is keyed by the directory a person presses Tab in.

required
Source code in packages/footman/src/livery/footman/_refresh.py
def refresh_completion(directory: str | Path) -> None:
    """Start the detached rebuild of *directory*'s completion manifest and return.

    A program that has just changed which tasks *directory* offers calls this,
    for example after it installed a distribution that brings new tasks.
    Without it, the next <kbd>Tab</kbd> there answers from the manifest the last
    run wrote, until another run there or until the manifest is older than
    `completion.max-age`. The rebuild is the one a stale manifest starts after a
    <kbd>Tab</kbd> press: the same detached child, run in *directory*, builds
    the tree a run there serves, in this CLI's own cache.

    Starts nothing when no person is there to press <kbd>Tab</kbd>, as in CI
    or a run without a terminal: [livery.footman.attended][] answers, and it
    knows `--no-input` and `--dry-run` too. Nobody completes there, and on
    Windows a detached child can hold files of the environment open while a
    later step replaces them. Starts nothing when the configuration that
    applies in *directory* sets `completion.max-age` to `off`, which asks for
    no background rebuilds, and nothing when that configuration cannot be
    read. Prints nothing and never raises: when the child cannot start,
    nothing starts, and the caller's own outcome stands.

    Args:
        directory: The directory whose manifest to rebuild. A manifest is keyed
            by the directory a person presses <kbd>Tab</kbd> in.
    """
    with contextlib.suppress(Exception):
        import os
        from pathlib import Path

        from livery.footman import _complete, _config, _context, _globals

        if not _context.attended():
            return
        stand = Path(directory)
        cfg = _config.load_config(stand, _config.cascade_ceiling(stand))
        if _config.completion_max_age(cfg) is None:
            return
        # Called from a task body, this spawn is footman's own work on the
        # body's behalf, so the Popen guard stands down for it. The guard
        # would hand the child the task's environment. The snapshot, taken
        # through the router before `internal()`, hands over the same, and
        # the directory is passed explicitly too, so nothing changes with
        # the guard gone.
        env = dict(os.environ)
        with _globals.internal():
            _complete._spawn_refresh(spawn_in=str(stand), env=env)

Libraries that run tools

A library that runs tools, toolroom among them, asks host() for the run it is called in, and gets None outside one, so it keeps its standalone behaviour there. It hands run(view=…) a CommandView, so the command line a run shows is the readable one while the call runs whatever the tool needs.

livery.footman.host

host() -> Host | None

The footman run this call is made in; None when no run is in flight.

One is answered while footman's routers are installed or a task's context is current. A library that only imports footman, outside any run, gets None and keeps its standalone behaviour.

Source code in packages/footman/src/livery/footman/_host.py
def host() -> Host | None:
    """The footman run this call is made in; None when no run is in flight.

    One is answered while footman's routers are installed or a task's
    context is current. A library that only imports footman, outside any
    run, gets None and keeps its standalone behaviour.
    """
    import sys

    if "livery.footman._context" not in sys.modules:
        return None
    found = Host()
    return found if found.active or found.in_task else None

livery.footman.Host

The footman run a call is made in, as a tool wrapper asks of it.

A run is in flight when footman's routers are installed (active), and a task is running when a task's context is current (in_task); either makes livery.footman.host answer one.

Methods:

Name Description
real_cwd

The process's own working directory, which a parallel task never moves.

target_cwd

The directory a call runs in: cwd or the task's, relative under it.

argv_override

A block in which this thread alone sees args as sys.argv.

Attributes:

Name Type Description
active bool

Whether footman's routers are installed: a run is in flight.

in_task bool

Whether a task's context is current: a call joins its directory.

active property

active: bool

Whether footman's routers are installed: a run is in flight.

in_task property

in_task: bool

Whether a task's context is current: a call joins its directory.

real_cwd

real_cwd() -> str

The process's own working directory, which a parallel task never moves.

Source code in packages/footman/src/livery/footman/_host.py
def real_cwd(self) -> str:
    """The process's own working directory, which a parallel task never moves."""
    from livery.footman import _globals

    return _globals.real_getcwd()

target_cwd

target_cwd(cwd: str | Path | None = None, relative: str | Path | None = None) -> Path | None

The directory a call runs in: cwd or the task's, relative under it.

None when the task runs unmanaged, or for cwd="unmanaged": the call then inherits the process's directory.

Raises:

Type Description
ValueError

when relative is absolute, or is given with cwd="unmanaged", which has no base to join it to.

Source code in packages/footman/src/livery/footman/_host.py
def target_cwd(
    self, cwd: str | Path | None = None, relative: str | Path | None = None
) -> Path | None:
    """The directory a call runs in: *cwd* or the task's, *relative* under it.

    None when the task runs unmanaged, or for ``cwd="unmanaged"``: the
    call then inherits the process's directory.

    Raises:
        ValueError: when *relative* is absolute, or is given with
            ``cwd="unmanaged"``, which has no base to join it to.
    """
    from livery.footman._context import _target_cwd, current

    return _target_cwd(current(), cwd, relative)

argv_override

argv_override(args: list[str]) -> AbstractContextManager[None]

A block in which this thread alone sees args as sys.argv.

A wrapper runs a tool's zero-argument main() in-process inside one, so parallel calls do not share one sys.argv.

Source code in packages/footman/src/livery/footman/_host.py
def argv_override(self, args: list[str]) -> AbstractContextManager[None]:
    """A block in which this thread alone sees *args* as ``sys.argv``.

    A wrapper runs a tool's zero-argument ``main()`` in-process inside
    one, so parallel calls do not share one ``sys.argv``.
    """
    from livery.footman import _globals

    overridden: AbstractContextManager[None] = _globals.argv_override(args)
    return overridden

livery.footman.CommandView dataclass

CommandView(parts: tuple[tuple[str, str], ...], exact: tuple[str, ...])

What a run() call is, apart from how it's spelled to execute.

A tool wrapper, toolroom's bridge among them, hands one to run(view=…) so the run shows a readable, syntax-highlighted command line — options in separated form, tagged by role — while executing whatever the tool actually needs (attached flags, or an in-process callable). parts is the normalised, human form, each a role and its text; exact is the literal argv, shown under --verbose and always copy-pasteable. Passing it is how the two are kept from drifting: both come from one translation of one call.

Attributes:

Name Type Description
parts tuple[tuple[str, str], ...]

The command line's normalised form, each part a role and its text.

exact tuple[str, ...]

The literal argv the call runs.

Methods:

Name Description
text

The plain command line — the width-measured, non-colour form.

painted

The shown command line, role-coloured when the stream wants it.

parts instance-attribute

parts: tuple[tuple[str, str], ...]

exact instance-attribute

exact: tuple[str, ...]

text

text(*, exact: bool) -> str

The plain command line — the width-measured, non-colour form.

Source code in packages/footman/src/livery/footman/_context.py
def text(self, *, exact: bool) -> str:
    """The plain command line — the width-measured, non-colour form."""
    if exact:
        # `exact` is the literal argv, and the bridge keeps a `Secret`
        # whole in it on purpose — the child needs the real value. That
        # makes this the one rendering path where the marker is still
        # here to act on, and `--verbose` is a showing like any other: a
        # secret must not appear just because the reader asked for the
        # paste-able spelling. `parts` was redacted upstream by the
        # bridge; this is the same rule reaching the other form.
        from livery.footman._describe import redact

        return " ".join(_shell_quote(str(redact(a))) for a in self.exact)
    return " ".join(text for _, text in self.parts)

painted

painted(*, color: bool, exact: bool) -> str

The shown command line, role-coloured when the stream wants it.

Source code in packages/footman/src/livery/footman/_context.py
def painted(self, *, color: bool, exact: bool) -> str:
    """The shown command line, role-coloured when the stream wants it."""
    if exact or not color:
        return self.text(exact=exact)
    from livery.footman._describe import paint_cli

    return paint_cli(list(self.parts), color)

The invocation, and editing the discovered tree

@pre_tasks runs a hook once per invocation, over the fully-merged cascade and before anything else — see Hooks & plugin options. It is handed the Invocation, whose tasks is a Tasks view; iterating or indexing that yields a TaskView that reads and edits one task. The per-task pair — @pre_task and @post_task — runs around every execution; see Around every task.

livery.footman.pre_tasks module-attribute

pre_tasks: Final[HookRegistrar] = root.pre_tasks

livery.footman.pre_bind module-attribute

pre_bind: Final[HookRegistrar] = root.pre_bind

livery.footman.pre_task module-attribute

pre_task: Final[HookRegistrar] = root.pre_task

livery.footman.post_task module-attribute

post_task: Final[HookRegistrar] = root.post_task

livery.footman.post_tasks module-attribute

post_tasks: Final[HookRegistrar] = root.post_tasks

livery.footman.pre_reexec module-attribute

pre_reexec: Final[HookRegistrar] = root.pre_reexec

livery.footman.handing_off

handing_off() -> Generator[dict[str, str]]

Hand this run's state to the process about to replace it.

A verb that re-runs its own command line in a new process wraps the replacing in this, and hands what it yields to execve or to subprocess.run(env=…) where there is no exec:

with footman.handing_off() as handed:
    os.execve(exe, cmd, {**os.environ, **handed})

Every pre_reexec hook the run mounted is entered, and what they yield is merged into one mapping of environment entries for the successor. Nothing mounted, or nothing with state to carry, yields an empty mapping and costs one attribute read.

The block ends by not returning, so returning normally means the replacement did not happen: every hook is then closed the ordinary way and takes its own state back. An exception means the replacement happened — a handoff that waits for its child exits with its code — and the hooks see it, so what they wrote down stands.

A hook that raises on the way in is named on stderr and skipped. A plugin's bookkeeping never stops a repair that was already under way.

Source code in packages/footman/src/livery/footman/_executor.py
@contextlib.contextmanager
def handing_off() -> Generator[dict[str, str]]:
    """Hand this run's state to the process about to replace it.

    A verb that re-runs its own command line in a new process wraps the
    replacing in this, and hands what it yields to `execve` or to
    `subprocess.run(env=…)` where there is no exec:

        with footman.handing_off() as handed:
            os.execve(exe, cmd, {**os.environ, **handed})

    Every `pre_reexec` hook the run mounted is entered, and what they yield
    is merged into one mapping of environment entries for the successor.
    Nothing mounted, or nothing with state to carry, yields an empty mapping
    and costs one attribute read.

    The block ends by not returning, so returning normally means the
    replacement did not happen: every hook is then closed the ordinary way
    and takes its own state back. An exception means the replacement
    happened — a handoff that waits for its child exits with its code — and
    the hooks see it, so what they wrote down stands.

    A hook that raises on the way in is named on stderr and skipped. A
    plugin's bookkeeping never stops a repair that was already under way.
    """
    life = _lifecycle
    handed: dict[str, str] = {}
    with contextlib.ExitStack() as stack:
        for hook in life.handoffs if life is not None else ():
            try:
                entered = stack.enter_context(hook())
            except Exception as exc:
                named = getattr(hook, "__module__", None) or "<unknown>"
                print(f"{named}: its re-exec handoff failed ({exc})", file=sys.stderr)
                continue
            if isinstance(entered, Mapping):
                handed.update({str(key): str(value) for key, value in entered.items()})
        yield handed

livery.footman.GlobalOption

GlobalOption(name: str, annotation: Any = bool, *, default: Any = None, config: bool | str = False, help: str = '')

A plugin's own global option — --env-file=PATH beside --jobs=N.

Constructing one is registering it: a module-level singleton in the provider, stamped with the module that defined it, riding the same carriage as lifecycle hooks — so it reaches a run only when its owner is mounted, and an unmounted owner's option is an unknown option, taught. Long-form only, and the value is =-attached like every option's.

ENV_FILE = GlobalOption("env-file", Path, help="load this .env file")

A bool annotation makes it a flag; anything else takes a value, coerced and validated through the same pipeline as a task parameter — Literal choices, Path file completion, Annotated[..., suggest(...)] all work, because the manifest describes it with the same machinery. Read it anywhere in-run as OPT.value (frozen after parse); cross-plugin use is an ordinary import of the singleton.

A mention with no value is legal — --profile beside --profile=out.json — and carries presence rather than a value: .value is then whatever the option would have had anyway, and .given says someone asked. That is what lets one declared value cover three outcomes (off, the default file, a named file) where a second declared value used to be needed.

config=True gives the option a project-config rung — the one ladder, CLI > env() > config > default(fn) > declared — reading the key named like the option from this provider's own section under the brand table's reserved plugins. child: [tool.footman.plugins.acme-devkit] for the acme.devkit entry point (the dot becomes a hyphen, because TOML's dot is its nesting operator). config="key" names the key instead, for a flag renamed around a collision — flag and key are different namespaces, and only the flag's is shared. The section is the entry point's, de-dotted; footman.config_section("...") names it explicitly where there is nothing to derive from (an include()d module) or the derivation reads wrong.

Methods:

Name Description
__repr__

Attributes:

Name Type Description
__slots__
name str
annotation Any
default Any
config bool | str
help str
owner str
value Any

The parsed value for this run — the flag's presence, the option's

given bool

Whether this option was named on the command line, with or without a

Source code in packages/footman/src/livery/footman/_registry.py
def __init__(
    self,
    name: str,
    annotation: Any = bool,
    *,
    default: Any = None,
    config: bool | str = False,
    help: str = "",  # matches the manifest's vocabulary
) -> None:
    if name.startswith("-"):
        raise RegistrationError(
            f"GlobalOption({name!r}): give the bare name — the dashes are "
            f"the grammar's (and plugin globals are long-form only)"
        )
    self.name = cli_name(name)
    self.annotation = annotation
    self.default = default if annotation is not bool else bool(default)
    self.config = config
    self.help = help
    # Provenance the mount writes down (the entry-point identity), and
    # the config section resolved from it at discovery — the derivation
    # `config=` rides on.
    self._mounted: str | None = None
    self._section: str | None = None
    # The DEFINING module, never the importing capture: what a collision
    # names, what pairing and provenance key on.
    import sys as _sys

    frame = _sys._getframe(1)
    self.owner = frame.f_globals.get("__name__", "<unknown>")
    self._value: Any = _UNBOUND
    self._given = False
    self._frozen = False
    self._reads: set[str] = set()
    self._register()

__slots__ class-attribute instance-attribute

__slots__ = ('_frozen', '_given', '_mounted', '_reads', '_section', '_value', 'annotation', 'config', 'default', 'help', 'name', 'owner')

name instance-attribute

name: str = cli_name(name)

annotation instance-attribute

annotation: Any = annotation

default instance-attribute

default: Any = default if annotation is not bool else bool(default)

config instance-attribute

config: bool | str = config

help instance-attribute

help: str = help

owner instance-attribute

owner: str = frame.f_globals.get('__name__', '<unknown>')

value property

value: Any

The parsed value for this run — the flag's presence, the option's coerced value, or the default when the line didn't carry it. Frozen after parse; reading it outside a run is a taught error, because there is no invocation to have carried it.

given property

given: bool

Whether this option was named on the command line, with or without a value — the twin of value, and the half a value cannot express.

PROFILE = GlobalOption("profile", Path, default=Path("fm-profile.json"))
if PROFILE.given:            # `--profile` writes the default file,
    write_trace(PROFILE.value)   # no `--profile` writes nothing

Three outcomes from one declared value: absent, named, named with a value. value answers what, given answers whether anyone asked — and an env fallback fills the first without ever touching the second, so a caller who wants the environment alone to count can say so, and one who does not can say that instead.

__repr__

__repr__() -> str
Source code in packages/footman/src/livery/footman/_registry.py
def __repr__(self) -> str:
    state = repr(self._value) if self._frozen else "unbound"
    return f"<GlobalOption --{self.name} from {self.owner}: {state}>"

livery.footman.config_section

config_section(name: str) -> None

Name this provider module's config section — the <name> of [tool.footman.plugins.<name>] — instead of the entry-point derivation.

Module-level, beside the module's GlobalOptions. For an include()d module (no entry point to derive from), or a derivation that reads wrong or ugly. The name is claimed at discovery, so two providers naming one section refuse loudly, never resolve by order.

Source code in packages/footman/src/livery/footman/_registry.py
def config_section(name: str) -> None:
    """Name this provider module's config section — the `<name>` of
    `[tool.footman.plugins.<name>]` — instead of the entry-point derivation.

    Module-level, beside the module's `GlobalOption`s. For an `include()`d
    module (no entry point to derive from), or a derivation that reads
    wrong or ugly. The name is claimed at discovery, so two providers
    naming one section refuse loudly, never resolve by order."""
    import sys as _sys

    module = _sys._getframe(1).f_globals.get("__name__", "<unknown>")
    _CONFIG_SECTIONS[module] = cli_name(name)

livery.footman.wrap_task module-attribute

wrap_task: Final[HookRegistrar] = root.wrap_task

livery.footman.wrap_bind module-attribute

wrap_bind: Final[HookRegistrar] = root.wrap_bind

livery.footman.Invocation

Invocation(*, cli: dict[str, Any] | None = None, config: dict[str, Any] | None = None, root: str = '', cwd: str = '', tasks: Tasks | None = None, docs_url: str | None = None)

What one fm line is doing, handed to every lifecycle hook.

Editable only at pre_tasks; every later moment sees the same object with writes refused, so what a task-time hook reads is what the run decided.

Methods:

Name Description
freeze

Close the invocation for writes — called once, before tasks run.

__setattr__
__repr__

Attributes:

Name Type Description
__slots__
cli dict[str, Any]

The global options this line carried. Empty in the manifest refresh

config dict[str, Any]

The merged [tool.footman] configuration.

root str

The cascade root: the directory of the highest tasks.py.

cwd str

Where fm was invoked.

tasks Tasks | None

The merged command tree, as a Tasks view — the same surface a

docs_url str | None

The URL template task names link to, or None for no links.

results tuple[Any, ...]

The run's rows, in the order the work was created, as result

skipped tuple[Any, ...]

The skipped subset of results — what never ran because

total_ms float

Wall-clock for the whole run, the envelope's total_ms — filled

Source code in packages/footman/src/livery/footman/_invocation.py
def __init__(
    self,
    *,
    cli: dict[str, Any] | None = None,
    config: dict[str, Any] | None = None,
    root: str = "",
    cwd: str = "",
    tasks: Tasks | None = None,
    docs_url: str | None = None,
) -> None:
    object.__setattr__(self, "_frozen", False)
    self.docs_url = docs_url
    self.cli = dict(cli or {})
    """The global options this line carried. Empty in the manifest refresh
    child, which has no command line — so a tree edit that reads this would
    be reading nothing there, which is exactly why it must not."""
    self.config = dict(config or {})
    """The merged `[tool.footman]` configuration."""
    self.root = root
    """The cascade root: the directory of the highest `tasks.py`."""
    self.cwd = cwd
    """Where `fm` was invoked."""
    self.tasks = tasks
    """The merged command tree, as a `Tasks` view — the same surface a
    `TaskView` edit uses. Editable at `pre_tasks`, when a hook may disable a
    task, add a prerequisite, or read provenance."""
    self.results: tuple[Any, ...] = ()
    """The run's rows, in the order the work was created, as result
    views — filled for
    `post_tasks` (the run itself writes past the freeze; hooks read).
    Executions, `shared` rows, refusals and `skipped` nodes alike."""
    self.skipped: tuple[Any, ...] = ()
    """The `skipped` subset of `results` — what never ran because
    something it needed failed."""
    self.total_ms: float = 0.0
    """Wall-clock for the whole run, the envelope's `total_ms` — filled
    for `post_tasks`."""

__slots__ class-attribute instance-attribute

__slots__ = ('_docs_url', '_frozen', 'cli', 'config', 'cwd', 'results', 'root', 'skipped', 'tasks', 'total_ms')

cli instance-attribute

cli: dict[str, Any] = dict(cli or {})

The global options this line carried. Empty in the manifest refresh child, which has no command line — so a tree edit that reads this would be reading nothing there, which is exactly why it must not.

config instance-attribute

config: dict[str, Any] = dict(config or {})

The merged [tool.footman] configuration.

root instance-attribute

root: str = root

The cascade root: the directory of the highest tasks.py.

cwd instance-attribute

cwd: str = cwd

Where fm was invoked.

tasks instance-attribute

tasks: Tasks | None = tasks

The merged command tree, as a Tasks view — the same surface a TaskView edit uses. Editable at pre_tasks, when a hook may disable a task, add a prerequisite, or read provenance.

docs_url property writable

docs_url: str | None

The URL template task names link to, or None for no links.

Task names in --list, --tree and --help link to it, and each --json row carries the URL as docs_url: {path} is the task's address joined by slashes, {slug} joined by dashes. It starts as the configured docs-url. A pre_tasks hook may set it, for a plugin that knows where its task pages are; one that sets it only while it is None keeps a configured docs-url first. A hook runs on every invocation, so a template set there holds for each one, where a value set while a module imports would not, since a provider module imports once per process.

Raises:

Type Description
ValueError

on a write, a template footman cannot fill.

results instance-attribute

results: tuple[Any, ...] = ()

The run's rows, in the order the work was created, as result views — filled for post_tasks (the run itself writes past the freeze; hooks read). Executions, shared rows, refusals and skipped nodes alike.

skipped instance-attribute

skipped: tuple[Any, ...] = ()

The skipped subset of results — what never ran because something it needed failed.

total_ms instance-attribute

total_ms: float = 0.0

Wall-clock for the whole run, the envelope's total_ms — filled for post_tasks.

freeze

freeze() -> None

Close the invocation for writes — called once, before tasks run.

Source code in packages/footman/src/livery/footman/_invocation.py
def freeze(self) -> None:
    """Close the invocation for writes — called once, before tasks run."""
    object.__setattr__(self, "_frozen", True)

__setattr__

__setattr__(name: str, value: Any) -> None
Source code in packages/footman/src/livery/footman/_invocation.py
def __setattr__(self, name: str, value: Any) -> None:
    if getattr(self, "_frozen", False):
        raise Frozen(
            f"inv.{name} cannot be set now: the invocation is editable only "
            f"at pre_tasks, before anything runs. Per-task state belongs on "
            f"task.state, and per-task environment on ctx.env."
        )
    object.__setattr__(self, name, value)

__repr__

__repr__() -> str
Source code in packages/footman/src/livery/footman/_invocation.py
def __repr__(self) -> str:
    shape = "frozen" if self._frozen else "editable"
    return f"<Invocation {shape} cwd={self.cwd!r}>"

livery.footman.Tasks

Tasks(root: Group)

A hook's view of the merged command tree: iterate every task, or look one up by its address, each as a TaskView.

Methods:

Name Description
__iter__
get

The task at name — its full dotted address — or None.

__getitem__
__contains__
Source code in packages/footman/src/livery/footman/_registry.py
def __init__(self, root: Group) -> None:
    self._root = root

__iter__

__iter__() -> Iterator[TaskView]
Source code in packages/footman/src/livery/footman/_registry.py
def __iter__(self) -> Iterator[TaskView]:
    yield from _task_views(self._root)

get

get(name: str) -> TaskView | None

The task at name — its full dotted address — or None.

Addresses are unique by construction (a name is a task or a group at each level, never both), so this either finds one task or finds none: there is nothing here to be ambiguous about. A bare leaf is not an address — get("build") finds a top-level build, never docs.build. To search by leaf, iterate: two tasks may answer to one, and picking between them is the caller's to make, not footman's to guess.

A runnable group answers whatever its default answers, so get("lint") is get("lint.default") — the bare group name is that action's other spelling on the command line, and lookup would otherwise be the one place that isn't true.

Source code in packages/footman/src/livery/footman/_registry.py
def get(self, name: str) -> TaskView | None:
    """The task at *name* — its full dotted address — or `None`.

    Addresses are unique by construction (a name is a task or a group
    at each level, never both), so this either finds one task or finds
    none: there is nothing here to be ambiguous about. A bare leaf is
    not an address — `get("build")` finds a top-level `build`, never
    `docs.build`. To search by leaf, iterate: two tasks may answer to
    one, and picking between them is the caller's to make, not
    footman's to guess.

    A runnable group answers whatever its default answers, so
    `get("lint")` is `get("lint.default")` — the bare group name is
    that action's other spelling on the command line, and lookup would
    otherwise be the one place that isn't true.
    """
    by_address = {v.address: v for v in self}
    if (view := by_address.get(name)) is not None:
        return view
    return by_address.get(f"{name}.default")

__getitem__

__getitem__(name: str) -> TaskView
Source code in packages/footman/src/livery/footman/_registry.py
def __getitem__(self, name: str) -> TaskView:
    if (view := self.get(name)) is None:
        raise KeyError(name)
    return view

__contains__

__contains__(name: object) -> bool
Source code in packages/footman/src/livery/footman/_registry.py
def __contains__(self, name: object) -> bool:
    return isinstance(name, str) and self.get(name) is not None

livery.footman.TaskView

TaskView(fn: Task, name: str, group: Group | None = None, *, path: tuple[str, ...] | None = None)

A hook's handle on one task: read its wiring, its policy flags, and its cascade provenance (where it was defined, what it overrode), and edit it here — never through the private _footman_* attributes.

Methods:

Name Description
add_pre

Prepend prerequisites (views or functions), skipping any already set.

add_post

Append post-tasks (views or functions), skipping any already set.

disable

Mark the task unavailable — listed with reason, refused if run.

set_opts

Set orchestration options on the task permanently, for every use —

Attributes:

Name Type Description
fn

The task function itself — the escape hatch past the view.

name

The task's leaf name, e.g. build. The whole spelling is

group

The group this task lives in, or None for a top-level task — its

path tuple[str, ...]

Every segment of the task's address, leaf last — `("forge", "dev",

address str

The task's full dotted address, exactly as the command line spells

mounted_from str | None

Which provider this task came from — the footman.tasks

pre tuple[Task, ...]

The prerequisites that run before this task.

post tuple[Task, ...]

The tasks that run after this one.

disabled str | None

Why the task is unavailable here, or None if it can run.

keep_going bool | None

The task's declared failure policy (@task(keep_going=…)), or None

atomic bool

Whether the task's subprocesses opt out of fail-fast's kill.

infinite bool

Whether the task runs until stopped (@task(infinite=True)).

interactive bool

Whether the task owns the real terminal (@task(interactive=True)).

hidden bool | None

The task's own hidden= answer, or None when it inherits one.

timed bool

Whether the task records timing history / shows a determinate bar —

confirm str

The @task(confirm="…") prompt gating the task, or "" if none.

defining_dir str | None

The folder the task was defined in, or None when the cascade did

shadowed Task | None

The task this one overrides — same name, one cascade level up — or

shadow_chain tuple[Task, ...]

This task and every task it shadows, nearest (this one) first.

source_file str | None

The file the task's function is defined in, or None when it can't

Source code in packages/footman/src/livery/footman/_registry.py
def __init__(
    self,
    fn: Task,
    name: str,
    group: Group | None = None,
    *,
    path: tuple[str, ...] | None = None,
) -> None:
    self.fn = fn
    """The task function itself — the escape hatch past the view."""
    self.name = name
    """The task's leaf name, e.g. `build`. The whole spelling is
    `address` — two tasks in different groups share this one."""
    self.group = group
    """The group this task lives in, or `None` for a top-level task — its
    `.name` is the group's command-line spelling (e.g. `docs`)."""
    # A group has no parent pointer, deliberately: `include()`/`plugin()`
    # can mount one group object in more than one place, so an address
    # belongs to the *view* the walk yields, not to the group or the
    # function. The walk passes it; the fallback is for a hand-built view
    # (a test), where the immediate group is all there is to go on.
    self._path = path or ((group.name, name) if group else (name,))

fn instance-attribute

fn = fn

The task function itself — the escape hatch past the view.

name instance-attribute

name = name

The task's leaf name, e.g. build. The whole spelling is address — two tasks in different groups share this one.

group instance-attribute

group = group

The group this task lives in, or None for a top-level task — its .name is the group's command-line spelling (e.g. docs).

path property

path: tuple[str, ...]

Every segment of the task's address, leaf last — ("forge", "dev", "up"). address is the same thing as one string.

address property

address: str

The task's full dotted address, exactly as the command line spells it: forge.dev.up. Unique across the tree — a name is a task or a group at each level, never both — so this is the key to hold a task by, and what Tasks.get looks up.

mounted_from property

mounted_from: str | None

Which provider this task came from — the footman.tasks entry-point identity for plugin(), the module name for include() — or None when the tasks file defines it itself, which is the honest answer: the project owns it.

Language-neutral by construction: it names a provider, not a file, so it keeps answering for a task that is one day not a Python function. A group carries the same field only when it was grafted whole; the moment a mount composes into a group that already exists, the group is shared and answers None while every task under it still answers exactly. Read ownership here.

pre property

pre: tuple[Task, ...]

The prerequisites that run before this task.

post property

post: tuple[Task, ...]

The tasks that run after this one.

disabled property

disabled: str | None

Why the task is unavailable here, or None if it can run.

keep_going property

keep_going: bool | None

The task's declared failure policy (@task(keep_going=…)), or None when it left the choice to the command line / the built-in default.

atomic property

atomic: bool

Whether the task's subprocesses opt out of fail-fast's kill.

infinite property

infinite: bool

Whether the task runs until stopped (@task(infinite=True)).

interactive property

interactive: bool

Whether the task owns the real terminal (@task(interactive=True)).

hidden property

hidden: bool | None

The task's own hidden= answer, or None when it inherits one.

Read the declaration, not the resolved answer: a hook that hides a group wants to know whether this task overrode it.

timed property

timed: bool

Whether the task records timing history / shows a determinate bar — @task(progress=False) (and infinite/interactive) opt out.

confirm property

confirm: str

The @task(confirm="…") prompt gating the task, or "" if none.

defining_dir property

defining_dir: str | None

The folder the task was defined in, or None when the cascade did not tag it (a plugin- or include()-composed task, not a cascade file). Use it to act on tasks from one subtree of a monorepo.

shadowed property

shadowed: Task | None

The task this one overrides — same name, one cascade level up — or None if it shadows nothing.

shadow_chain property

shadow_chain: tuple[Task, ...]

This task and every task it shadows, nearest (this one) first.

source_file property

source_file: str | None

The file the task's function is defined in, or None when it can't be located (a built-in or dynamically constructed function).

add_pre

add_pre(*tasks: TaskView | Task) -> None

Prepend prerequisites (views or functions), skipping any already set.

Source code in packages/footman/src/livery/footman/_registry.py
def add_pre(self, *tasks: TaskView | Task) -> None:
    """Prepend prerequisites (views or functions), skipping any already set."""
    have = list(pre_deps(self.fn))
    setattr(
        self.fn,
        _PRE,
        [*(f for t in tasks if (f := _as_fn(t)) not in have), *have],
    )

add_post

add_post(*tasks: TaskView | Task) -> None

Append post-tasks (views or functions), skipping any already set.

Source code in packages/footman/src/livery/footman/_registry.py
def add_post(self, *tasks: TaskView | Task) -> None:
    """Append post-tasks (views or functions), skipping any already set."""
    have = list(post_deps(self.fn))
    setattr(
        self.fn,
        _POST,
        [*have, *(f for t in tasks if (f := _as_fn(t)) not in have)],
    )

disable

disable(reason: str) -> None

Mark the task unavailable — listed with reason, refused if run.

Source code in packages/footman/src/livery/footman/_registry.py
def disable(self, reason: str) -> None:
    """Mark the task unavailable — listed with *reason*, refused if run."""
    _gate(lambda: reason)(self.fn)

set_opts

set_opts(**overrides: Unpack[TaskOpts]) -> None

Set orchestration options on the task permanently, for every use — the discovery-time counterpart to a per-use .opts(). Takes the same options (TaskOpts, the whole .opts() set) and rejects a task parameter with the same taught error; the difference is that it edits the registered task rather than a per-use proxy, so a hook can set a policy across a whole class of tasks. A command-line -k/--fail-fast still wins over a set keep_going.

Source code in packages/footman/src/livery/footman/_registry.py
def set_opts(self, **overrides: Unpack[TaskOpts]) -> None:
    """Set orchestration options on the task **permanently, for every use** —
    the discovery-time counterpart to a per-use `.opts()`. Takes the same
    options (`TaskOpts`, the whole `.opts()` set) and rejects a task
    parameter with the same taught error; the difference is that it edits
    the registered task rather than a per-use proxy, so a hook can set a
    policy across a whole class of tasks. A command-line `-k`/`--fail-fast`
    still wins over a set `keep_going`."""
    for attr, value in _opts_overrides(dict(overrides)).items():
        setattr(self.fn, attr, value)

Custom CLI

livery.footman.App

App(name: str = 'footman', prog: str = 'fm', version: str | None = None, tasks_file: str = 'tasks.py', dist: str | None = None, cache_dir: Path | str | None = None, data_dir: Path | str | None = None, env_prefix: str | None = None, config_name: str | None = None, builtin: Sequence[str] = ())

A branded footman CLI — call run from your console-script entry.

One App serves a process: run points module-level state (the brand, its locations) at this brand and deliberately never restores it — a process runs one brand, and run may not return at all (the uv handoff re-execs). Driving two brands from one process is supported only through footman.testing.Runner, which saves and restores around each invocation.

Methods:

Name Description
run

Resolve and run the CLI, returning the process exit code.

Attributes:

Name Type Description
brand Brand
Source code in packages/footman/src/livery/footman/_application.py
def __init__(
    self,
    name: str = "footman",
    prog: str = "fm",
    version: str | None = None,
    tasks_file: str = "tasks.py",
    dist: str | None = None,
    cache_dir: Path | str | None = None,
    data_dir: Path | str | None = None,
    env_prefix: str | None = None,
    config_name: str | None = None,
    builtin: Sequence[str] = (),
) -> None:
    # The stock pins: an `App` that kept the `fm` command *is* stock
    # footman, and stock pins the long words its two-letter command
    # cannot derive — `FOOTMAN_*` variables, `footman.toml` config. The
    # moment `prog` moves, the pins stop applying and a brand derives
    # from its own command (pin `env_prefix=` / `config_name=` to
    # differ). Without this, a bare `App()` would read `FM_CONFIG` and
    # `[tool.fm]` while the `fm` on PATH reads footman's.
    if prog == "fm":
        env_prefix = env_prefix or "FOOTMAN"
        config_name = config_name or "footman"
    # `dist` is opt-in for a branded CLI: footman cannot guess which
    # distribution ships someone else's runner, and a wrong guess would
    # hand a user's invocation to an environment without it. Unset, the
    # handoffs stay out of the way (documented in custom-cli.md).
    self.brand = Brand(
        name=name,
        prog=prog,
        version=version or __version__,
        tasks_file=tasks_file,
        dist=dist,
        cache_dir=Path(cache_dir).expanduser() if cache_dir is not None else None,
        data_dir=Path(data_dir).expanduser() if data_dir is not None else None,
        env_prefix=env_prefix,
        config_name=config_name,
        builtin=tuple(builtin),
    )

brand instance-attribute

brand: Brand = Brand(name=name, prog=prog, version=version or __version__, tasks_file=tasks_file, dist=dist, cache_dir=Path(cache_dir).expanduser() if cache_dir is not None else None, data_dir=Path(data_dir).expanduser() if data_dir is not None else None, env_prefix=env_prefix, config_name=config_name, builtin=tuple(builtin))

run

run(argv: list[str] | None = None) -> int

Resolve and run the CLI, returning the process exit code.

Handles the stdlib-only --complete hot path before importing the framework, so completion stays fast even through a custom entry point.

Source code in packages/footman/src/livery/footman/_application.py
def run(self, argv: list[str] | None = None) -> int:
    """Resolve and run the CLI, returning the process exit code.

    Handles the stdlib-only `--complete` hot path before importing the
    framework, so completion stays fast even through a custom entry point.
    """
    args = list(sys.argv[1:] if argv is None else argv)
    # Locations first, and on both paths: the completion hot path reads
    # this brand's cache exactly as the execution path writes it.
    self.brand.install()
    if args and args[0] == "--complete":
        from livery.footman._complete import complete_cli

        return complete_cli(args[1:])
    # A process started without a stream (the caller closed the fd;
    # pythonw) gets `None` for it, and every later touch — the
    # scheduler's isatty, the uv handoff's flush, a body's print —
    # becomes an AttributeError traceback. A stream nobody connected
    # means "discard", so it is wired to devnull once, here, and the
    # whole run downstream never has to ask.
    import os as _os

    if sys.stdout is None:
        sys.stdout = open(_os.devnull, "w", encoding="utf-8")  # noqa: SIM115
    if sys.stderr is None:
        sys.stderr = open(_os.devnull, "w", encoding="utf-8")  # noqa: SIM115
    try:
        _os.getcwd()
    except OSError:
        # A shell sitting in a directory another process deleted: every
        # later step needs a cwd (discovery, config, the cache key), and
        # each used to fail as its own raw FileNotFoundError traceback.
        # One taught line, at the door.
        print(
            f"{self.brand.prog}: the working directory no longer exists "
            f"— cd to a real directory and try again",
            file=sys.stderr,
        )
        return 1
    from livery.footman import _app

    code = _app.run(args, brand=self.brand)
    try:
        sys.stdout.flush()
    except BrokenPipeError:
        # The reader hung up mid-run (`fm … | head`). Flushing here, and
        # pointing fd 1 at devnull for the interpreter's own shutdown
        # flush, keeps "Exception ignored while flushing sys.stdout" off
        # the screen; the code is what a SIGPIPE-default tool reports.
        import contextlib

        with contextlib.suppress(Exception):
            devnull = _os.open(_os.devnull, _os.O_WRONLY)
            _os.dup2(devnull, sys.stdout.fileno())
        code = code or 141
    return code

livery.footman.Brand dataclass

Brand(name: str = 'footman', prog: str = 'fm', version: str = __version__, tasks_file: str = 'tasks.py', dist: str | None = 'livery-footman', cache_dir: Path | None = None, data_dir: Path | None = None, env_prefix: str | None = None, config_name: str | None = None, builtin: tuple[str, ...] = ())

The names a CLI shows the user, and where it keeps its things.

name is the long / display name (the --version banner); prog is the short command name (the error prefix and hints); version is your version string; tasks_file is the filename your users write tasks in (config tasks still overrides it per project).

dist is the distribution that ships your CLI — the name a user would pip install. It is what the handoffs reason about: which package a project's lockfile must pin, and which one a tasks file carrying its own PEP 723 dependencies must declare. Left None (the default for a custom brand), both handoffs simply stay out of your way.

cache_dir and data_dir are the two folders this CLI keeps things in, and you place them, so footman never guesses at your product's layout:

acme_home = Path(os.environ.get("ACME_HOME", Path.home() / ".acme"))
cache_dir=acme_home / ".cache" / "acme-cli",
data_dir=acme_home / "acme-cli",

They are not anchored to each other — put them wherever each belongs in your world. Cache is derived data, safe to delete, and the collector sweeps it; data is durable and machine-local (credentials, tokens, generated assets) and is never collected. footman refuses to start if the two name the same directory, because that would point the collector at things it must not delete.

<PREFIX>_CACHE_DIR and <PREFIX>_DATA_DIR override them at run time, which is how two installations run side by side under different identities. Left unset with those variables unset, both fall back to XDG — ~/.cache/acme and ~/.local/share/acme.

Task authors never see any of this: they call footman.cache_dir() and footman.data_dir() and get a directory that exists.

env_prefix is the namespace for every variable this CLI reads, and defaults to prog uppercased: the command is acme, so the variables are ACME_*. A branded CLI reads only its own prefix, so a stray FOOTMAN_CACHE_DIR can never move someone else's product.

Set it explicitly for either of two reasons. A terse command makes a poor variable: footman's own is fm, but its variables are FOOTMAN_*, because FOOTMAN_CACHE_DIR tells a reader who has never heard of the tool what it belongs to and FM_CACHE_DIR tells them nothing. Or the namespace collides with your product's own — keeping it clear is yours to arrange.

config_name names the standalone config file (acme.toml), the table inside pyproject.toml ([tool.acme]), and the user-level config corner (~/.config/acme/), from one field so the three cannot drift apart. It defaults to prog — the machine word your users already type, the same rule the env prefix follows — never the display name, which is free text ([tool."Acme DevKit"] is nothing anyone would write, and a capitalised table is one nobody would find). Set it when the identity your users should write isn't the command: footman's own command is fm, but its config is footman.toml, pinned for the same reason its variables are FOOTMAN_*. The user-level config file is not placed by the brand: it stays at ~/.config/acme/config.toml, where a user looks for their own settings, with <PREFIX>_CONFIG naming another.

Methods:

Name Description
env

This brand's spelling of an environment variable: ACME_CACHE_DIR.

config_file

This brand's standalone config filename — acme.toml.

install

Point the process's locations at this brand — the one call the

Attributes:

Name Type Description
name str
prog str
version str
tasks_file str
dist str | None
cache_dir Path | None
data_dir Path | None
env_prefix str | None
config_name str | None
builtin tuple[str, ...]

The brand's own task surface where there is no project — a tuple of

prefix str

The environment-variable namespace — env_prefix, else from prog.

config_stem str

The config identity — config_name, else prog: the acme of

name class-attribute instance-attribute

name: str = 'footman'

prog class-attribute instance-attribute

prog: str = 'fm'

version class-attribute instance-attribute

version: str = __version__

tasks_file class-attribute instance-attribute

tasks_file: str = 'tasks.py'

dist class-attribute instance-attribute

dist: str | None = 'livery-footman'

cache_dir class-attribute instance-attribute

cache_dir: Path | None = None

data_dir class-attribute instance-attribute

data_dir: Path | None = None

env_prefix class-attribute instance-attribute

env_prefix: str | None = None

config_name class-attribute instance-attribute

config_name: str | None = None

builtin class-attribute instance-attribute

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

The brand's own task surface where there is no project — a tuple of footman.tasks entry-point names, mounted as the base of the tree exactly when discovery finds no project task files. The ladder is project > user > built-in: a project ignores the base outright (its tasks file mounts what it wants — nothing is privileged, nothing lost), and the user tasks file overlays it. Strings, never live objects: the detached refresh child rebuilds manifests in a bare process, and a name rides argv where an object cannot. Curate a small global surface — what does this CLI offer someone with no project? — rather than aiming it at the everyday tasks, which belong where their probes work.

prefix property

prefix: str

The environment-variable namespace — env_prefix, else from prog.

config_stem property

config_stem: str

The config identity — config_name, else prog: the acme of acme.toml, [tool.acme] and ~/.config/acme/.

env

env(suffix: str) -> str

This brand's spelling of an environment variable: ACME_CACHE_DIR.

Source code in packages/footman/src/livery/footman/_application.py
def env(self, suffix: str) -> str:
    """This brand's spelling of an environment variable: `ACME_CACHE_DIR`."""
    return f"{self.prefix}_{suffix}"

config_file

config_file() -> str

This brand's standalone config filename — acme.toml.

Source code in packages/footman/src/livery/footman/_application.py
def config_file(self) -> str:
    """This brand's standalone config filename — `acme.toml`."""
    return f"{self.config_stem}.toml"

install

install() -> None

Point the process's locations at this brand — the one call the real entry (App.run) and the embedded harness (Runner.invoke) both make, so the two can never configure different worlds (they once each listed the fields by hand, and grew apart by three).

Source code in packages/footman/src/livery/footman/_application.py
def install(self) -> None:
    """Point the process's locations at this brand — the one call the
    real entry (`App.run`) and the embedded harness (`Runner.invoke`)
    both make, so the two can never configure different worlds (they
    once each listed the fields by hand, and grew apart by three)."""
    from livery.footman import _paths

    _paths.configure(
        prefix=self.prefix,
        cache_dir=self.cache_dir,
        data_dir=self.data_dir,
        config_name=self.config_stem,
        tasks_file=self.tasks_file,
        prog=self.prog,
        brand_version=self.version,
        builtin=self.builtin,
        dist=self.dist,
    )

livery.footman.main

main(tasks_file: str | None = None) -> None

Console-script entry for footman and fm.

tasks_file makes a tasks file its own command. Ending a file with

if __name__ == "__main__":
    footman.main(__file__)

turns it into a runnable script — ./deploy.py build — reading its own tasks whatever the directory, which is what pairs with a PEP 723 header and a #!/usr/bin/env -S uv run --script shebang. An explicit -f on the command line still wins.

Source code in packages/footman/src/livery/footman/__init__.py
def main(tasks_file: str | None = None) -> None:
    """Console-script entry for `footman` and `fm`.

    `tasks_file` makes a tasks file its own command. Ending a file with

        if __name__ == "__main__":
            footman.main(__file__)

    turns it into a runnable script — `./deploy.py build` — reading its own
    tasks whatever the directory, which is what pairs with a PEP 723
    header and a `#!/usr/bin/env -S uv run --script` shebang. An explicit
    `-f` on the command line still wins.
    """
    import sys

    argv = sys.argv[1:]
    if argv and argv[0] == "--complete":
        # Still first: the hot path answers before anything else is decided,
        # and `footman.app` (with its dataclass machinery) stays off a TAB
        # press entirely. `_paths`' module defaults *are* stock footman's
        # locations — except the built-ins, which live on the `App` below
        # and no default can know. Telling `_paths` about them is two
        # attribute writes, and without it the hot path cannot see that a
        # project-less directory has a global tree at all: the fallback is
        # skipped, the refresh child writes nothing, and every TAB in a
        # directory like $HOME pays the full cold bound for empty output.
        from livery.footman import _paths
        from livery.footman._complete import complete_cli

        # `brand_version` too, not just the built-ins: the global-mode
        # manifest is keyed by (prog, version, builtins), and the execution
        # path configures the real version — leaving the default "" here
        # would give completion and execution two different global caches.
        _paths.configure(builtin=BUILTIN, brand_version=__version__)
        raise SystemExit(complete_cli(argv[1:]))
    # Past the hot path, so the TAB press above pays nothing for it (and
    # `_complete` writes bytes anyway): everything from here on prints text,
    # and a locale-encoded stdout defaults to errors='strict'. A task name, a
    # docstring, `--tree`'s own branch glyphs or the em dash in a header is
    # then unencodable on an ascii or cp1252 console, and a listing dies
    # half-written with a raw UnicodeEncodeError. Degrade those glyphs to '?'
    # instead. This is the same reconfigure `context.routing()` installs
    # around a run — hoisted here so the listings, which never start one, are
    # covered too.
    import contextlib

    for stream in (sys.stdout, sys.stderr):
        with contextlib.suppress(Exception):
            # getattr, not hasattr-then-call: hasattr narrowing is not
            # portable across checkers, the getattr is.
            reconfigure = getattr(stream, "reconfigure", None)
            if reconfigure is not None:
                reconfigure(errors="replace", line_buffering=True)
    if tasks_file is not None and not any(
        a.startswith(("-f=", "--tasks-file=")) for a in argv
    ):
        argv = [f"--tasks-file={tasks_file}", *argv]
    # Past the completion hot path, this process exists to run one command and
    # exit, so it should not spend its startup collecting garbage it has not
    # made yet. `_globals` turns the collector back on — with everything
    # loaded by then frozen — at the last moment before task bodies run.
    from livery.footman import _globals
    from livery.footman._application import App

    _globals.defer_gc()

    # `dist` names the distribution this console script ships in — what a
    # project's lockfile pins, and what a tasks file carrying its own
    # dependencies must declare. A branded CLI passes its own.
    #
    # The stock pins — `FOOTMAN_*` variables, `footman.toml` config, the
    # long words a two-letter command cannot derive — are `App`'s own: any
    # `App` that keeps the `fm` command gets them, this one included.
    # `fm self.*` in an empty directory: footman declares its own built-in,
    # the same way any branded CLI would.
    raise SystemExit(App(dist="livery-footman", builtin=BUILTIN).run(argv))

Typed-parameter helpers

livery.footman.Many module-attribute

Many = list

livery.footman.Arg module-attribute

Arg = Annotated[_T, _arg]

An optional trailing positional, via Annotated-alias:

@task
def files(pattern: Arg[str] = "*"): ...

fm files src fills the positional; a bare fm files runs on the default. The grammar is deterministic and greedy: when a bare word follows, it is the value — never re-interpreted as the next task, no name-peeking — and capped at one token. To run the task argument-less ahead of another, say so with the explicit boundary: fm files + build. An Arg needs a default (absence must mean something), takes at most one token (use a list parameter for many), and must trail every required positional.

Arg is the one exception to the rule that sorts every other parameter: the default decides — no default makes a required positional, a default makes an option you pass by name. Arg says "keep me a positional even though I have a default", which is why it needs the greedy-but-capped grammar above. The rules it is bending are laid out in the typing guide.

livery.footman.Forward module-attribute

Forward = Annotated[_T, forward]

Shorthand for Annotated[T, forward], like Many[T] is for a list:

@task(pre=[build, lint])
def check(fix: Forward[bool] = False): ...

Forward[bool] expands to Annotated[bool, forward] — the same marker, less noise on a signature full of forwarded parameters. See forward.

livery.footman.forward module-attribute

forward: Final[ForwardMarker] = ForwardMarker()

Forward this parameter to the tasks this task dispatches, via Annotated:

@task(pre=[build, lint])
def check(fix: Annotated[bool, forward] = False): ...

A forward-marked parameter's value is passed to every task this one dispatches — its pre/post prerequisites, and a runnable group's fan-out — that declares a parameter of the same name; tasks that don't declare it run on their own defaults. The forwarded value overrides the callee's default, chains through callees that re-declare the marker, and may satisfy a defaultless parameter — the same courtesy ask() and stdin extend, so a receiver never needs a fake default just to be reachable. Presence travels beside the value, so given() reads the same sentence in the dispatcher and in what it dispatched.

livery.footman.NoSplit module-attribute

NoSplit = Annotated[_T, nosplit]

Shorthand for Annotated[T, nosplit]: NoSplit[list[str]] opts a collection out of comma-splitting (see nosplit).

livery.footman.nosplit module-attribute

nosplit: Final[NoSplitMarker] = NoSplitMarker()

Opt a list/dict parameter OUT of comma-splitting, via Annotated:

def build(names: Annotated[list[str], nosplit] = ()): ...

By default a collection parameter splits a single token on commas (--tag a,b,c -> ["a", "b", "c"]) in addition to the repeatable form (--tag a --tag b). Mark it nosplit when a value may itself contain a comma: then only the repeated flag adds items and --name "a,b" stays the literal "a,b". NoSplit[list[str]] is the terser spelling of the same thing.

livery.footman.Hidden module-attribute

Hidden = Annotated[_T, hidden]

Shorthand for Annotated[T, hidden]: Hidden[str] keeps a parameter out of the listings while it still binds and completes (see hidden).

livery.footman.hidden module-attribute

hidden: Final[HiddenMarker] = HiddenMarker()

Keep a parameter out of the listings a human reads, via Annotated:

def deploy(target: str, legacy: Annotated[str, hidden] = ""): ...

It means on a parameter what hidden=True means on a task. --help does not list it and the synthesised example does not use it, but it still binds, still completes, and --all reveals it. The manifest marks it rather than dropping it, so an agent reading --describe still learns it exists — hiding and completing are different questions, and a long machine-facing flag is the one you most want spelled for you.

For a deprecated flag kept working but unadvertised, a debug switch, or a flag a wrapper script passes. Hidden[str] is the terser spelling.

livery.footman.suggest

suggest(fn: Callable[[], Any], *, strict: bool = True)

Attach a dynamic completer to a parameter, via Annotated:

def build(project: Annotated[str, suggest(list_projects)]): ...

list_projects() -> list[str] returns the candidate values. footman runs it on the execution path — refreshing a cache the completion hot path serves — and, when strict (the default), validates the supplied value against a fresh call. The wrapper is required: a bare callable in Annotated is refused, so a marker that happens to be callable can never be mistaken for a completer.

Attributes:

Name Type Description
__slots__
fn Callable[[], Any]
strict bool
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, fn: Callable[[], Any], *, strict: bool = True) -> None:
    self.fn = fn
    self.strict = strict

__slots__ class-attribute instance-attribute

__slots__ = ('fn', 'strict')

fn instance-attribute

fn: Callable[[], Any] = fn

strict instance-attribute

strict: bool = strict

livery.footman.exists module-attribute

exists: Final[PathRequirement] = PathRequirement('exists', 'exists')

Require a Path parameter to name something that exists on disk:

def rm(target: Annotated[Path, exists]): ...

Validated eagerly (at parse time) with a taught error. See also isfile and isdir.

livery.footman.isfile module-attribute

isfile: Final[PathRequirement] = PathRequirement('file', 'isfile')

Require a Path parameter to name an existing file (see exists).

livery.footman.isdir module-attribute

isdir: Final[PathRequirement] = PathRequirement('dir', 'isdir')

Require a Path parameter to name an existing directory (see exists).

livery.footman.Exists module-attribute

Exists = Annotated[Path, exists]

Shorthand for Annotated[Path, exists] — target: Exists requires the path to exist. Type-fixed to Path; use Annotated directly for a list[Path].

livery.footman.IsFile module-attribute

IsFile = Annotated[Path, isfile]

Shorthand for Annotated[Path, isfile]: require an existing file.

livery.footman.IsDir module-attribute

IsDir = Annotated[Path, isdir]

Shorthand for Annotated[Path, isdir]: require an existing directory.

livery.footman.matching

matching(pattern: str)

Narrow a Path parameter's Tab completion to a glob:

def load(env_file: Annotated[Path, matching(".env*")] = Path(".env")): ...

footman cannot complete paths itself — it answers from a cached manifest and never touches the filesystem — so a path value is handed to the shell's own file completion. This is what it hands along: the pattern the shell filters by, so --env-file offers .env and .env.local rather than every file in the directory.

Directories are always offered whatever the pattern says, or a match one level down would be unreachable. The glob matches the file's name (*.json, not **/*.json) — the vocabulary all five shells share.

Completion only. It narrows what Tab shows; it does not reject a value typed anyway — that is check()'s job, or exists/isfile's. A completion filter that quietly became validation would refuse the perfectly good path someone pasted.

Methods:

Name Description
__repr__

Attributes:

Name Type Description
__slots__
pattern str
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, pattern: str) -> None:
    if not pattern:
        raise ValueError("matching() needs a glob, e.g. matching('*.json')")
    self.pattern = pattern

__slots__ class-attribute instance-attribute

__slots__ = ('pattern',)

pattern instance-attribute

pattern: str = pattern

__repr__

__repr__() -> str
Source code in packages/footman/src/livery/footman/_params.py
def __repr__(self) -> str:
    return f"matching({self.pattern!r})"

livery.footman.between

between(lo: float | None, hi: float | None)

Inclusive numeric bounds for an int/float parameter:

def test(jobs: Annotated[int, between(1, 32)] = 4): ...

Validated eagerly with a taught error (--jobs must be between 1 and 32). Either bound may be None for open-ended ranges. A bare range in Annotated also works for ints, with Python's half-open semantics (range(0, 8) accepts 0 through 7).

Attributes:

Name Type Description
__slots__
lo float | None
hi float | None
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, lo: float | None, hi: float | None) -> None:
    self.lo = lo
    self.hi = hi

__slots__ class-attribute instance-attribute

__slots__ = ('hi', 'lo')

lo instance-attribute

lo: float | None = lo

hi instance-attribute

hi: float | None = hi

livery.footman.env

env(var: str)

Fall back to an environment variable when the option isn't given:

def deploy(target: Annotated[str, env("DEPLOY_ENV")] = "staging"): ...

Precedence is CLI > $DEPLOY_ENV > default. The env value flows through the same coercion and validation as a command-line token. Only valid on a parameter with a default — an env fallback makes it optional, so it needs somewhere to fall. A body call that omits the parameter reads the same ladder; a value passed explicitly wins over env, however the task was asked for.

Attributes:

Name Type Description
__slots__
var str
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, var: str) -> None:
    self.var = var

__slots__ class-attribute instance-attribute

__slots__ = ('var',)

var instance-attribute

var: str = var

livery.footman.check

check(fn: Callable[..., Any])

A custom validator, run after coercion; raise ValueError to reject:

def tag(version: Annotated[str, check(semver)]): ...

The callable receives the coerced value (each element, for collections). Its ValueError message is shown to the user, so write it for them.

Declare a second parameter to also receive the siblings — the parameters to this one's left at their effective values (a provided value, else the parameter's own default), coerced and read-only (empty for the first parameter) — so a check can validate against another input:

def newer(v, params):
    current = current_version(params["name"])   # the package named earlier
    if Version(v) <= current:
        raise ValueError(f"must be newer than {current}")

def release(name: str, version: Annotated[str, check(newer)]): ...

Attributes:

Name Type Description
__slots__
fn Callable[..., Any]
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, fn: Callable[..., Any]) -> None:
    self.fn = fn

__slots__ class-attribute instance-attribute

__slots__ = ('fn',)

fn instance-attribute

fn: Callable[..., Any] = fn

livery.footman.default

default(fn: Callable[..., Any])

Compute a parameter's default when the task runs, via Annotated:

def install(shell: Annotated[str, default(detect_shell)] = ""): ...

A Python default is evaluated once, at import — fine for a constant, wrong for anything that depends on the machine, the environment or the clock. default(fn) calls fn() at bind time instead, so --help and the run agree and both are current.

It sits in the ladder just above the Python default — CLI value > env > default(fn) > the declared default — and, like env(), it needs a declared default to sit on: a plain Python call of the task, outside any run, has to keep working.

Declare one positional argument and it receives the sibling parameters resolved so far — the same courtesy check(fn) gets, and for the same reason: a default is often a function of the inputs beside it.

def cast(*, shell: str = "zsh",
         title: Annotated[str, default(lambda p: f"{p['shell']} · x")] = ""): ...

Read-only, and only what is to its left in the signature. The view holds effective values — what each parameter will actually be — and only a left one has that yet, which is also why a cycle cannot be written down: the signature fixes a total order and binding walks it. Reaching rightwards is a taught error, through p["x"] and p.get("x") alike. --help cannot show such a default — there is no invocation to read — so it shows none rather than one it would have to invent.

The value is used as it comes back, not coerced: fn() returns a real object, and coercion exists because the command line only has strings. It still runs the annotation's validators, so a default(fn) that would be refused as a typed value is refused here too rather than smuggled in.

Attributes:

Name Type Description
__slots__
fn Callable[..., Any]
reads_siblings bool

Whether fn takes the sibling view. Decided once, here, because both the

Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, fn: Callable[..., Any]) -> None:
    self.fn = fn
    self.reads_siblings = _takes_an_argument(fn)

__slots__ class-attribute instance-attribute

__slots__ = ('fn', 'reads_siblings')

fn instance-attribute

fn: Callable[..., Any] = fn

reads_siblings instance-attribute

reads_siblings: bool = _takes_an_argument(fn)

Whether fn takes the sibling view. Decided once, here, because both the binder and the manifest need the answer and the manifest cannot import the binder — asking the marker beats asking the same question twice in two modules. Inspected rather than probed by call, so a real arity error raised inside fn is never mistaken for the no-argument form.

livery.footman.doc

doc(text: str)

Help text for one parameter, via Annotated:

def lint(fix: Annotated[bool, doc("apply fixes in place")] = False): ...

One line, written for the person at the prompt. It shows in fm --help <task>, as the option's description in shells that render one (zsh, fish, nushell, PowerShell tooltips), and in the fm --json --list catalog.

Attributes:

Name Type Description
__slots__
text str
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, text: str) -> None:
    self.text = text

__slots__ class-attribute instance-attribute

__slots__ = ('text',)

text instance-attribute

text: str = text

livery.footman.ask

ask(*, secret: bool = False, prompt: str | None = None)

Prompt for a parameter's value when it isn't supplied, via Annotated:

def release(version: Annotated[str, ask()]): ...

A parameter marked ask() is prompted for when the command line does not give it and no env fills it — the answer runs through the same coercion and validation as a CLI token, re-asking on a bad value. Precedence is CLI > env > prompt (offering the default) > the default.

A declared default becomes the offer: the prompt shows it, Enter accepts it, and where nobody can be asked — off a terminal, under --no-input, in --json — it is simply used. So ask() is safe on any parameter: a person gets asked, an unattended run gets the default. Without a default there is no other answer, so those cases error naming the flag rather than hanging.

Naming the option bare (--version) skips the question: the caller has already said "the declared one", and asking again would be footman not listening.

secret=True hides the input (getpass) and never shows the default, though Enter still accepts it; prompt="…" overrides the question text.

Attributes:

Name Type Description
__slots__
prompt str | None
secret bool
Source code in packages/footman/src/livery/footman/_params.py
def __init__(self, *, secret: bool = False, prompt: str | None = None) -> None:
    self.secret = secret
    self.prompt = prompt

__slots__ class-attribute instance-attribute

__slots__ = ('prompt', 'secret')

prompt instance-attribute

prompt: str | None = prompt

secret instance-attribute

secret: bool = secret

livery.footman.Secret

Bases: str

A string that redacts everywhere it is shown.

Answers to ask(secret=True) and prompt(secret=True) arrive as Secret, and a parameter annotated Secret coerces into one whatever its value came from — a flag, an env() fallback, a default. It is a real str for the body (comparisons, formatting — the caller's business), but its repr — what tracebacks, logs, and debuggers print — is Secret('***'), and structured surfaces serialise it as ***: the --json envelope, a Stdout[…] document, baked manifest defaults.

Redaction covers the places footman shows a value, not the bytes a task deliberately writes. print(token) and f"TOKEN={token}" emit the real thing, because every string operation on a Secret yields a plain str — which is what makes a task that must print a secret (an export … line for eval) work without a switch to disarm.

reveal() is that unwrap said out loud, for where it isn't implicit:

@task
def creds(token: Secret) -> Stdout[dict]:
    return {"token": token.reveal()}   # meant to leave; not redacted

Because it is a method, every intentional exposure is greppable — an audit list a run-wide "don't redact" flag could never give you.

Methods:

Name Description
__repr__
reveal

The real value as a plain str, deliberately un-redacted.

Attributes:

Name Type Description
__slots__

__slots__ class-attribute instance-attribute

__slots__ = ()

__repr__

__repr__() -> str
Source code in packages/footman/src/livery/footman/_params.py
def __repr__(self) -> str:
    return "Secret('***')"

reveal

reveal() -> str

The real value as a plain str, deliberately un-redacted.

Reach for it where a Secret would otherwise survive into a structured surface that redacts — a dict, a dataclass field, a Stdout[…] document — and you mean the value to be there.

Source code in packages/footman/src/livery/footman/_params.py
def reveal(self) -> str:
    """The real value as a plain `str`, deliberately un-redacted.

    Reach for it where a `Secret` would otherwise survive into a
    structured surface that redacts — a dict, a dataclass field, a
    `Stdout[…]` document — and you mean the value to be there.
    """
    return str.__str__(self)

Docstrings

Standalone (stdlib-only, no footman imports) — reusable outside footman.

livery.footman.docstrings.parse

parse(text: str | None) -> Docstring

Parse text (a raw or already-cleaned docstring) into its pieces.

Source code in packages/footman/src/livery/footman/docstrings.py
def parse(text: str | None) -> Docstring:
    """Parse *text* (a raw or already-cleaned docstring) into its pieces."""
    if not text:
        return Docstring()
    lines = inspect.cleandoc(text).splitlines()
    if not lines:
        return Docstring()
    if _opens_with_section(lines):
        summary, body = "", _reindented(lines)
    else:
        summary, body = lines[0].strip(), lines[1:]
    returns = _numpy_returns(body) or _google_returns(body) or _sphinx_returns(body)

    found: list[tuple[int, str]] = []
    if (i := _find_google(body)) is not None:
        found.append((i, "google"))
    if (i := _find_numpy(body)) is not None:
        found.append((i, "numpy"))
    if (i := _find_sphinx(body)) is not None:
        found.append((i, "sphinx"))
    if not found:
        long = _prose(body[: _long_end(body, len(body))])
        return Docstring(summary, long, returns=returns)

    start, kind = min(found)
    params = {
        "google": _google_params,
        "numpy": _numpy_params,
        "sphinx": _sphinx_params,
    }[kind](body, start)
    return Docstring(summary, _prose(body[: _long_end(body, start)]), params, returns)

livery.footman.docstrings.Docstring dataclass

Docstring(summary: str = '', long: str = '', params: dict[str, str] = dict(), returns: str = '')

The parsed pieces of one docstring.

Shaped to grow additively (returns, raises, …) without breaking reusers; absent pieces are empty, never None.

Attributes:

Name Type Description
summary str

The first line — the one-liner listings and completion menus show.

long str

Prose between the summary and the first section (Args: and

params dict[str, str]

Per-parameter help, keyed by the Python parameter name (not the

returns str

The Returns: prose, joined to one line — what the value means,

summary class-attribute instance-attribute

summary: str = ''

The first line — the one-liner listings and completion menus show.

long class-attribute instance-attribute

long: str = ''

Prose between the summary and the first section (Args: and friends), structure preserved; empty when there is none.

params class-attribute instance-attribute

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

Per-parameter help, keyed by the Python parameter name (not the CLI spelling): {"fix": "apply safe fixes in place"}.

returns class-attribute instance-attribute

returns: str = ''

The Returns: prose, joined to one line — what the value means, beside whatever schema the return annotation declares.

Markdown export

Pure functions over manifest tree nodes — see Your tasks, documented for the task-level surface.

livery.footman.markdown.render_page

render_page(tree: dict[str, Any], *, path: tuple[str, ...] = (), heading: int = 1, flavor: str = 'plain', prog: str = 'fm') -> str

One markdown document for the node at path (empty = whole tree).

Source code in packages/footman/src/livery/footman/markdown.py
def render_page(
    tree: dict[str, Any],
    *,
    path: tuple[str, ...] = (),
    heading: int = 1,
    flavor: str = "plain",
    prog: str = "fm",
) -> str:
    """One markdown document for the node at *path* (empty = whole tree)."""
    kind, node = _resolve(tree, path)
    if kind == "task":
        parts = _task_page(list(path), node, heading, flavor, prog)
    else:
        parts = _group_page(list(path), node, heading, flavor, prog)
    return "\n".join(parts).rstrip() + "\n"

livery.footman.markdown.render_site

render_site(tree: dict[str, Any], *, path: tuple[str, ...] = (), flavor: str = 'plain', prog: str = 'fm') -> dict[str, str]

A linked set of files for the node at path: index.md per group (name, help, a table of children with relative links), one file per task. Keys are POSIX-relative paths.

Source code in packages/footman/src/livery/footman/markdown.py
def render_site(
    tree: dict[str, Any],
    *,
    path: tuple[str, ...] = (),
    flavor: str = "plain",
    prog: str = "fm",
) -> dict[str, str]:
    """A linked set of files for the node at *path*: `index.md` per group
    (name, help, a table of children with relative links), one file per task.
    Keys are POSIX-relative paths."""
    kind, node = _resolve(tree, path)
    if kind == "task":
        name = path[-1]
        page = render_page(tree, path=path, heading=1, flavor=flavor, prog=prog)
        return {f"{name}.md": page}
    files: dict[str, str] = {}
    _site_group(list(path), node, "", files, flavor, prog)
    return files

The docs plugin

What plugin("footman.docs") mounts, as functions a tasks file calls to write its task reference — see Your tasks, documented.

livery.footman.docs.page

page(target: Annotated[str, doc('dotted task/group to scope to; empty = all')] = '', heading: Annotated[int, between(1, 6), doc('top heading level')] = 1, flavor: Annotated[Literal['plain', 'material'], doc('plain CommonMark, or material/zensical extras')] = 'plain', out: Annotated[Path | None, doc('file to write the page into; omitted = stdout')] = None, prog: Annotated[str, _invoking_cli, doc('command name in usage and examples')] = '', all: Annotated[bool, doc("include footman's own mounted tasks")] = False) -> list[str] | None

Render the task tree (or one group/task) as one markdown page.

Without --out the page is the task's stdout, ready to redirect or pipe (into pandoc, say); with --out it is written to the file. The heading level makes the page nest under a host site's own structure, so it drops into zensical/mkdocs via a snippet include.

Source code in packages/footman/src/livery/footman/docs.py
@tasks.task
def page(
    target: Annotated[str, doc("dotted task/group to scope to; empty = all")] = "",
    heading: Annotated[int, between(1, 6), doc("top heading level")] = 1,
    flavor: Annotated[
        Literal["plain", "material"],
        doc("plain CommonMark, or material/zensical extras"),
    ] = "plain",
    out: Annotated[
        Path | None, doc("file to write the page into; omitted = stdout")
    ] = None,
    prog: Annotated[str, _invoking_cli, doc("command name in usage and examples")] = "",
    all: Annotated[bool, doc("include footman's own mounted tasks")] = False,
) -> list[str] | None:
    """Render the task tree (or one group/task) as one markdown page.

    Without --out the page is the task's stdout, ready to redirect or pipe
    (into pandoc, say); with --out it is written to the file. The heading
    level makes the page nest under a host site's own structure, so it
    drops into zensical/mkdocs via a snippet include.
    """
    tree = _project_tree(all)
    try:
        text = markdown.render_page(
            tree, path=_path_of(target), heading=heading, flavor=flavor, prog=prog
        )
    except ValueError as exc:
        # An unknown --target: the resolver's message already teaches (the
        # menu of what it does know), so it only needs delivering as the
        # deliberate refusal it is, not as a raw ValueError with a traceback.
        context.fail(f"--target: {exc}")
    if out is None:
        print(text, end="")
        return None
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(text, encoding="utf-8")
    # Inside a task, stderr merges into task output by contract — a plain
    # print is the honest note here; `returned` carries the machine copy.
    print(f"wrote {out}")
    return [str(out)]

livery.footman.docs.site

site(out: Annotated[Path, doc('directory to write the pages into')], target: Annotated[str, doc('dotted group to scope to; empty = all')] = '', flavor: Annotated[Literal['plain', 'material'], doc('material fits zensical/mkdocs; plain is portable')] = 'material', prog: Annotated[str, _invoking_cli, doc('command name in usage and examples')] = '', all: Annotated[bool, doc("include footman's own mounted tasks")] = False) -> list[str]

Render the task tree as linked pages: index.md per group, one file per task.

Made for docs sites — point into your docs tree and add the pages to the nav. Regenerate on each docs build so they can't drift.

Source code in packages/footman/src/livery/footman/docs.py
@tasks.task
def site(
    out: Annotated[Path, doc("directory to write the pages into")],
    target: Annotated[str, doc("dotted group to scope to; empty = all")] = "",
    flavor: Annotated[
        Literal["plain", "material"],
        doc("material fits zensical/mkdocs; plain is portable"),
    ] = "material",
    prog: Annotated[str, _invoking_cli, doc("command name in usage and examples")] = "",
    all: Annotated[bool, doc("include footman's own mounted tasks")] = False,
) -> list[str]:
    """Render the task tree as linked pages: index.md per group, one file per task.

    Made for docs sites — point <out> into your docs tree and add the pages
    to the nav. Regenerate on each docs build so they can't drift.
    """
    tree = _project_tree(all)
    try:
        files = markdown.render_site(
            tree, path=_path_of(target), flavor=flavor, prog=prog
        )
    except ValueError as exc:
        # Same delivery as `page` above: teach, don't traceback.
        context.fail(f"--target: {exc}")
    written: list[str] = []
    for rel, content in files.items():
        dest = out / rel
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(content, encoding="utf-8")
        written.append(str(dest))
    print(f"wrote {len(written)} pages under {out}")
    return written

livery.footman.docs.globals_

globals_(out: Annotated[Path | None, doc('file to write the table into; omitted = stdout')] = None, prog: Annotated[str, _invoking_cli, doc('command name in the table')] = '') -> list[str] | None

Render the runner's global options as a markdown table.

The rows come straight from the CLI grammar — the same table --help prints — so a reference page that regenerates this on each docs build can never drift from the runner. Without --out the table is the task's stdout; with --out it is written to the file.

Source code in packages/footman/src/livery/footman/docs.py
@tasks.task(name="globals")
def globals_(
    out: Annotated[
        Path | None, doc("file to write the table into; omitted = stdout")
    ] = None,
    prog: Annotated[str, _invoking_cli, doc("command name in the table")] = "",
) -> list[str] | None:
    """Render the runner's global options as a markdown table.

    The rows come straight from the CLI grammar — the same table `--help`
    prints — so a reference page that regenerates this on each docs build
    can never drift from the runner. Without --out the table is the task's
    stdout; with --out it is written to the file.
    """
    text = markdown.globals_table(prog=prog)
    if out is None:
        print(text, end="")
        return None
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(text, encoding="utf-8")
    print(f"wrote {out}")
    return [str(out)]

Trace fragments

A profiled run exports FM_PROFILE_DIR; any process drops Chrome-trace fragments there, and the run sweeps them onto its timeline. These are the protocol's two ends, for a process that writes fragments or a tool that reads a run's trace.

livery.footman.profile.DROP module-attribute

DROP = 'FM_PROFILE_DIR'

The drop box, named in every task's environment so that every child inherits it. A child may leave Chrome-trace fragments there. One directory per profiled run, under profiles/ in footman's cache.

The name is the same for every runner built on footman, brand and all, because it is a convention foreign tools speak: a test runner, a build, a converter for another program's timings. None of them can know a brand's prefix.

livery.footman.profile.box

box() -> Generator[Path]

A drop box for the children of this block, removed when it ends.

For a runner that spawns work and wants one timeline of it, whether or not its own run is profiled: a CI job's verbs, a build's compilers.

The directory is yielded and nothing else happens: naming it to the children is the caller's, because a caller that spawns already builds their environment, and writing this process's own environment from inside a task is ambient and footman notes it. Name it under livery.footman.profile.DROP in the environment you hand them.

Yields:

Type Description
Generator[Path]

The directory to name, which exists for the block's duration.

Source code in packages/footman/src/livery/footman/profile.py
@contextlib.contextmanager
def box() -> Generator[Path]:
    """A drop box for the children of this block, removed when it ends.

    For a runner that spawns work and wants one timeline of it, whether or
    not its own run is profiled: a CI job's verbs, a build's compilers.

    The directory is yielded and nothing else happens: naming it to the
    children is the caller's, because a caller that spawns already builds
    their environment, and writing this process's own environment from
    inside a task is ambient and footman notes it. Name it under
    [livery.footman.profile.DROP][] in the environment you hand them.

    Yields:
        The directory to name, which exists for the block's duration.
    """
    made = Path(tempfile.mkdtemp(dir=_boxes_home()))
    _open_boxes.add(str(made))
    atexit.register(_sweep_orphan, str(made))
    try:
        yield made
    finally:
        _open_boxes.discard(str(made))
        shutil.rmtree(made, ignore_errors=True)

livery.footman.profile.keeping

keeping() -> bool

Whether this run keeps a trace, so a caller can skip building one.

The cheap question, for a caller whose timeline costs something to assemble: a run's worth of jobs read from a forge, a tool's report parsed. One environment read, and no answer here is ever a reason to fail: nothing is profiling in the ordinary case.

Source code in packages/footman/src/livery/footman/profile.py
def keeping() -> bool:
    """Whether this run keeps a trace, so a caller can skip building one.

    The cheap question, for a caller whose timeline costs something to
    assemble: a run's worth of jobs read from a forge, a tool's report
    parsed. One environment read, and no answer here is ever a reason to
    fail: nothing is profiling in the ordinary case.
    """
    return _box() is not None

livery.footman.profile.dropped

dropped(events: list[dict[str, Any]]) -> Path | None

Leave events in this run's drop box as a fragment of its own.

For a caller with a timeline to add that this process did not live: a CI run it watched from here, a tool's own report. The stamps are epoch microseconds, the convention every fragment follows, and the writer lays the fragment on the run's clock like any other.

Parameters:

Name Type Description Default
events list[dict[str, Any]]

Chrome-trace events, stamped in epoch microseconds.

required

Returns:

Type Description
Path | None

The file, or None when this run is not profiled and there is no box

Path | None

to drop into, which is the ordinary case.

Source code in packages/footman/src/livery/footman/profile.py
def dropped(events: list[dict[str, Any]]) -> Path | None:
    """Leave *events* in this run's drop box as a fragment of its own.

    For a caller with a timeline to add that this process did not live: a CI
    run it watched from here, a tool's own report. The stamps are epoch
    microseconds, the convention every fragment follows, and the writer lays
    the fragment on the run's clock like any other.

    Args:
        events: Chrome-trace events, stamped in epoch microseconds.

    Returns:
        The file, or `None` when this run is not profiled and there is no box
        to drop into, which is the ordinary case.
    """
    sink = _box()
    return None if sink is None else _drop(sink, events)

livery.footman.profile.swept

swept(where: Path | str, *, zero: float | None = None) -> tuple[list[dict[str, Any]], float]

Every fragment in where, on one clock; the events and that clock.

A fragment is stamped in epoch microseconds, so reading a box is subtracting one moment from every stamp. zero is that moment, in wall-clock microseconds; the earliest stamp in the box by default, which makes a file that starts at zero rather than at fifty thousand years. A fragment that will not parse is named on stderr and skipped, never fatal, because the run it rode in is the point.

Parameters:

Name Type Description Default
where Path | str

The directory the fragments are in.

required
zero float | None

The wall-clock moment to measure from, or None for the earliest stamp found.

None

Returns:

Type Description
list[dict[str, Any]]

The events, and the moment they are measured from. No fragments at

float

all is no events and the zero asked for, or zero.

Source code in packages/footman/src/livery/footman/profile.py
def swept(
    where: Path | str, *, zero: float | None = None
) -> tuple[list[dict[str, Any]], float]:
    """Every fragment in *where*, on one clock; the events and that clock.

    A fragment is stamped in epoch microseconds, so reading a box is
    subtracting one moment from every stamp. *zero* is that moment, in
    wall-clock microseconds; the earliest stamp in the box by default,
    which makes a file that starts at zero rather than at fifty thousand
    years. A fragment that will not parse is named on stderr and skipped,
    never fatal, because the run it rode in is the point.

    Args:
        where: The directory the fragments are in.
        zero: The wall-clock moment to measure from, or ``None`` for the
            earliest stamp found.

    Returns:
        The events, and the moment they are measured from. No fragments at
        all is no events and the *zero* asked for, or zero.
    """
    found: list[dict[str, Any]] = []
    for fragment in sorted(Path(where).glob("*.json")):
        try:
            payload: Any = json.loads(fragment.read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            print(f"profile: skipped fragment {fragment.name}: {exc}", file=sys.stderr)
            continue
        events = payload.get("traceEvents") if isinstance(payload, dict) else payload
        if not isinstance(events, list):
            continue
        found += [event for event in events if isinstance(event, dict)]
    origin = zero
    if origin is None:
        stamps = [ts for e in found if isinstance(ts := e.get("ts"), (int, float))]
        origin = min(stamps, default=0.0)
    return [
        {**e, "ts": round(ts - origin, 1)}
        if isinstance(ts := e.get("ts"), (int, float))
        else e
        for e in found
    ], origin

livery.footman.profile.as_trace

as_trace(events: list[dict[str, Any]], *, origin: float) -> str

events as the text of a trace file, for a reader to open.

One place builds the shape: the events, the unit a reader shows by default, and where this trace's zero sits on the wall clock, so another timeline can be laid on it.

Parameters:

Name Type Description Default
events list[dict[str, Any]]

Chrome-trace events, stamped relative to origin.

required
origin float

That zero, in wall-clock microseconds. Zero when the stamps are already the wall clock's.

required

Returns:

Type Description
str

The file's text.

Source code in packages/footman/src/livery/footman/profile.py
def as_trace(events: list[dict[str, Any]], *, origin: float) -> str:
    """*events* as the text of a trace file, for a reader to open.

    One place builds the shape: the events, the unit a reader shows by
    default, and where this trace's zero sits on the wall clock, so another
    timeline can be laid on it.

    Args:
        events: Chrome-trace events, stamped relative to *origin*.
        origin: That zero, in wall-clock microseconds. Zero when the stamps
            are already the wall clock's.

    Returns:
        The file's text.
    """
    return json.dumps(
        {"traceEvents": events, "displayTimeUnit": "ms", ORIGIN: round(origin, 1)}
    )

livery.footman.profile.laid_on

laid_on(text: str, *, zero: float, pids: Iterator[int], label: str = '') -> tuple[list[dict[str, Any]], str]

One trace's events laid on another clock; the events, or why not.

A trace records the wall-clock moment its own zero sits at, and every stamp in it is relative to that. So two traces written anywhere, by anything, can be read on one timeline: each one's stamps shift by its own origin against the reading clock's. The alignment comes from what each side wrote down, never from the order anything arrived in.

The process groups are renumbered from pids, because every run's own group carries the same number and two traces would otherwise read as one process. A group's name keeps label in front of it, so a reader can tell which trace a group came from.

Parameters:

Name Type Description Default
text str

The trace, as its writer wrote it.

required
zero float

Where the reading clock's zero sits on the wall clock, in microseconds, as this module records it under ORIGIN.

required
pids Iterator[int]

Process ids to claim, one per group the trace holds.

required
label str

What to put in front of each group's name.

''

Returns:

Type Description
list[dict[str, Any]]

The events on the reading clock, and a reason when there are none:

str

a trace that does not parse, or one that records no origin and so

tuple[list[dict[str, Any]], str]

cannot be placed at all.

Source code in packages/footman/src/livery/footman/profile.py
def laid_on(
    text: str, *, zero: float, pids: Iterator[int], label: str = ""
) -> tuple[list[dict[str, Any]], str]:
    """One trace's events laid on another clock; the events, or why not.

    A trace records the wall-clock moment its own zero sits at, and every
    stamp in it is relative to that. So two traces written anywhere, by
    anything, can be read on one timeline: each one's stamps shift by its own
    origin against the reading clock's. The alignment comes from what each
    side wrote down, never from the order anything arrived in.

    The process groups are renumbered from *pids*, because every run's own
    group carries the same number and two traces would otherwise read as one
    process. A group's name keeps *label* in front of it, so a reader can
    tell which trace a group came from.

    Args:
        text: The trace, as its writer wrote it.
        zero: Where the reading clock's zero sits on the wall clock, in
            microseconds, as this module records it under `ORIGIN`.
        pids: Process ids to claim, one per group the trace holds.
        label: What to put in front of each group's name.

    Returns:
        The events on the reading clock, and a reason when there are none:
        a trace that does not parse, or one that records no origin and so
        cannot be placed at all.
    """
    try:
        payload: Any = json.loads(text)
    except ValueError as exc:
        return [], f"the trace does not parse ({exc})"
    if not isinstance(payload, dict):
        return [], "the trace is not a trace object"
    origin = payload.get(ORIGIN)
    if not isinstance(origin, (int, float)) or isinstance(origin, bool):
        return [], f"the trace records no {ORIGIN}, so it cannot be placed"
    found = payload.get("traceEvents")
    if not isinstance(found, list):
        return [], "the trace carries no events"
    shift = float(origin) - zero
    mapped: dict[Any, int] = {}
    placed: list[dict[str, Any]] = []
    for event in found:
        if not isinstance(event, dict):
            continue
        own: Any = event.get("pid")
        if own not in mapped:
            mapped[own] = next(pids)
        moved: dict[str, Any] = {**event, "pid": mapped[own]}
        if isinstance(ts := event.get("ts"), (int, float)):
            moved["ts"] = round(ts + shift, 1)
        if label and moved.get("ph") == "M" and moved.get("name") == "process_name":
            args = moved.get("args")
            was = args.get("name", "fm") if isinstance(args, dict) else "fm"
            moved["args"] = {"name": f"{label}: {was}"}
        placed.append(moved)
    return placed, ""

Testing

livery.footman.Runner

Runner(app: App | None = None)

Drive a footman CLI in-process, capturing output and results.

Pass a branded App to test a custom CLI (Runner(App(prog="acme"))) — error prefixes, --version, and hints then use that brand, exactly as they would for real users.

Methods:

Name Description
invoke

Run one command line and return everything it produced.

Attributes:

Name Type Description
app App
Source code in packages/footman/src/livery/footman/testing.py
def __init__(self, app: App | None = None) -> None:
    self.app = app if app is not None else App()

app instance-attribute

app: App = app if app is not None else App()

invoke

invoke(args: str | list[str], *, tasks: Path | Group | None = None, cwd: Path | None = None, stdin: str | bytes | None = None, answers: Mapping[Any, Any] | None = None) -> InvokeResult

Run one command line and return everything it produced.

args is a string (shlex-split) or an argv list. tasks overrides discovery: a Path routes through --tasks-file, a Group skips discovery entirely (an in-memory tree, no files needed). Without it, the normal tasks.py cascade from cwd applies. stdin is what a pipe would have delivered — a str is encoded UTF-8 — and its absence means "a terminal": the invocation never reads the test harness's real stream, so stdin-bound parameters see exactly what the test says and nothing else. answers scripts the world the invocation rehearses in — the same table recording(answers=…) takes — and implies --dry-run, so the CLI runs end to end against scripted commands. Never raises on task failure — the code is in the Result; KeyboardInterrupt passes through.

Source code in packages/footman/src/livery/footman/testing.py
def invoke(
    self,
    args: str | list[str],
    *,
    tasks: Path | Group | None = None,
    cwd: Path | None = None,
    stdin: str | bytes | None = None,
    answers: Mapping[Any, Any] | None = None,
) -> InvokeResult:
    """Run one command line and return everything it produced.

    `args` is a string (shlex-split) or an argv list. `tasks` overrides
    discovery: a `Path` routes through `--tasks-file`, a `Group` skips
    discovery entirely (an in-memory tree, no files needed). Without it,
    the normal `tasks.py` cascade from `cwd` applies. `stdin` is what a
    pipe would have delivered — a `str` is encoded UTF-8 — and its
    absence means "a terminal": the invocation never reads the test
    harness's real stream, so `stdin`-bound parameters see exactly what
    the test says and nothing else. `answers` scripts the world the
    invocation rehearses in — the same table `recording(answers=…)`
    takes — and implies `--dry-run`, so the CLI runs end to end against
    scripted commands. Never raises on task failure — the code is in
    the `Result`; `KeyboardInterrupt` passes through.
    """
    argv = shlex.split(args) if isinstance(args, str) else list(args)
    if answers is not None and not any(a in ("--dry-run", "-n") for a in argv):
        argv = ["--dry-run", *argv]
    out, err = io.StringIO(), io.StringIO()
    collected: list[TaskResult] = []
    payload = stdin.encode("utf-8") if isinstance(stdin, str) else stdin
    previous = context._inject_stdin(payload)
    table = context._inject_answers(
        context._Answers(answers) if answers is not None else None
    )
    try:
        return self._invoke(argv, tasks, cwd, out, err, collected)
    finally:
        context._inject_answers(table)
        context._restore_stdin_payload(previous)

livery.footman.testing.InvokeResult dataclass

InvokeResult(exit_code: int, stdout: str, stderr: str, results: list[TaskResult] = list())

Everything one Runner.invoke produced.

Named apart from the run-step Result (footman.Result, what run() returns): this is the outcome of a whole CLI invocation — its exit code, captured streams, and per-task TaskResults.

Attributes:

Name Type Description
exit_code int
stdout str
stderr str
results list[TaskResult]
ok bool

exit_code instance-attribute

exit_code: int

stdout instance-attribute

stdout: str

stderr instance-attribute

stderr: str

results class-attribute instance-attribute

results: list[TaskResult] = field(default_factory=list)

ok property

ok: bool

livery.footman.recording

recording(*, answers: Mapping[Any, Any] | None = None, **overrides: Any) -> Generator[list[Result]]

Capture the commands a block would run() — silently, not executing.

Yields the live step list; each run() call inside the block — hosted toolroom calls included — appends a Result instead of executing, and answers with a blank success. Keyword overrides go to the underlying Context (e.g. env={...}).

answers= scripts the answers instead. Keys are command prefixes — "uv tool list", or a tuple of tokens — matched against the recorded command (Result.command), longest match first. Values: a str is stdout with exit 0, an int is an exit code, a Result sets code and both streams, an exception instance is raised by the call (a missing binary), and a list answers consecutive matches in order and refuses by name when it runs dry. Unmatched calls keep the blank success. A non-zero answer takes the real failing lane — returned under nofail=True, raised as RunFailed otherwise — and a matched call is answered even when it opted out of the record with recorded=False. A recorded step also keeps the env and cwd it would have run with.

toolroom's answers() is the same table applied one layer down, at the bridge's own seam; nested inside a recording, it wins and the record sees nothing.

Source code in packages/footman/src/livery/footman/testing.py
@contextlib.contextmanager
def recording(
    *, answers: Mapping[Any, Any] | None = None, **overrides: Any
) -> Generator[list[Result]]:
    """Capture the commands a block would `run()` — silently, not executing.

    Yields the live step list; each `run()` call inside the block — hosted
    toolroom calls included — appends a `Result` instead of executing, and
    answers with a blank success. Keyword overrides go to the underlying
    `Context` (e.g. `env={...}`).

    `answers=` scripts the answers instead. Keys are command prefixes —
    `"uv tool list"`, or a tuple of tokens — matched against the recorded
    command (`Result.command`), longest match first. Values: a `str` is
    stdout with exit 0, an `int` is an exit code, a `Result` sets code and
    both streams, an exception instance is *raised* by the call (a missing
    binary), and a list answers consecutive matches in order and refuses by
    name when it runs dry. Unmatched calls keep the blank success. A
    non-zero answer takes the real failing lane — returned under
    `nofail=True`, raised as `RunFailed` otherwise — and a matched call is
    answered even when it opted out of the record with `recorded=False`.
    A recorded step also keeps the `env` and `cwd` it would have run with.

    toolroom's `answers()` is the same table applied one layer down, at the
    bridge's own seam; nested inside a recording, it wins and the record
    sees nothing.
    """
    # Build the kwargs dict so `overrides` can win over the dry_run/quiet
    # defaults — passing them as positional defaults made `recording(quiet=False)`
    # raise "got multiple values for keyword argument" (F51).
    # One merged dict, then one splat — a caller's override may replace the
    # defaults (a direct `Context(dry_run=True, **overrides)` would raise on
    # a duplicate keyword instead).
    merged: dict[str, Any] = {"dry_run": True, "quiet": True, **overrides}
    if answers is not None:
        merged["answers"] = context._Answers(answers)
    ctx = Context(**merged)
    with use_context(ctx):
        yield ctx.steps