Skip to content

livery.toolroom.bench._colorprobe

livery.toolroom.bench._colorprobe

Probe a tool's colour control by running it — the engine behind fm toolroom.color.

footman forces colour into the tools it spawns (see context.color_env): by the environment for the modern set, by the tool's own flag for the few that ignore it. Which is which is a fact about each tool, and the honest way to learn it is to run the tool and look at the bytes. This module does that: for each tool it forces colour on and off, first by environment then by flag, and records whether each direction obeys the environment (env), needs the flag (flag), or can be forced neither way (none).

The result generates _colordata.py — read by tools.py for its forcing table and by the docs for the support table. A maintainer runs it against the provisioned binaries; nothing here is imported on a normal fm run.

A tool only colourises when it has something to colour, so each needs a hardcoded trigger: a command (and any fixture files) that produces colourable output. Figured out once per tool; one without a trigger reports unprobed.

Classes:

Name Description
Trigger

How to make a tool emit colour: its argv, and the fixture it needs.

ColourFlag

The tokens that force a tool's colour on/off, and where they go.

Verdict

One tool's probed colour control, each direction categorised.

Functions:

Name Description
flag_candidate

The colour switch to try for a tool: a curated quirk (git), else a

probe

Categorise one tool by running its trigger with colour forced each way.

probe_all

Probe each (key, argv0, binary, spec); return {key: (argv0, verdict)}.

merged

fresh over stored: a probe records what it ran and leaves the rest.

render

The text of _colordata.py for a batch of probe results.

Attributes:

Name Type Description
TRIGGERS dict[str, Trigger]
Row

One stored line of _colordata.py — see its _Row.

TRIGGERS module-attribute

TRIGGERS: dict[str, Trigger] = {'ruff': Trigger(('check', 'bad.py'), {'bad.py': 'import os\n'}), 'ruff_format': Trigger(('format', '--diff', 'bad.py'), {'bad.py': 'x=1\n'}), 'basedpyright': Trigger(('bad.py',), {'bad.py': _PY_TYPE}), 'mypy': Trigger(('bad.py',), {'bad.py': _PY_TYPE}), 'ty': Trigger(('check', 'bad.py'), {'bad.py': _PY_TYPE}), 'pytest': Trigger(('t.py',), {'t.py': 'def test():\n    assert True\n'}), 'cspell': Trigger(('lint', 'bad.txt'), {'bad.txt': _SPELL}), 'uv': Trigger(('python', 'list')), 'gh': Trigger(('--help',)), 'bun': Trigger(('--help',)), 'prek': Trigger(('--help',)), 'mkdocs': Trigger(('--help',)), 'twine': Trigger(('check', 's.py'), {'s.py': 'print(1)\n'}), 'cmake': Trigger(('-S', '.', '-B', 'b')), 'ninja': Trigger((), {'build.ninja': 'rule f\n  command = false\nbuild x: f\n'}), 'build': Trigger(('--sdist',), {'pyproject.toml': '[project]\nname="x"\nversion="1"\n'}), 'git': Trigger(('log', '--oneline', '-1'), {'a.txt': 'hi\n'}, git=True), 'git_cliff': Trigger((), {'a.txt': 'hi\n'}, git=True), 'git_changelog': Trigger(('.',), {'a.txt': 'hi\n'}, git=True), 'djlint': Trigger(('bad.html',), {'bad.html': '<div ></div>\n'}), 'markdownlint': Trigger(('bad.md',), {'bad.md': '#x\n'}), 'eclint': Trigger(('-h',)), 'coverage': Trigger(('report',)), 'python': Trigger(('--version',)), 'zensical': Trigger(('--help',)), 'claude': Trigger(('--help',)), 'tea': Trigger(('--help',))}

Row module-attribute

Row = tuple[str, str, str, tuple[str, ...], tuple[str, ...], bool]

One stored line of _colordata.py — see its _Row.

Trigger dataclass

Trigger(args: tuple[str, ...], files: dict[str, str] = dict(), git: bool = False)

How to make a tool emit colour: its argv, and the fixture it needs.

Attributes:

Name Type Description
args tuple[str, ...]
files dict[str, str]
git bool

args instance-attribute

args: tuple[str, ...]

files class-attribute instance-attribute

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

git class-attribute instance-attribute

git: bool = False

ColourFlag dataclass

ColourFlag(on: tuple[str, ...] = (), off: tuple[str, ...] = (), pre_verb: bool = False)

The tokens that force a tool's colour on/off, and where they go.

Attributes:

Name Type Description
on tuple[str, ...]
off tuple[str, ...]
pre_verb bool

on class-attribute instance-attribute

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

off class-attribute instance-attribute

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

pre_verb class-attribute instance-attribute

pre_verb: bool = False

Verdict dataclass

Verdict(on: str, off: str, flag: ColourFlag | None = None)

One tool's probed colour control, each direction categorised.

Attributes:

Name Type Description
on str
off str
flag ColourFlag | None

on instance-attribute

on: str

off instance-attribute

off: str

flag class-attribute instance-attribute

flag: ColourFlag | None = None

flag_candidate

flag_candidate(key: str, spec: ToolSpec) -> ColourFlag | None

The colour switch to try for a tool: a curated quirk (git), else a --color=always/never detected from its stub (ToolSpec.color_flags).

Source code in packages/toolroom-bench/src/livery/toolroom/bench/_colorprobe.py
def flag_candidate(key: str, spec: ToolSpec) -> ColourFlag | None:
    """The colour switch to try for a tool: a curated quirk (git), else a
    `--color=always/never` detected from its stub (`ToolSpec.color_flags`).
    """
    if key in _CURATED:
        on, off, pre = _CURATED[key]
        return ColourFlag(on, off, pre)
    detected = spec.color_flags()
    for _verb, (flag, on_val, off_val) in sorted(detected.items()):
        on = (f"{flag}={on_val}",) if on_val else ()
        off = (f"{flag}={off_val}",) if off_val else ()
        if on or off:
            return ColourFlag(on, off, pre_verb=False)
    return None

probe

probe(key: str, binary: str, spec: ToolSpec) -> Verdict

Categorise one tool by running its trigger with colour forced each way.

Source code in packages/toolroom-bench/src/livery/toolroom/bench/_colorprobe.py
def probe(key: str, binary: str, spec: ToolSpec) -> Verdict:
    """Categorise one tool by running its trigger with colour forced each way."""
    if key in _PASSTHROUGH:  # a wrapper; colour isn't footman's to control
        return Verdict("n/a", "n/a")
    trigger = TRIGGERS.get(key)
    if trigger is None:
        return Verdict("unprobed", "unprobed")
    flag = flag_candidate(key, spec)
    pre_on = flag.on if (flag and flag.pre_verb) else ()
    post_on = flag.on if (flag and not flag.pre_verb) else ()
    pre_off = flag.off if (flag and flag.pre_verb) else ()
    post_off = flag.off if (flag and not flag.pre_verb) else ()

    def coloured(
        env_add: dict[str, str],
        pre: tuple[str, ...] = (),
        post: tuple[str, ...] = (),
    ) -> bool:
        return bool(
            _SGR.search(_capture(_argv(binary, trigger, pre, post), cwd, env_add))
        )

    with _fixture(binary, trigger) as cwd:
        # Force colour maximally (environment and flag). No colour then means
        # the tool can't be forced: `none` if it produced output to colour,
        # `unprobed` if the trigger produced nothing to judge.
        maxed = _capture(_argv(binary, trigger, pre_on, post_on), cwd, _ON_ENV)
        if not _SGR.search(maxed):
            # It produced output but no colour by any means → `none`; footman
            # can't make it colour over its pipe, so there is nothing to suppress
            # either (`off` is `n/a`, not a spurious `env`). No output at all →
            # the trigger judged nothing (`unprobed`).
            return (
                Verdict("none", "n/a")
                if maxed.strip()
                else Verdict("unprobed", "unprobed")
            )

        if coloured(_ON_ENV):
            on = "env"
        elif flag and (pre_on or post_on) and coloured({}, pre_on, post_on):
            on = "flag"
        else:
            on = "none"

        # A tool footman can't force *on* has nothing to turn *off* over a pipe —
        # a monochrome result there is the pipe, not the tool respecting NO_COLOR.
        if on == "none":
            off = "n/a"
        elif not coloured(_OFF_ENV):  # footman's off signal keeps it clean
            off = "env"
        elif flag and (pre_off or post_off) and not coloured({}, pre_off, post_off):
            off = "flag"
        else:
            off = "none"

    needs_flag = "flag" in (on, off)
    return Verdict(on, off, flag if needs_flag else None)

probe_all

probe_all(installed: list[tuple[str, str, str, ToolSpec]]) -> dict[str, tuple[str, Verdict]]

Probe each (key, argv0, binary, spec); return {key: (argv0, verdict)}.

Source code in packages/toolroom-bench/src/livery/toolroom/bench/_colorprobe.py
def probe_all(
    installed: list[tuple[str, str, str, ToolSpec]],
) -> dict[str, tuple[str, Verdict]]:
    """Probe each `(key, argv0, binary, spec)`; return `{key: (argv0, verdict)}`."""
    return {
        key: (argv0, probe(key, binary, spec)) for key, argv0, binary, spec in installed
    }

merged

merged(stored: dict[str, Row], fresh: dict[str, tuple[str, Verdict]]) -> dict[str, tuple[str, Verdict]]

fresh over stored: a probe records what it ran and leaves the rest.

A probe needs a binary, and the man tier provisions pages — so git, ssh and their siblings are in no prefix, and a run that wrote only what it saw would drop git's -c color.ui=always and take the bridge's colour forcing out with it. The same shape as a platform's reading folding into the option history: what was looked at is recorded, and what was not is left exactly as it was.

Source code in packages/toolroom-bench/src/livery/toolroom/bench/_colorprobe.py
def merged(
    stored: dict[str, Row], fresh: dict[str, tuple[str, Verdict]]
) -> dict[str, tuple[str, Verdict]]:
    """*fresh* over *stored*: a probe records what it ran and leaves the rest.

    A probe needs a binary, and the man tier provisions pages — so git, ssh
    and their siblings are in no prefix, and a run that wrote only what it
    saw would drop git's `-c color.ui=always` and take the bridge's colour
    forcing out with it. The same shape as a platform's reading folding
    into the option history: what was looked at is recorded, and what was
    not is left exactly as it was.
    """
    kept = {
        key: (
            argv0,
            Verdict(on, off, ColourFlag(f_on, f_off, pre) if f_on or f_off else None),
        )
        for key, (argv0, on, off, f_on, f_off, pre) in stored.items()
        if key not in fresh
    }
    return {**kept, **fresh}

render

render(results: dict[str, tuple[str, Verdict]]) -> str

The text of _colordata.py for a batch of probe results.

Source code in packages/toolroom-bench/src/livery/toolroom/bench/_colorprobe.py
def render(results: dict[str, tuple[str, Verdict]]) -> str:
    """The text of `_colordata.py` for a batch of probe results."""
    lines = [_HEADER]
    for key in sorted(results):
        argv0, v = results[key]
        f_on = v.flag.on if v.flag else ()
        f_off = v.flag.off if v.flag else ()
        pre = v.flag.pre_verb if v.flag else False
        lines.append(
            f"    {key!r}: ({argv0!r}, {v.on!r}, {v.off!r}, "
            f"{f_on!r}, {f_off!r}, {pre!r}),"
        )
    lines.append("}\n")
    return "\n".join(lines)