Ir para o conteúdo

Referência

Gerada a partir das docstrings do pacote via mkdocstrings.

Superfície de topo

tempest_cli

Framework-agnostic quality gate for Python projects.

tempest-cli runs ruff, mypy and pytest behind one command, with a typing-strictness dial read from [tool.tempest] in the project's pyproject.toml — and a generator for the prompt that makes an AI fill a pull-request description from the branch's own diff.

It knows nothing about any web framework. ruff ships with it, so the lint/format commands work the moment it is installed; mypy and pytest are left to the project, which pins the versions it wants. The tools are invoked from the project's environment first, so a pinned version always beats the bundled one.

tempest-cli check                 # lint + fmt-check + type + test
tempest-cli fix                   # every ruff autofix, then format
tempest-cli type -s strict        # override the configured strictness
tempest-cli pr-prompt | claude -p

tc check                          # `tc` is the short alias for the same CLI

Everything is importable too, for a project that would rather wire the gate into its own tooling:

from tempest_cli import load_tempest_config, run_full_check

config = load_tempest_config()
exit_code = run_full_check(".", config=config)

A framework that wants its own rules in check passes them as :class:tempest_cli.CheckStep values — extra_steps on :func:run_full_check and on :func:tempest_cli.main.register_commands — and they run after mypy, before pytest.

And :func:tempest_cli.main.register_commands mounts the whole gate onto an existing :class:typer.Typer, so another CLI can expose these commands under its own name without copying them.

DEFAULT_TYPING_STRICTNESS module-attribute

DEFAULT_TYPING_STRICTNESS: TypingStrictness = 'standard'

Level applied when the key is absent or no pyproject.toml is found.

TypingStrictness module-attribute

TypingStrictness = Literal['lenient', 'standard', 'strict']

Allowed values for [tool.tempest] typing_strictness.

TempestConfig dataclass

TempestConfig(typing_strictness: TypingStrictness = DEFAULT_TYPING_STRICTNESS)

Resolved [tool.tempest] settings.

Attributes:

Name Type Description
typing_strictness TypingStrictness

How strictly the CLI gates enforce typing. One of "lenient", "standard", "strict".

ruff_ann_select

ruff_ann_select() -> list[str]

Return the ANN rule codes to add to ruff for this level.

Returns:

Type Description
list[str]

list[str]: Rule codes for --extend-select (empty for

list[str]

"lenient"). ANN401 is never present.

Source code in tempest_cli/config.py
def ruff_ann_select(self) -> list[str]:
    """Return the ANN rule codes to add to ruff for this level.

    Returns:
        list[str]: Rule codes for ``--extend-select`` (empty for
        ``"lenient"``). ANN401 is never present.
    """
    return list(_RUFF_ANN_BY_LEVEL[self.typing_strictness])

mypy_flags

mypy_flags() -> list[str]

Return the extra mypy flags to add for this level.

Returns:

Type Description
list[str]

list[str]: Flags layered on top of the project's

list[str]

[tool.mypy] config (empty for "lenient").

Source code in tempest_cli/config.py
def mypy_flags(self) -> list[str]:
    """Return the extra mypy flags to add for this level.

    Returns:
        list[str]: Flags layered on top of the project's
        ``[tool.mypy]`` config (empty for ``"lenient"``).
    """
    return list(_MYPY_FLAGS_BY_LEVEL[self.typing_strictness])

GitError

Bases: RuntimeError

A git invocation failed, or the repository lacks what was asked.

Carries the command's own stderr so the caller can print the reason git gave instead of a generic failure.

PromptLanguage

Bases: StrEnum

Language of the bundled template and of the prompt's instructions.

Only the bundled template is translated: a repository template is used verbatim in whatever language it was written in, since it is that repository's contract.

CheckStep dataclass

CheckStep(
    name: str,
    run: Callable[[str], int],
    run_with_options: Callable[[str, StepOptions], int] | None = None,
)

A step check runs after mypy and before pytest.

The step owns its own output: whatever run prints is what the user reads, so a failing step should name the file, the line and the fix. check echoes $ <name> to stderr before calling it, the way it echoes the command line of every built-in step.

Attributes:

Name Type Description
name str

Label echoed as $ <name> before the step runs.

run Callable[[str], int]

Called with the check target (the path given on the command line, . by default); returns an exit code, 0 meaning the step passed. A non-zero code stops the gate and becomes its exit code.

run_with_options Callable[[str, StepOptions], int] | None

Called instead of run when set, with the target and the :class:StepOptions check parsed. None (the default) marks a step with no options; check --rule refuses to run when no step declares this.

Example
from tempest_cli import CheckStep, run_full_check


def no_todo(target: str) -> int:
    return 0


exit_code: int = run_full_check(
    ".", extra_steps=[CheckStep(name="no-todo", run=no_todo)]
)

StepOptions dataclass

StepOptions(rules: tuple[str, ...] = (), strict: bool | None = None)

Options of check that only the extra steps read.

check --rule <CODE> and check --strict mean nothing to ruff, mypy or pytest; they are for a step that reports rule codes with a severity. tempest-cli parses them and hands them over as typed values, so a step never parses the command line itself.

Attributes:

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

Rule codes to report, as typed (--rule repeated). Empty means every rule.

strict bool | None

--strict / --no-strict. None when neither was typed, so the step falls back to its own default.

given property

given: bool

Tell whether any option was typed.

Returns:

Name Type Description
bool bool

True when --rule or --strict / --no-strict

bool

was passed.

find_pyproject

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

Locate the nearest pyproject.toml walking up from start.

Parameters:

Name Type Description Default
start Path | None

Directory to begin the search. Defaults to the current working directory.

None

Returns:

Type Description
Path | None

Path | None: The path to the first pyproject.toml found in

Path | None

start or an ancestor, or None when none exists.

Source code in tempest_cli/config.py
def find_pyproject(start: Path | None = None) -> Path | None:
    """Locate the nearest ``pyproject.toml`` walking up from ``start``.

    Args:
        start (Path | None): Directory to begin the search. Defaults to
            the current working directory.

    Returns:
        Path | None: The path to the first ``pyproject.toml`` found in
        ``start`` or an ancestor, or ``None`` when none exists.
    """
    current = (start or Path.cwd()).resolve()
    for directory in (current, *current.parents):
        candidate = directory / "pyproject.toml"
        if candidate.is_file():
            return candidate
    return None

load_tempest_config

load_tempest_config(start: Path | None = None) -> TempestConfig

Load [tool.tempest] from the nearest pyproject.toml.

Parameters:

Name Type Description Default
start Path | None

Directory to begin the search. Defaults to the current working directory.

None

Returns:

Name Type Description
TempestConfig TempestConfig

The resolved config. Falls back to defaults when

TempestConfig

no pyproject.toml or no [tool.tempest] table is found.

Raises:

Type Description
ValueError

When typing_strictness is present but invalid.

Source code in tempest_cli/config.py
def load_tempest_config(start: Path | None = None) -> TempestConfig:
    """Load ``[tool.tempest]`` from the nearest ``pyproject.toml``.

    Args:
        start (Path | None): Directory to begin the search. Defaults to
            the current working directory.

    Returns:
        TempestConfig: The resolved config. Falls back to defaults when
        no ``pyproject.toml`` or no ``[tool.tempest]`` table is found.

    Raises:
        ValueError: When ``typing_strictness`` is present but invalid.
    """
    pyproject = find_pyproject(start)
    if pyproject is None:
        return TempestConfig()
    with pyproject.open("rb") as handle:
        data = tomllib.load(handle)
    table = data.get("tool", {}).get("tempest", {})
    strictness = (
        _coerce_strictness(table["typing_strictness"], source=str(pyproject))
        if "typing_strictness" in table
        else DEFAULT_TYPING_STRICTNESS
    )
    return TempestConfig(typing_strictness=strictness)

resolve_tool

resolve_tool(executable: str) -> list[str] | None

Return an argv prefix invoking executable or None when absent.

Public because callers outside the gate need the same lookup — the SDK's OpenAPI code generator formats what it emits with the project's own ruff, and reimplementing the environment/uv run fallback there would be a second answer to the same question.

Preference order:

  1. the environments that belong to this run (see :func:_environment_dirs): the CLI's own interpreter directory, $VIRTUAL_ENV, then the nearest .venv;
  2. executable on PATH — skipped when it resolves to a version-manager shim that does not dispatch anywhere;
  3. uv run --with <executable> <executable> when uv is on the PATH: the project's own environment plus the tool, without requiring activation or a prior uv sync.

Step 3 carries --with on purpose. A plain uv run ruff falls back to PATH when the project environment has no ruff — landing right back on the dead shim this lookup just rejected. --with puts the tool in the run's own overlay, so the command is always the one that runs. When the project pins a version, uv resolves the overlay against the project's requirements, so the pin still wins.

Parameters:

Name Type Description Default
executable str

The command name (ruff/mypy/pytest).

required

Returns:

Type Description
list[str] | None

list[str] | None: argv prefix to extend with extra arguments, or

list[str] | None

None when no runner could be found.

Source code in tempest_cli/lint.py
def resolve_tool(executable: str) -> list[str] | None:
    """Return an argv prefix invoking ``executable`` or ``None`` when absent.

    Public because callers outside the gate need the same lookup — the
    SDK's OpenAPI code generator formats what it emits with the project's
    own ruff, and reimplementing the environment/``uv run`` fallback
    there would be a second answer to the same question.

    Preference order:

    1. the environments that belong to this run (see
       :func:`_environment_dirs`): the CLI's own interpreter directory,
       ``$VIRTUAL_ENV``, then the nearest ``.venv``;
    2. ``executable`` on ``PATH`` — skipped when it resolves to a
       version-manager shim that does not dispatch anywhere;
    3. ``uv run --with <executable> <executable>`` when ``uv`` is on the
       ``PATH``: the project's own environment plus the tool, without
       requiring activation or a prior ``uv sync``.

    Step 3 carries ``--with`` on purpose. A plain ``uv run ruff`` falls
    back to ``PATH`` when the project environment has no ruff — landing
    right back on the dead shim this lookup just rejected. ``--with``
    puts the tool in the run's own overlay, so the command is always the
    one that runs. When the project pins a version, uv resolves the
    overlay against the project's requirements, so the pin still wins.

    Args:
        executable (str): The command name (``ruff``/``mypy``/``pytest``).

    Returns:
        list[str] | None: argv prefix to extend with extra arguments, or
        ``None`` when no runner could be found.
    """
    for directory in _environment_dirs():
        local = shutil.which(executable, path=str(directory))
        if local is not None:
            return [local]
    direct = _path_lookup(executable)
    if direct is not None:
        return [direct]
    uv = _path_lookup("uv")
    if uv is not None:
        return [uv, "run", "--with", executable, executable]
    return None

run_full_check

run_full_check(
    target: str,
    *,
    config: TempestConfig | None = None,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    extra_steps: Sequence[CheckStep] = (),
    require_xdist: bool = True,
    step_options: StepOptions = StepOptions(),
) -> int

Run the entire quality gate sequentially.

Order: ruff check → ruff format --check → mypy → each of extra_steps, in the order given → pytest. Every step is announced on stderr as $ <command line> ($ <name> for an extra step) and the gate stops at the first non-zero exit code, so failures surface fast. The extra steps sit before pytest because they are static checks: a layering rule should fail in a second, not after the whole suite.

With fast=True the pytest step runs the way :func:run_pytest runs it with fast=True. The pytest-xdist preflight happens before the first step, so a required plugin that is missing fails in a second instead of after lint and mypy have already run, and a merely preferred one degrades the pytest step to serial up front.

Parameters:

Name Type Description Default
target str

The path inspected by ruff/mypy and handed to every extra step. Pytest always runs against the project's configured testpaths.

required
config TempestConfig | None

Resolved [tool.tempest] config controlling the ANN rules and mypy flags layered onto the ruff/mypy steps. When None the default level is used.

None
fast bool

When True, run the pytest step in parallel with pytest-xdist.

False
workers str

The pytest -n value used when fast is True.

DEFAULT_FAST_WORKERS
extra_steps Sequence[CheckStep]

Caller-supplied steps run after mypy and before pytest. Empty by default, which leaves the gate exactly as it was without them.

()
require_xdist bool

With fast, whether a missing pytest-xdist stops the gate or degrades the pytest step to serial — as in :func:run_pytest.

True
step_options StepOptions

Handed to every extra step that declares run_with_options; the built-in steps never see it.

StepOptions()

Returns:

Name Type Description
int int

The first non-zero exit code — a tool's or an extra step's —

int

or 0 when every gate passed.

Source code in tempest_cli/lint.py
def run_full_check(
    target: str,
    *,
    config: TempestConfig | None = None,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    extra_steps: Sequence[CheckStep] = (),
    require_xdist: bool = True,
    step_options: StepOptions = StepOptions(),
) -> int:
    """Run the entire quality gate sequentially.

    Order: ``ruff check`` → ``ruff format --check`` → ``mypy`` → each of
    ``extra_steps``, in the order given → ``pytest``. Every step is
    announced on stderr as ``$ <command line>`` (``$ <name>`` for an
    extra step) and the gate stops at the first non-zero exit code, so
    failures surface fast. The extra steps sit before ``pytest`` because
    they are static checks: a layering rule should fail in a second, not
    after the whole suite.

    With ``fast=True`` the pytest step runs the way :func:`run_pytest`
    runs it with ``fast=True``. The pytest-xdist preflight happens
    *before* the first step, so a required plugin that is missing fails
    in a second instead of after lint and mypy have already run, and a
    merely preferred one degrades the pytest step to serial up front.

    Args:
        target (str): The path inspected by ruff/mypy and handed to every
            extra step. Pytest always runs against the project's
            configured ``testpaths``.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the ANN rules and mypy flags layered onto the
            ruff/mypy steps. When ``None`` the default level is used.
        fast (bool): When True, run the pytest step in parallel with
            pytest-xdist.
        workers (str): The ``pytest -n`` value used when ``fast`` is True.
        extra_steps (Sequence[CheckStep]): Caller-supplied steps run
            after ``mypy`` and before ``pytest``. Empty by default, which
            leaves the gate exactly as it was without them.
        require_xdist (bool): With ``fast``, whether a missing
            pytest-xdist stops the gate or degrades the pytest step to
            serial — as in :func:`run_pytest`.
        step_options (StepOptions): Handed to every extra step that
            declares ``run_with_options``; the built-in steps never see it.

    Returns:
        int: The first non-zero exit code — a tool's or an extra step's —
        or ``0`` when every gate passed.
    """
    if fast:
        decision = _parallel_allowed(require_xdist=require_xdist)
        if decision == "stop":
            return MISSING_TOOL_EXIT_CODE
        fast = decision == "parallel"
    resolved = config or TempestConfig()
    steps: list[tuple[str, Callable[[], int]]] = [
        _tool_step("ruff", ["check", *_ruff_ann_args(resolved), target]),
        _tool_step("ruff", ["format", "--check", target]),
        _tool_step("mypy", [*resolved.mypy_flags(), target]),
        *(_extra_step(step, target, step_options) for step in extra_steps),
        _tool_step("pytest", _pytest_args(None, fast=fast, workers=workers)),
    ]
    for label, run in steps:
        typer.echo(f"$ {label}", err=True)
        code = run()
        if code != 0:
            return code
    return 0

run_mypy

run_mypy(target: str, *, config: TempestConfig | None = None) -> int

Invoke mypy <target> with the configured strictness flags.

Parameters:

Name Type Description Default
target str

The path passed verbatim to mypy.

required
config TempestConfig | None

Resolved [tool.tempest] config controlling the mypy strictness flags layered on top of the project's [tool.mypy]. When None the default level is used.

None

Returns:

Name Type Description
int int

The mypy exit code.

Source code in tempest_cli/lint.py
def run_mypy(target: str, *, config: TempestConfig | None = None) -> int:
    """Invoke ``mypy <target>`` with the configured strictness flags.

    Args:
        target (str): The path passed verbatim to mypy.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the mypy strictness flags layered on top of the
            project's ``[tool.mypy]``. When ``None`` the default level is
            used.

    Returns:
        int: The mypy exit code.
    """
    flags = (config or TempestConfig()).mypy_flags()
    return _execute("mypy", [*flags, target])

run_pytest

run_pytest(
    target: str | None,
    *,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    require_xdist: bool = True,
) -> int

Invoke pytest with an optional target.

With fast=True the suite is spread across pytest-xdist workers: -n <workers> plus -p no:cacheprovider, since several workers writing .pytest_cache at once is a race that buys nothing. The cache is what --lf / --ff read, so those belong to serial runs. Before spawning, the interpreter pytest runs under is asked whether it can import pytest-xdist; what happens when it cannot is require_xdist's call (:func:_parallel_allowed).

Parameters:

Name Type Description Default
target str | None

Optional pytest path filter. None runs the default test suite.

required
fast bool

When True, run the suite in parallel with pytest-xdist.

False
workers str

Worker count for fast — an integer, auto (one per CPU core: physical when psutil is importable) or logical, exactly as pytest -n takes it. Ignored when the run is serial.

DEFAULT_FAST_WORKERS
require_xdist bool

With fast, whether a missing pytest-xdist stops the run (True, the default) or degrades it to serial with a notice (False, what the CLI passes when parallel is only its default).

True

Returns:

Name Type Description
int int

The pytest exit code, or :data:MISSING_TOOL_EXIT_CODE when

int

pytest — or a required pytest-xdist — is absent.

Source code in tempest_cli/lint.py
def run_pytest(
    target: str | None,
    *,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    require_xdist: bool = True,
) -> int:
    """Invoke ``pytest`` with an optional target.

    With ``fast=True`` the suite is spread across pytest-xdist workers:
    ``-n <workers>`` plus ``-p no:cacheprovider``, since several workers
    writing ``.pytest_cache`` at once is a race that buys nothing. The
    cache is what ``--lf`` / ``--ff`` read, so those belong to serial
    runs. Before spawning, the interpreter pytest runs under is asked
    whether it can import pytest-xdist; what happens when it cannot is
    ``require_xdist``'s call (:func:`_parallel_allowed`).

    Args:
        target (str | None): Optional pytest path filter. ``None`` runs
            the default test suite.
        fast (bool): When True, run the suite in parallel with
            pytest-xdist.
        workers (str): Worker count for ``fast`` — an integer, ``auto``
            (one per CPU core: physical when ``psutil`` is importable) or
            ``logical``, exactly as ``pytest -n`` takes it. Ignored when
            the run is serial.
        require_xdist (bool): With ``fast``, whether a missing
            pytest-xdist stops the run (``True``, the default) or degrades
            it to serial with a notice (``False``, what the CLI passes
            when parallel is only its default).

    Returns:
        int: The pytest exit code, or :data:`MISSING_TOOL_EXIT_CODE` when
        pytest — or a required pytest-xdist — is absent.
    """
    if fast:
        decision = _parallel_allowed(require_xdist=require_xdist)
        if decision == "stop":
            return MISSING_TOOL_EXIT_CODE
        fast = decision == "parallel"
    return _execute("pytest", _pytest_args(target, fast=fast, workers=workers))

run_ruff_check

run_ruff_check(target: str, *, config: TempestConfig | None = None) -> int

Invoke ruff check <target> with the configured ANN rules.

Parameters:

Name Type Description Default
target str

The path passed verbatim to ruff.

required
config TempestConfig | None

Resolved [tool.tempest] config controlling the typing-strictness ANN rules layered on. When None the default level is used.

None

Returns:

Name Type Description
int int

The ruff exit code.

Source code in tempest_cli/lint.py
def run_ruff_check(target: str, *, config: TempestConfig | None = None) -> int:
    """Invoke ``ruff check <target>`` with the configured ANN rules.

    Args:
        target (str): The path passed verbatim to ruff.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the typing-strictness ANN rules layered on. When
            ``None`` the default level is used.

    Returns:
        int: The ruff exit code.
    """
    return _execute("ruff", ["check", *_ruff_ann_args(config), target])

run_ruff_fix

run_ruff_fix(
    target: str, *, unsafe: bool = False, config: TempestConfig | None = None
) -> int

Apply every automatic fix ruff can perform, then format the target.

Runs these passes, so the report describes the file the formatter left behind rather than the one it started from:

  1. ruff check --fix-only [--unsafe-fixes] <target> — autofix imports (sort + dedupe), remove unused imports, normalize string quotes, drop trailing whitespace, fix the rest of the lint rules that have safe (or, with unsafe=True, also unsafe) autofixers. --fix-only keeps it from reporting the leftovers, which the formatter may still resolve.
  2. ruff format <target> — normalize indentation, line length, blank lines and trailing newlines.
  3. Long lines the formatter cannot break, shortened where that is safe (see :mod:tempest_cli.rewrite): ruff's JSON report is read, comments past the limit are wrapped and string literals are split into implicitly concatenated parts, each edit kept only when the file's AST is unchanged. The files touched go through ruff format once more.
  4. ruff check <target> — the report of what is left, and the exit code of the command.

When the last pass fails, ruff's JSON report of the same target is read to explain the leftovers (see :mod:tempest_cli.residuals): an E501 that survived is one with no mechanical fix — a dotted name, a long name, an expression — and is named as such with the action that does resolve it, and the residual violations are split into those with no autofix and those --unsafe would fix. The exit code is unaffected, so CI still fails on them.

Parameters:

Name Type Description Default
target str

The path passed verbatim to ruff.

required
unsafe bool

When True, pass --unsafe-fixes so ruff also applies the fixes it would otherwise leave alone.

False
config TempestConfig | None

Resolved [tool.tempest] config controlling the typing-strictness ANN rules layered onto the fix and report passes. When None the default level is used.

None

Returns:

Name Type Description
int int

0 when nothing is left to fix; otherwise the report pass

int

exit code (residual violations), or the format pass exit code

int

when the report was clean. 127 when ruff cannot be found.

Source code in tempest_cli/lint.py
def run_ruff_fix(
    target: str,
    *,
    unsafe: bool = False,
    config: TempestConfig | None = None,
) -> int:
    """Apply every automatic fix ruff can perform, then format the target.

    Runs these passes, so the report describes the file the formatter
    left behind rather than the one it started from:

    1. ``ruff check --fix-only [--unsafe-fixes] <target>`` — autofix
       imports (sort + dedupe), remove unused imports, normalize string
       quotes, drop trailing whitespace, fix the rest of the lint rules
       that have safe (or, with ``unsafe=True``, also unsafe) autofixers.
       ``--fix-only`` keeps it from reporting the leftovers, which the
       formatter may still resolve.
    2. ``ruff format <target>`` — normalize indentation, line length,
       blank lines and trailing newlines.
    3. Long lines the formatter cannot break, shortened where that is
       safe (see :mod:`tempest_cli.rewrite`): ruff's JSON report is read,
       comments past the limit are wrapped and string literals are split
       into implicitly concatenated parts, each edit kept only when the
       file's AST is unchanged. The files touched go through ``ruff
       format`` once more.
    4. ``ruff check <target>`` — the report of what is left, and the exit
       code of the command.

    When the last pass fails, ruff's JSON report of the same target is
    read to explain the leftovers (see :mod:`tempest_cli.residuals`): an
    E501 that survived is one with no mechanical fix — a dotted name, a
    long name, an expression — and is named as such with the action that
    does resolve it, and the residual violations are split into those
    with no autofix and those ``--unsafe`` would fix. The exit code is
    unaffected, so CI still fails on them.

    Args:
        target (str): The path passed verbatim to ruff.
        unsafe (bool): When True, pass ``--unsafe-fixes`` so ruff also
            applies the fixes it would otherwise leave alone.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the typing-strictness ANN rules layered onto the
            fix and report passes. When ``None`` the default level is used.

    Returns:
        int: ``0`` when nothing is left to fix; otherwise the report pass
        exit code (residual violations), or the format pass exit code
        when the report was clean. ``127`` when ruff cannot be found.
    """
    ann_args = _ruff_ann_args(config)
    fix_args = ["check", "--fix-only", *ann_args]
    if unsafe:
        fix_args.append("--unsafe-fixes")
    fix_args.append(target)
    fix_code = _execute("ruff", fix_args)
    if fix_code == MISSING_TOOL_EXIT_CODE:
        return fix_code
    format_code = _execute("ruff", ["format", target])
    report_args = ["check", *ann_args, "--output-format", "json", "--exit-zero"]
    long_lines = _capture("ruff", [*report_args, target])
    shortened = rewrite.rewrite_long_lines(long_lines) if long_lines else []
    if shortened:
        typer.echo(rewrite.render_rewrites(shortened), err=True, nl=False)
        touched = sorted({item.path for item in shortened})
        reformat_code = _execute("ruff", ["format", "--force-exclude", *touched])
        format_code = format_code or reformat_code
    check_code = _execute("ruff", ["check", *ann_args, target])
    if check_code:
        report = _capture("ruff", [*report_args, target])
        found = residuals.collect_residuals(report) if report is not None else None
        if found is not None:
            typer.echo(residuals.render_residuals(found), err=True, nl=False)
    return check_code or format_code

run_ruff_format

run_ruff_format(target: str, *, check: bool) -> int

Invoke ruff format (write or check-only).

Parameters:

Name Type Description Default
target str

The path passed verbatim to ruff.

required
check bool

When True, run ruff format --check (read-only).

required

Returns:

Name Type Description
int int

The ruff exit code.

Source code in tempest_cli/lint.py
def run_ruff_format(target: str, *, check: bool) -> int:
    """Invoke ``ruff format`` (write or check-only).

    Args:
        target (str): The path passed verbatim to ruff.
        check (bool): When True, run ``ruff format --check`` (read-only).

    Returns:
        int: The ruff exit code.
    """
    args = ["format"]
    if check:
        args.append("--check")
    args.append(target)
    return _execute("ruff", args)

generate_pr_prompt

generate_pr_prompt(
    *,
    base: str = DEFAULT_BASE,
    head: str | None = None,
    cwd: Path | None = None,
    template: Path | None = None,
    language: PromptLanguage = PT_BR,
    max_files: int | None = DEFAULT_MAX_FILES,
    max_chars: int | None = DEFAULT_MAX_CHARS,
) -> tuple[str, PullRequestContext, ResolvedTemplate]

Read the repository and render the prompt in one call.

Parameters:

Name Type Description Default
base str

The base ref the pull request targets.

DEFAULT_BASE
head str | None

The branch being described. Defaults to the checked-out one.

None
cwd Path | None

Any directory inside the repository.

None
template Path | None

An explicit template path.

None
language PromptLanguage

Language of the instructions and of the bundled fallback template.

PT_BR
max_files int | None

How many files contribute a patch excerpt. 0 drops every patch, None excerpts them all.

DEFAULT_MAX_FILES
max_chars int | None

Characters kept per patch, or None for the whole patch.

DEFAULT_MAX_CHARS

Returns:

Type Description
str

tuple[str, PullRequestContext, ResolvedTemplate]: The prompt plus

PullRequestContext

the context and template it was built from, so a caller can

ResolvedTemplate

report what was read and what was dropped.

Raises:

Type Description
GitError

When the repository, the base ref or the template path cannot be resolved.

Source code in tempest_cli/pr_prompt.py
def generate_pr_prompt(
    *,
    base: str = DEFAULT_BASE,
    head: str | None = None,
    cwd: Path | None = None,
    template: Path | None = None,
    language: PromptLanguage = PromptLanguage.PT_BR,
    max_files: int | None = DEFAULT_MAX_FILES,
    max_chars: int | None = DEFAULT_MAX_CHARS,
) -> tuple[str, PullRequestContext, ResolvedTemplate]:
    """Read the repository and render the prompt in one call.

    Args:
        base (str): The base ref the pull request targets.
        head (str | None): The branch being described. Defaults to the
            checked-out one.
        cwd (Path | None): Any directory inside the repository.
        template (Path | None): An explicit template path.
        language (PromptLanguage): Language of the instructions and of
            the bundled fallback template.
        max_files (int | None): How many files contribute a patch
            excerpt. ``0`` drops every patch, ``None`` excerpts them all.
        max_chars (int | None): Characters kept per patch, or ``None``
            for the whole patch.

    Returns:
        tuple[str, PullRequestContext, ResolvedTemplate]: The prompt plus
        the context and template it was built from, so a caller can
        report what was read and what was dropped.

    Raises:
        GitError: When the repository, the base ref or the template path
            cannot be resolved.
    """
    context = collect_context(
        base=base,
        head=head,
        cwd=cwd,
        max_files=max_files,
        max_chars=max_chars,
    )
    root = repository_root((cwd or Path.cwd()).expanduser().resolve())
    resolved_template = resolve_template(root, template=template, language=language)
    prompt = build_prompt(context, resolved_template, language=language)
    return prompt, context, resolved_template

Configuração

TempestConfig dataclass

TempestConfig(typing_strictness: TypingStrictness = DEFAULT_TYPING_STRICTNESS)

Resolved [tool.tempest] settings.

Attributes:

Name Type Description
typing_strictness TypingStrictness

How strictly the CLI gates enforce typing. One of "lenient", "standard", "strict".

ruff_ann_select

ruff_ann_select() -> list[str]

Return the ANN rule codes to add to ruff for this level.

Returns:

Type Description
list[str]

list[str]: Rule codes for --extend-select (empty for

list[str]

"lenient"). ANN401 is never present.

Source code in tempest_cli/config.py
def ruff_ann_select(self) -> list[str]:
    """Return the ANN rule codes to add to ruff for this level.

    Returns:
        list[str]: Rule codes for ``--extend-select`` (empty for
        ``"lenient"``). ANN401 is never present.
    """
    return list(_RUFF_ANN_BY_LEVEL[self.typing_strictness])

mypy_flags

mypy_flags() -> list[str]

Return the extra mypy flags to add for this level.

Returns:

Type Description
list[str]

list[str]: Flags layered on top of the project's

list[str]

[tool.mypy] config (empty for "lenient").

Source code in tempest_cli/config.py
def mypy_flags(self) -> list[str]:
    """Return the extra mypy flags to add for this level.

    Returns:
        list[str]: Flags layered on top of the project's
        ``[tool.mypy]`` config (empty for ``"lenient"``).
    """
    return list(_MYPY_FLAGS_BY_LEVEL[self.typing_strictness])

TypingStrictness module-attribute

TypingStrictness = Literal['lenient', 'standard', 'strict']

Allowed values for [tool.tempest] typing_strictness.

load_tempest_config

load_tempest_config(start: Path | None = None) -> TempestConfig

Load [tool.tempest] from the nearest pyproject.toml.

Parameters:

Name Type Description Default
start Path | None

Directory to begin the search. Defaults to the current working directory.

None

Returns:

Name Type Description
TempestConfig TempestConfig

The resolved config. Falls back to defaults when

TempestConfig

no pyproject.toml or no [tool.tempest] table is found.

Raises:

Type Description
ValueError

When typing_strictness is present but invalid.

Source code in tempest_cli/config.py
def load_tempest_config(start: Path | None = None) -> TempestConfig:
    """Load ``[tool.tempest]`` from the nearest ``pyproject.toml``.

    Args:
        start (Path | None): Directory to begin the search. Defaults to
            the current working directory.

    Returns:
        TempestConfig: The resolved config. Falls back to defaults when
        no ``pyproject.toml`` or no ``[tool.tempest]`` table is found.

    Raises:
        ValueError: When ``typing_strictness`` is present but invalid.
    """
    pyproject = find_pyproject(start)
    if pyproject is None:
        return TempestConfig()
    with pyproject.open("rb") as handle:
        data = tomllib.load(handle)
    table = data.get("tool", {}).get("tempest", {})
    strictness = (
        _coerce_strictness(table["typing_strictness"], source=str(pyproject))
        if "typing_strictness" in table
        else DEFAULT_TYPING_STRICTNESS
    )
    return TempestConfig(typing_strictness=strictness)

find_pyproject

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

Locate the nearest pyproject.toml walking up from start.

Parameters:

Name Type Description Default
start Path | None

Directory to begin the search. Defaults to the current working directory.

None

Returns:

Type Description
Path | None

Path | None: The path to the first pyproject.toml found in

Path | None

start or an ancestor, or None when none exists.

Source code in tempest_cli/config.py
def find_pyproject(start: Path | None = None) -> Path | None:
    """Locate the nearest ``pyproject.toml`` walking up from ``start``.

    Args:
        start (Path | None): Directory to begin the search. Defaults to
            the current working directory.

    Returns:
        Path | None: The path to the first ``pyproject.toml`` found in
        ``start`` or an ancestor, or ``None`` when none exists.
    """
    current = (start or Path.cwd()).resolve()
    for directory in (current, *current.parents):
        candidate = directory / "pyproject.toml"
        if candidate.is_file():
            return candidate
    return None

Runners

run_ruff_check

run_ruff_check(target: str, *, config: TempestConfig | None = None) -> int

Invoke ruff check <target> with the configured ANN rules.

Parameters:

Name Type Description Default
target str

The path passed verbatim to ruff.

required
config TempestConfig | None

Resolved [tool.tempest] config controlling the typing-strictness ANN rules layered on. When None the default level is used.

None

Returns:

Name Type Description
int int

The ruff exit code.

Source code in tempest_cli/lint.py
def run_ruff_check(target: str, *, config: TempestConfig | None = None) -> int:
    """Invoke ``ruff check <target>`` with the configured ANN rules.

    Args:
        target (str): The path passed verbatim to ruff.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the typing-strictness ANN rules layered on. When
            ``None`` the default level is used.

    Returns:
        int: The ruff exit code.
    """
    return _execute("ruff", ["check", *_ruff_ann_args(config), target])

run_ruff_fix

run_ruff_fix(
    target: str, *, unsafe: bool = False, config: TempestConfig | None = None
) -> int

Apply every automatic fix ruff can perform, then format the target.

Runs these passes, so the report describes the file the formatter left behind rather than the one it started from:

  1. ruff check --fix-only [--unsafe-fixes] <target> — autofix imports (sort + dedupe), remove unused imports, normalize string quotes, drop trailing whitespace, fix the rest of the lint rules that have safe (or, with unsafe=True, also unsafe) autofixers. --fix-only keeps it from reporting the leftovers, which the formatter may still resolve.
  2. ruff format <target> — normalize indentation, line length, blank lines and trailing newlines.
  3. Long lines the formatter cannot break, shortened where that is safe (see :mod:tempest_cli.rewrite): ruff's JSON report is read, comments past the limit are wrapped and string literals are split into implicitly concatenated parts, each edit kept only when the file's AST is unchanged. The files touched go through ruff format once more.
  4. ruff check <target> — the report of what is left, and the exit code of the command.

When the last pass fails, ruff's JSON report of the same target is read to explain the leftovers (see :mod:tempest_cli.residuals): an E501 that survived is one with no mechanical fix — a dotted name, a long name, an expression — and is named as such with the action that does resolve it, and the residual violations are split into those with no autofix and those --unsafe would fix. The exit code is unaffected, so CI still fails on them.

Parameters:

Name Type Description Default
target str

The path passed verbatim to ruff.

required
unsafe bool

When True, pass --unsafe-fixes so ruff also applies the fixes it would otherwise leave alone.

False
config TempestConfig | None

Resolved [tool.tempest] config controlling the typing-strictness ANN rules layered onto the fix and report passes. When None the default level is used.

None

Returns:

Name Type Description
int int

0 when nothing is left to fix; otherwise the report pass

int

exit code (residual violations), or the format pass exit code

int

when the report was clean. 127 when ruff cannot be found.

Source code in tempest_cli/lint.py
def run_ruff_fix(
    target: str,
    *,
    unsafe: bool = False,
    config: TempestConfig | None = None,
) -> int:
    """Apply every automatic fix ruff can perform, then format the target.

    Runs these passes, so the report describes the file the formatter
    left behind rather than the one it started from:

    1. ``ruff check --fix-only [--unsafe-fixes] <target>`` — autofix
       imports (sort + dedupe), remove unused imports, normalize string
       quotes, drop trailing whitespace, fix the rest of the lint rules
       that have safe (or, with ``unsafe=True``, also unsafe) autofixers.
       ``--fix-only`` keeps it from reporting the leftovers, which the
       formatter may still resolve.
    2. ``ruff format <target>`` — normalize indentation, line length,
       blank lines and trailing newlines.
    3. Long lines the formatter cannot break, shortened where that is
       safe (see :mod:`tempest_cli.rewrite`): ruff's JSON report is read,
       comments past the limit are wrapped and string literals are split
       into implicitly concatenated parts, each edit kept only when the
       file's AST is unchanged. The files touched go through ``ruff
       format`` once more.
    4. ``ruff check <target>`` — the report of what is left, and the exit
       code of the command.

    When the last pass fails, ruff's JSON report of the same target is
    read to explain the leftovers (see :mod:`tempest_cli.residuals`): an
    E501 that survived is one with no mechanical fix — a dotted name, a
    long name, an expression — and is named as such with the action that
    does resolve it, and the residual violations are split into those
    with no autofix and those ``--unsafe`` would fix. The exit code is
    unaffected, so CI still fails on them.

    Args:
        target (str): The path passed verbatim to ruff.
        unsafe (bool): When True, pass ``--unsafe-fixes`` so ruff also
            applies the fixes it would otherwise leave alone.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the typing-strictness ANN rules layered onto the
            fix and report passes. When ``None`` the default level is used.

    Returns:
        int: ``0`` when nothing is left to fix; otherwise the report pass
        exit code (residual violations), or the format pass exit code
        when the report was clean. ``127`` when ruff cannot be found.
    """
    ann_args = _ruff_ann_args(config)
    fix_args = ["check", "--fix-only", *ann_args]
    if unsafe:
        fix_args.append("--unsafe-fixes")
    fix_args.append(target)
    fix_code = _execute("ruff", fix_args)
    if fix_code == MISSING_TOOL_EXIT_CODE:
        return fix_code
    format_code = _execute("ruff", ["format", target])
    report_args = ["check", *ann_args, "--output-format", "json", "--exit-zero"]
    long_lines = _capture("ruff", [*report_args, target])
    shortened = rewrite.rewrite_long_lines(long_lines) if long_lines else []
    if shortened:
        typer.echo(rewrite.render_rewrites(shortened), err=True, nl=False)
        touched = sorted({item.path for item in shortened})
        reformat_code = _execute("ruff", ["format", "--force-exclude", *touched])
        format_code = format_code or reformat_code
    check_code = _execute("ruff", ["check", *ann_args, target])
    if check_code:
        report = _capture("ruff", [*report_args, target])
        found = residuals.collect_residuals(report) if report is not None else None
        if found is not None:
            typer.echo(residuals.render_residuals(found), err=True, nl=False)
    return check_code or format_code

run_ruff_format

run_ruff_format(target: str, *, check: bool) -> int

Invoke ruff format (write or check-only).

Parameters:

Name Type Description Default
target str

The path passed verbatim to ruff.

required
check bool

When True, run ruff format --check (read-only).

required

Returns:

Name Type Description
int int

The ruff exit code.

Source code in tempest_cli/lint.py
def run_ruff_format(target: str, *, check: bool) -> int:
    """Invoke ``ruff format`` (write or check-only).

    Args:
        target (str): The path passed verbatim to ruff.
        check (bool): When True, run ``ruff format --check`` (read-only).

    Returns:
        int: The ruff exit code.
    """
    args = ["format"]
    if check:
        args.append("--check")
    args.append(target)
    return _execute("ruff", args)

run_mypy

run_mypy(target: str, *, config: TempestConfig | None = None) -> int

Invoke mypy <target> with the configured strictness flags.

Parameters:

Name Type Description Default
target str

The path passed verbatim to mypy.

required
config TempestConfig | None

Resolved [tool.tempest] config controlling the mypy strictness flags layered on top of the project's [tool.mypy]. When None the default level is used.

None

Returns:

Name Type Description
int int

The mypy exit code.

Source code in tempest_cli/lint.py
def run_mypy(target: str, *, config: TempestConfig | None = None) -> int:
    """Invoke ``mypy <target>`` with the configured strictness flags.

    Args:
        target (str): The path passed verbatim to mypy.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the mypy strictness flags layered on top of the
            project's ``[tool.mypy]``. When ``None`` the default level is
            used.

    Returns:
        int: The mypy exit code.
    """
    flags = (config or TempestConfig()).mypy_flags()
    return _execute("mypy", [*flags, target])

run_pytest

run_pytest(
    target: str | None,
    *,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    require_xdist: bool = True,
) -> int

Invoke pytest with an optional target.

With fast=True the suite is spread across pytest-xdist workers: -n <workers> plus -p no:cacheprovider, since several workers writing .pytest_cache at once is a race that buys nothing. The cache is what --lf / --ff read, so those belong to serial runs. Before spawning, the interpreter pytest runs under is asked whether it can import pytest-xdist; what happens when it cannot is require_xdist's call (:func:_parallel_allowed).

Parameters:

Name Type Description Default
target str | None

Optional pytest path filter. None runs the default test suite.

required
fast bool

When True, run the suite in parallel with pytest-xdist.

False
workers str

Worker count for fast — an integer, auto (one per CPU core: physical when psutil is importable) or logical, exactly as pytest -n takes it. Ignored when the run is serial.

DEFAULT_FAST_WORKERS
require_xdist bool

With fast, whether a missing pytest-xdist stops the run (True, the default) or degrades it to serial with a notice (False, what the CLI passes when parallel is only its default).

True

Returns:

Name Type Description
int int

The pytest exit code, or :data:MISSING_TOOL_EXIT_CODE when

int

pytest — or a required pytest-xdist — is absent.

Source code in tempest_cli/lint.py
def run_pytest(
    target: str | None,
    *,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    require_xdist: bool = True,
) -> int:
    """Invoke ``pytest`` with an optional target.

    With ``fast=True`` the suite is spread across pytest-xdist workers:
    ``-n <workers>`` plus ``-p no:cacheprovider``, since several workers
    writing ``.pytest_cache`` at once is a race that buys nothing. The
    cache is what ``--lf`` / ``--ff`` read, so those belong to serial
    runs. Before spawning, the interpreter pytest runs under is asked
    whether it can import pytest-xdist; what happens when it cannot is
    ``require_xdist``'s call (:func:`_parallel_allowed`).

    Args:
        target (str | None): Optional pytest path filter. ``None`` runs
            the default test suite.
        fast (bool): When True, run the suite in parallel with
            pytest-xdist.
        workers (str): Worker count for ``fast`` — an integer, ``auto``
            (one per CPU core: physical when ``psutil`` is importable) or
            ``logical``, exactly as ``pytest -n`` takes it. Ignored when
            the run is serial.
        require_xdist (bool): With ``fast``, whether a missing
            pytest-xdist stops the run (``True``, the default) or degrades
            it to serial with a notice (``False``, what the CLI passes
            when parallel is only its default).

    Returns:
        int: The pytest exit code, or :data:`MISSING_TOOL_EXIT_CODE` when
        pytest — or a required pytest-xdist — is absent.
    """
    if fast:
        decision = _parallel_allowed(require_xdist=require_xdist)
        if decision == "stop":
            return MISSING_TOOL_EXIT_CODE
        fast = decision == "parallel"
    return _execute("pytest", _pytest_args(target, fast=fast, workers=workers))

run_full_check

run_full_check(
    target: str,
    *,
    config: TempestConfig | None = None,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    extra_steps: Sequence[CheckStep] = (),
    require_xdist: bool = True,
    step_options: StepOptions = StepOptions(),
) -> int

Run the entire quality gate sequentially.

Order: ruff check → ruff format --check → mypy → each of extra_steps, in the order given → pytest. Every step is announced on stderr as $ <command line> ($ <name> for an extra step) and the gate stops at the first non-zero exit code, so failures surface fast. The extra steps sit before pytest because they are static checks: a layering rule should fail in a second, not after the whole suite.

With fast=True the pytest step runs the way :func:run_pytest runs it with fast=True. The pytest-xdist preflight happens before the first step, so a required plugin that is missing fails in a second instead of after lint and mypy have already run, and a merely preferred one degrades the pytest step to serial up front.

Parameters:

Name Type Description Default
target str

The path inspected by ruff/mypy and handed to every extra step. Pytest always runs against the project's configured testpaths.

required
config TempestConfig | None

Resolved [tool.tempest] config controlling the ANN rules and mypy flags layered onto the ruff/mypy steps. When None the default level is used.

None
fast bool

When True, run the pytest step in parallel with pytest-xdist.

False
workers str

The pytest -n value used when fast is True.

DEFAULT_FAST_WORKERS
extra_steps Sequence[CheckStep]

Caller-supplied steps run after mypy and before pytest. Empty by default, which leaves the gate exactly as it was without them.

()
require_xdist bool

With fast, whether a missing pytest-xdist stops the gate or degrades the pytest step to serial — as in :func:run_pytest.

True
step_options StepOptions

Handed to every extra step that declares run_with_options; the built-in steps never see it.

StepOptions()

Returns:

Name Type Description
int int

The first non-zero exit code — a tool's or an extra step's —

int

or 0 when every gate passed.

Source code in tempest_cli/lint.py
def run_full_check(
    target: str,
    *,
    config: TempestConfig | None = None,
    fast: bool = False,
    workers: str = DEFAULT_FAST_WORKERS,
    extra_steps: Sequence[CheckStep] = (),
    require_xdist: bool = True,
    step_options: StepOptions = StepOptions(),
) -> int:
    """Run the entire quality gate sequentially.

    Order: ``ruff check`` → ``ruff format --check`` → ``mypy`` → each of
    ``extra_steps``, in the order given → ``pytest``. Every step is
    announced on stderr as ``$ <command line>`` (``$ <name>`` for an
    extra step) and the gate stops at the first non-zero exit code, so
    failures surface fast. The extra steps sit before ``pytest`` because
    they are static checks: a layering rule should fail in a second, not
    after the whole suite.

    With ``fast=True`` the pytest step runs the way :func:`run_pytest`
    runs it with ``fast=True``. The pytest-xdist preflight happens
    *before* the first step, so a required plugin that is missing fails
    in a second instead of after lint and mypy have already run, and a
    merely preferred one degrades the pytest step to serial up front.

    Args:
        target (str): The path inspected by ruff/mypy and handed to every
            extra step. Pytest always runs against the project's
            configured ``testpaths``.
        config (TempestConfig | None): Resolved ``[tool.tempest]`` config
            controlling the ANN rules and mypy flags layered onto the
            ruff/mypy steps. When ``None`` the default level is used.
        fast (bool): When True, run the pytest step in parallel with
            pytest-xdist.
        workers (str): The ``pytest -n`` value used when ``fast`` is True.
        extra_steps (Sequence[CheckStep]): Caller-supplied steps run
            after ``mypy`` and before ``pytest``. Empty by default, which
            leaves the gate exactly as it was without them.
        require_xdist (bool): With ``fast``, whether a missing
            pytest-xdist stops the gate or degrades the pytest step to
            serial — as in :func:`run_pytest`.
        step_options (StepOptions): Handed to every extra step that
            declares ``run_with_options``; the built-in steps never see it.

    Returns:
        int: The first non-zero exit code — a tool's or an extra step's —
        or ``0`` when every gate passed.
    """
    if fast:
        decision = _parallel_allowed(require_xdist=require_xdist)
        if decision == "stop":
            return MISSING_TOOL_EXIT_CODE
        fast = decision == "parallel"
    resolved = config or TempestConfig()
    steps: list[tuple[str, Callable[[], int]]] = [
        _tool_step("ruff", ["check", *_ruff_ann_args(resolved), target]),
        _tool_step("ruff", ["format", "--check", target]),
        _tool_step("mypy", [*resolved.mypy_flags(), target]),
        *(_extra_step(step, target, step_options) for step in extra_steps),
        _tool_step("pytest", _pytest_args(None, fast=fast, workers=workers)),
    ]
    for label, run in steps:
        typer.echo(f"$ {label}", err=True)
        code = run()
        if code != 0:
            return code
    return 0

Passos extras

CheckStep dataclass

CheckStep(
    name: str,
    run: Callable[[str], int],
    run_with_options: Callable[[str, StepOptions], int] | None = None,
)

A step check runs after mypy and before pytest.

The step owns its own output: whatever run prints is what the user reads, so a failing step should name the file, the line and the fix. check echoes $ <name> to stderr before calling it, the way it echoes the command line of every built-in step.

Attributes:

Name Type Description
name str

Label echoed as $ <name> before the step runs.

run Callable[[str], int]

Called with the check target (the path given on the command line, . by default); returns an exit code, 0 meaning the step passed. A non-zero code stops the gate and becomes its exit code.

run_with_options Callable[[str, StepOptions], int] | None

Called instead of run when set, with the target and the :class:StepOptions check parsed. None (the default) marks a step with no options; check --rule refuses to run when no step declares this.

Example
from tempest_cli import CheckStep, run_full_check


def no_todo(target: str) -> int:
    return 0


exit_code: int = run_full_check(
    ".", extra_steps=[CheckStep(name="no-todo", run=no_todo)]
)

StepOptions dataclass

StepOptions(rules: tuple[str, ...] = (), strict: bool | None = None)

Options of check that only the extra steps read.

check --rule <CODE> and check --strict mean nothing to ruff, mypy or pytest; they are for a step that reports rule codes with a severity. tempest-cli parses them and hands them over as typed values, so a step never parses the command line itself.

Attributes:

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

Rule codes to report, as typed (--rule repeated). Empty means every rule.

strict bool | None

--strict / --no-strict. None when neither was typed, so the step falls back to its own default.

given property

given: bool

Tell whether any option was typed.

Returns:

Name Type Description
bool bool

True when --rule or --strict / --no-strict

bool

was passed.


Prompt de PR

generate_pr_prompt

generate_pr_prompt(
    *,
    base: str = DEFAULT_BASE,
    head: str | None = None,
    cwd: Path | None = None,
    template: Path | None = None,
    language: PromptLanguage = PT_BR,
    max_files: int | None = DEFAULT_MAX_FILES,
    max_chars: int | None = DEFAULT_MAX_CHARS,
) -> tuple[str, PullRequestContext, ResolvedTemplate]

Read the repository and render the prompt in one call.

Parameters:

Name Type Description Default
base str

The base ref the pull request targets.

DEFAULT_BASE
head str | None

The branch being described. Defaults to the checked-out one.

None
cwd Path | None

Any directory inside the repository.

None
template Path | None

An explicit template path.

None
language PromptLanguage

Language of the instructions and of the bundled fallback template.

PT_BR
max_files int | None

How many files contribute a patch excerpt. 0 drops every patch, None excerpts them all.

DEFAULT_MAX_FILES
max_chars int | None

Characters kept per patch, or None for the whole patch.

DEFAULT_MAX_CHARS

Returns:

Type Description
str

tuple[str, PullRequestContext, ResolvedTemplate]: The prompt plus

PullRequestContext

the context and template it was built from, so a caller can

ResolvedTemplate

report what was read and what was dropped.

Raises:

Type Description
GitError

When the repository, the base ref or the template path cannot be resolved.

Source code in tempest_cli/pr_prompt.py
def generate_pr_prompt(
    *,
    base: str = DEFAULT_BASE,
    head: str | None = None,
    cwd: Path | None = None,
    template: Path | None = None,
    language: PromptLanguage = PromptLanguage.PT_BR,
    max_files: int | None = DEFAULT_MAX_FILES,
    max_chars: int | None = DEFAULT_MAX_CHARS,
) -> tuple[str, PullRequestContext, ResolvedTemplate]:
    """Read the repository and render the prompt in one call.

    Args:
        base (str): The base ref the pull request targets.
        head (str | None): The branch being described. Defaults to the
            checked-out one.
        cwd (Path | None): Any directory inside the repository.
        template (Path | None): An explicit template path.
        language (PromptLanguage): Language of the instructions and of
            the bundled fallback template.
        max_files (int | None): How many files contribute a patch
            excerpt. ``0`` drops every patch, ``None`` excerpts them all.
        max_chars (int | None): Characters kept per patch, or ``None``
            for the whole patch.

    Returns:
        tuple[str, PullRequestContext, ResolvedTemplate]: The prompt plus
        the context and template it was built from, so a caller can
        report what was read and what was dropped.

    Raises:
        GitError: When the repository, the base ref or the template path
            cannot be resolved.
    """
    context = collect_context(
        base=base,
        head=head,
        cwd=cwd,
        max_files=max_files,
        max_chars=max_chars,
    )
    root = repository_root((cwd or Path.cwd()).expanduser().resolve())
    resolved_template = resolve_template(root, template=template, language=language)
    prompt = build_prompt(context, resolved_template, language=language)
    return prompt, context, resolved_template

PromptLanguage

Bases: StrEnum

Language of the bundled template and of the prompt's instructions.

Only the bundled template is translated: a repository template is used verbatim in whatever language it was written in, since it is that repository's contract.

GitError

Bases: RuntimeError

A git invocation failed, or the repository lacks what was asked.

Carries the command's own stderr so the caller can print the reason git gave instead of a generic failure.


CLI

register_commands

register_commands(app: Typer, *, extra_steps: Sequence[CheckStep] = ()) -> None

Register the quality gate on an existing Typer application.

Parameters:

Name Type Description Default
app Typer

The application to extend. Its own name and help text are left untouched; only commands are added.

required
extra_steps Sequence[CheckStep]

Steps the check command runs after mypy and before pytest, in every variant (parallel or --serial). This is how a framework adds its own rules to the gate without this package knowing about it. Empty by default.

()
Example
import typer

from tempest_cli.main import register_commands

cli: typer.Typer = typer.Typer(name="mytool")
register_commands(cli)

With a step of its own in check:

import typer

from tempest_cli import CheckStep
from tempest_cli.main import register_commands


def layers(target: str) -> int:
    return 0


cli: typer.Typer = typer.Typer(name="mytool")
register_commands(cli, extra_steps=[CheckStep(name="layers", run=layers)])
Source code in tempest_cli/main.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def register_commands(
    app: typer.Typer,
    *,
    extra_steps: Sequence[CheckStep] = (),
) -> None:
    """Register the quality gate on an existing Typer application.

    Args:
        app (typer.Typer): The application to extend. Its own name and
            help text are left untouched; only commands are added.
        extra_steps (Sequence[CheckStep]): Steps the ``check`` command
            runs after ``mypy`` and before ``pytest``, in every variant
            (parallel or ``--serial``). This is how a framework adds its own
            rules to the gate without this package knowing about it.
            Empty by default.

    Example:
        ```python
        import typer

        from tempest_cli.main import register_commands

        cli: typer.Typer = typer.Typer(name="mytool")
        register_commands(cli)
        ```

        With a step of its own in ``check``:

        ```python
        import typer

        from tempest_cli import CheckStep
        from tempest_cli.main import register_commands


        def layers(target: str) -> int:
            return 0


        cli: typer.Typer = typer.Typer(name="mytool")
        register_commands(cli, extra_steps=[CheckStep(name="layers", run=layers)])
        ```
    """

    @app.command("lint")
    def lint_cmd(
        target: Annotated[
            str,
            typer.Argument(help="Path to lint. Defaults to the current directory."),
        ] = ".",
        strictness: Annotated[str | None, _strictness_option()] = None,
    ) -> None:
        """Run ``ruff check`` on the target."""
        config = _resolve_config(target, strictness)
        raise typer.Exit(lint_module.run_ruff_check(target, config=config))

    @app.command("fix")
    def fix_cmd(
        target: Annotated[
            str,
            typer.Argument(help="Path to fix. Defaults to the current directory."),
        ] = ".",
        unsafe: Annotated[
            bool,
            typer.Option(
                "--unsafe",
                help=(
                    "Also apply ruff's unsafe autofixes (rules with possible "
                    "behavior changes). Off by default — review the diff after "
                    "enabling."
                ),
            ),
        ] = False,
        strictness: Annotated[str | None, _strictness_option()] = None,
    ) -> None:
        """Apply every ruff autofix + format the target in one pass.

        Runs ``ruff check --fix-only``, ``ruff format``, then ``ruff
        check`` to report what is left: sorts and dedupes imports, drops
        unused imports, normalizes string quotes, removes trailing
        whitespace, normalizes indentation, line length and blank lines.

        A line still too long after formatting is one ruff format has
        nowhere to break. Long comments are wrapped and long strings are
        split into concatenated parts, each edit kept only when the AST
        is unchanged. Whatever is left (a dotted name, a long name, an
        expression) is named with the action that resolves it, and the
        leftovers are split into those with no autofix and those
        --unsafe would fix.
        """
        config = _resolve_config(target, strictness)
        raise typer.Exit(lint_module.run_ruff_fix(target, unsafe=unsafe, config=config))

    @app.command("format")
    def format_cmd(
        target: Annotated[
            str,
            typer.Argument(help="Path to format. Defaults to the current directory."),
        ] = ".",
    ) -> None:
        """Run ``ruff format`` on the target (writes files)."""
        raise typer.Exit(lint_module.run_ruff_format(target, check=False))

    @app.command("fmt-check")
    def fmt_check_cmd(
        target: Annotated[
            str,
            typer.Argument(help="Path to inspect. Defaults to the current directory."),
        ] = ".",
    ) -> None:
        """Run ``ruff format --check`` on the target (read-only)."""
        raise typer.Exit(lint_module.run_ruff_format(target, check=True))

    @app.command("type")
    def type_cmd(
        target: Annotated[
            str,
            typer.Argument(help="Package/path to type-check."),
        ] = ".",
        strictness: Annotated[str | None, _strictness_option()] = None,
    ) -> None:
        """Run ``mypy`` against the target."""
        config = _resolve_config(target, strictness)
        raise typer.Exit(lint_module.run_mypy(target, config=config))

    @app.command("test")
    def test_cmd(
        ctx: typer.Context,
        target: Annotated[
            str | None,
            typer.Argument(help="Optional pytest path filter."),
        ] = None,
        fast: Annotated[bool, _fast_option()] = True,
        workers: Annotated[str, _workers_option()] = lint_module.DEFAULT_FAST_WORKERS,
    ) -> None:
        """Run ``pytest`` (forwarding the optional path argument).

        The suite runs in parallel by default: pytest-xdist workers (-n
        auto unless --workers says otherwise), with the cache plugin off,
        so --lf / --ff belong to --serial runs. Without pytest-xdist in the
        environment pytest runs in, the default falls back to a serial run
        and says how to install it; --fast makes that an error (exit code
        127) instead.

        A test that fails only in parallel shares state with another
        one: a file, a port, a module-level global, a fixed sleep racing
        a busy machine. Before treating it as a regression, rerun it
        alone, serially, with its node id as the target
        (test --serial tests/test_x.py::test_name). Passing alone means the
        defect is the test's isolation, not the change under review.
        """
        resolved_workers = _resolve_workers(ctx, fast=fast, workers=workers)
        raise typer.Exit(
            lint_module.run_pytest(
                target,
                fast=fast,
                workers=resolved_workers,
                require_xdist=_require_xdist(ctx),
            )
        )

    @app.command("check")
    def check_cmd(
        ctx: typer.Context,
        target: Annotated[
            str,
            typer.Argument(help="Path to inspect. Defaults to the current directory."),
        ] = ".",
        strictness: Annotated[str | None, _strictness_option()] = None,
        fast: Annotated[bool, _fast_option()] = True,
        workers: Annotated[str, _workers_option()] = lint_module.DEFAULT_FAST_WORKERS,
        rule: Annotated[
            list[str] | None,
            typer.Option(
                "--rule",
                help="Report only this rule code in the host's steps "
                "(repeatable), to migrate one rule at a time.",
            ),
        ] = None,
        strict: Annotated[
            bool | None,
            typer.Option(
                "--strict/--no-strict",
                help="Make the host's steps fail on warnings too. Defaults to "
                "the step's own configuration.",
            ),
        ] = None,
    ) -> None:
        """Run the full quality gate (lint + fmt-check + type + test).

        The test step runs as ``test`` does — in parallel unless
        ``--serial`` — with the pytest-xdist check made before the first
        step. Steps the host CLI registered run after type and before test;
        ``--rule`` and ``--strict`` are handed to them.
        """
        options = _step_options(rule, strict, extra_steps)
        config = _resolve_config(target, strictness)
        resolved_workers = _resolve_workers(ctx, fast=fast, workers=workers)
        raise typer.Exit(
            lint_module.run_full_check(
                target,
                config=config,
                fast=fast,
                workers=resolved_workers,
                extra_steps=extra_steps,
                require_xdist=_require_xdist(ctx),
                step_options=options,
            )
        )

    @app.command("pr-prompt")
    def pr_prompt_cmd(
        ctx: typer.Context,
        base: Annotated[
            str,
            typer.Argument(
                help="Base ref the pull request targets. When the local ref is "
                "missing, 'origin/<base>' is tried before failing.",
            ),
        ] = pr_prompt_module.DEFAULT_BASE,
        head: Annotated[
            str | None,
            typer.Option(
                "--head",
                help="Branch to describe. Defaults to the checked-out one "
                "(the short sha when HEAD is detached).",
            ),
        ] = None,
        out: Annotated[
            Path | None,
            typer.Option(
                "--out",
                "-o",
                help="Write the prompt to this file instead of stdout.",
            ),
        ] = None,
        template: Annotated[
            Path | None,
            typer.Option(
                "--template",
                "-t",
                help="Template to fill in. Wins over the repository's own "
                "template and over the bundled default.",
            ),
        ] = None,
        language: Annotated[
            pr_prompt_module.PromptLanguage,
            typer.Option(
                "--lang",
                "-l",
                help="Language of the instructions and of the bundled template. "
                "A repository template is always used as written.",
            ),
        ] = pr_prompt_module.PromptLanguage.PT_BR,
        full: Annotated[
            bool,
            typer.Option(
                "--full",
                help="Excerpt every changed file, with its whole patch. Lifts "
                "both bounds at once; cannot be combined with --max-files / "
                "--max-chars.",
            ),
        ] = False,
        max_files: Annotated[
            int,
            typer.Option(
                "--max-files",
                min=0,
                help="How many files contribute a patch excerpt, most-changed "
                "first. 0 keeps the file list and drops every patch.",
            ),
        ] = pr_prompt_module.DEFAULT_MAX_FILES,
        max_chars: Annotated[
            int,
            typer.Option(
                "--max-chars",
                min=1,
                help="Characters kept per patch (cut on a line boundary).",
            ),
        ] = pr_prompt_module.DEFAULT_MAX_CHARS,
        target: Annotated[
            str,
            typer.Option(
                "--path",
                "-p",
                help="Directory inside the repository to read. Defaults to the "
                "current working directory.",
            ),
        ] = ".",
    ) -> None:
        """Build the prompt that makes an AI fill this branch's PR description.

        The prompt carries three things: the pull-request template (the
        repository's own when it has one, otherwise the bundled PT-BR /
        EN-US default), the rules that stop the model from returning the
        template with its placeholders still in it, and the branch
        context — commit subjects, the changed-file list and a bounded
        excerpt of each file's patch.

        It goes to stdout, so it pipes into whichever assistant you run::

            tempest-cli pr-prompt | claude -p
            tempest-cli pr-prompt develop --lang en --out pr_prompt.txt

        Diffs are read as ``base...head`` — the merge-base diff the forge
        shows on the pull request — so commits that landed on the base
        after the branch started are not attributed to it.

        The commit list and the changed-file list are always complete;
        only the patch excerpts are bounded, and whatever ``--max-files``
        / ``--max-chars`` leave out is stated inside the prompt, so a
        partial diff reads as partial instead of as the whole change.
        ``--full`` lifts both bounds for a branch small enough to send
        whole.

        Raises:
            typer.Exit: ``2`` when ``--full`` is combined with an explicit
                bound, when git fails or when a ref does not resolve;
                ``1`` when the comparison holds no commit and no changed
                file.
        """
        if full:
            conflicting = [
                name
                for option, name in (
                    ("max_files", "--max-files"),
                    ("max_chars", "--max-chars"),
                )
                if getattr(ctx.get_parameter_source(option), "name", "")
                == "COMMANDLINE"
            ]
            if conflicting:
                typer.secho(
                    f"error: --full already lifts every bound; drop "
                    f"{' and '.join(conflicting)}.",
                    fg="red",
                    err=True,
                )
                raise typer.Exit(2)

        try:
            prompt, context, resolved = pr_prompt_module.generate_pr_prompt(
                base=base,
                head=head,
                cwd=Path(target).expanduser(),
                template=template,
                language=language,
                max_files=None if full else max_files,
                max_chars=None if full else max_chars,
            )
        except pr_prompt_module.GitError as exc:
            typer.secho(f"error: {exc}", fg="red", err=True)
            raise typer.Exit(2) from exc

        if not context.commits and not context.files:
            typer.secho(
                f"error: `{context.head}` adds nothing over `{context.base}` — "
                "no commits and no changed files. Check the base ref.",
                fg="red",
                err=True,
            )
            raise typer.Exit(1)

        if out is not None:
            destination = out.expanduser()
            destination.write_text(prompt, encoding="utf-8")
            typer.secho(f"wrote {destination}", fg="green", err=True)
        else:
            typer.echo(prompt, nl=False)

        typer.secho(f"template: {resolved.source}", fg="cyan", err=True)
        omitted = (
            f", {context.omitted_files} file(s) without a patch"
            if context.omitted_files
            else ""
        )
        typer.secho(
            f"{len(context.commits)} commit(s), {len(context.files)} changed "
            f"file(s), {len(context.excerpts)} excerpt(s){omitted}.",
            fg="cyan",
            err=True,
        )