Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- Commands that take `--name` / `--type` / `--content` style flags now
emit a `hint:` line with the correct invocation when invoked with
positional values (e.g. `rc0 record set example.com www A 1.2.3.4`).
Closes the long-standing v1.0.7 polish item where Typer's generic
"Missing option" error left users without a path forward.

## [2.0.1] — 2026-04-29

### Fixed
Expand Down
66 changes: 60 additions & 6 deletions src/rc0/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,17 +293,71 @@ def _no_color_env() -> bool:
# ---------------------------------------------------------------- entrypoint


def main() -> None:
"""CLI entry point registered in ``pyproject.toml`` as ``rc0``."""
_USAGE_HINT_TRIGGERS = (
"Missing option",
"Missing argument",
"Got unexpected extra argument",
)


def _format_usage_hint(exc: click.UsageError) -> str | None:
"""Return a hint listing the command's required flags, or None.

Triggers when Click reports a missing option/argument or unexpected
extra positional argument and the command has at least one required
Option. Lists the canonical flag names so the correct invocation is
one paste away.
"""
ctx = exc.ctx
if ctx is None:
return None
msg = exc.format_message() or ""
if not any(trigger in msg for trigger in _USAGE_HINT_TRIGGERS):
return None
required = [
param for param in ctx.command.params if isinstance(param, click.Option) and param.required
]
if not required:
return None
flags = " ".join(f"{opt.opts[0]} {_placeholder(opt)}" for opt in required)
return f"hint: this command takes flags. Try: {ctx.command_path} {flags}"


def _placeholder(opt: click.Option) -> str:
"""Derive a metavar-style placeholder from the canonical flag name."""
if opt.metavar:
return opt.metavar
return opt.opts[0].lstrip("-").replace("-", "_").upper()


def _run(argv: list[str]) -> int:
"""Inner entry point — separated so tests can drive it without subprocess."""
try:
app(args=_hoist_global_flags(sys.argv[1:]))
app(args=_hoist_global_flags(argv), prog_name="rc0", standalone_mode=False)
except click.exceptions.Exit as exc:
return exc.exit_code
except click.UsageError as exc:
exc.show()
hint = _format_usage_hint(exc)
if hint:
typer.echo(hint, err=True)
return 2
except ConfirmationDeclined as exc:
typer.echo(f"error: {exc}", err=True)
raise typer.Exit(code=exc.exit_code) from exc
return exc.exit_code
except Rc0Error as exc:
typer.echo(f"error: {exc.message}", err=True)
if exc.hint:
typer.echo(f"hint: {exc.hint}", err=True)
raise typer.Exit(code=exc.exit_code) from exc
return exc.exit_code
except click.ClickException as exc:
exc.show()
return exc.exit_code
except KeyboardInterrupt:
raise typer.Exit(code=130) from None
return 130
return 0


def main() -> None:
"""CLI entry point registered in ``pyproject.toml`` as ``rc0``."""
sys.exit(_run(sys.argv[1:]))
53 changes: 52 additions & 1 deletion tests/integration/test_record_write_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import respx
from typer.testing import CliRunner

from rc0.app import app
from rc0.app import _run, app

if TYPE_CHECKING:
from pathlib import Path
Expand Down Expand Up @@ -845,3 +845,54 @@ def test_record_clear_dry_run(cli: CliRunner, isolated_config: Path) -> None:
parsed = json.loads(r.stdout)
assert parsed["dry_run"] is True
assert parsed["request"]["method"] == "DELETE"


# -------- usage hint (feedback #6) --------


def test_record_set_extra_positional_emits_hint(
capsys: pytest.CaptureFixture[str],
isolated_config: Path,
) -> None:
rc = _run(["record", "set", "example.com", "www", "A", "1.2.3.4"])
captured = capsys.readouterr()
assert rc == 2
assert "Got unexpected extra argument" in captured.err or "Missing option" in captured.err
assert "hint: this command takes flags" in captured.err
assert "rc0 record set" in captured.err
assert "--name NAME" in captured.err
assert "--type TYPE" in captured.err


def test_record_set_missing_options_emits_hint(
capsys: pytest.CaptureFixture[str],
isolated_config: Path,
) -> None:
rc = _run(["record", "set", "example.com"])
captured = capsys.readouterr()
assert rc == 2
assert "Missing option" in captured.err
assert "hint: this command takes flags" in captured.err
assert "--name NAME" in captured.err


def test_unknown_option_does_not_emit_hint(
capsys: pytest.CaptureFixture[str],
isolated_config: Path,
) -> None:
rc = _run(["record", "set", "example.com", "--bogus-flag"])
captured = capsys.readouterr()
assert rc == 2
assert "hint: this command takes flags" not in captured.err


def test_run_returns_zero_on_version(
capsys: pytest.CaptureFixture[str],
isolated_config: Path,
) -> None:
# `--version` callback raises typer.Exit(0); _run must surface that as exit 0
# — guards against the standalone_mode=False refactor swallowing the eager exit.
rc = _run(["--version"])
captured = capsys.readouterr()
assert rc == 0
assert "rc0" in captured.out
79 changes: 79 additions & 0 deletions tests/unit/test_usage_hint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Unit tests for the usage-error hint helper in rc0.app."""

from __future__ import annotations

import click
from typer.main import get_command

from rc0.app import _format_usage_hint, app


def _ctx_for(name_path: list[str]) -> click.Context:
"""Build a click.Context for the leaf command at name_path, with parents
chained so ``ctx.command_path`` renders the full chain (e.g. ``rc0 record set``)."""
root = get_command(app)
parent = click.Context(root, info_name="rc0")
current: click.Command = root
for name in name_path:
assert isinstance(current, click.Group)
sub = current.commands[name]
parent = click.Context(sub, info_name=name, parent=parent)
current = sub
return parent


def test_hint_for_missing_option_on_record_set() -> None:
ctx = _ctx_for(["record", "set"])
exc = click.UsageError("Missing option '--name'.", ctx=ctx)
hint = _format_usage_hint(exc)
assert hint is not None
assert "rc0 record set" in hint
assert "--name NAME" in hint
assert "--type TYPE" in hint


def test_hint_for_extra_positional_on_record_set() -> None:
ctx = _ctx_for(["record", "set"])
exc = click.UsageError("Got unexpected extra argument (www)", ctx=ctx)
hint = _format_usage_hint(exc)
assert hint is not None
assert "this command takes flags" in hint
assert "rc0 record set" in hint


def test_hint_uses_canonical_flag_not_python_name() -> None:
# Typer maps `--type` to Python attr `type_` and `--content` to `contents`;
# Click's default metavar would leak those Python names. The placeholder
# must derive from the flag instead.
ctx = _ctx_for(["record", "set"])
exc = click.UsageError("Missing option '--name'.", ctx=ctx)
hint = _format_usage_hint(exc)
assert hint is not None
assert "TYPE_" not in hint
assert "CONTENTS" not in hint


def test_no_hint_when_ctx_is_none() -> None:
exc = click.UsageError("Missing option '--name'.")
assert _format_usage_hint(exc) is None


def test_no_hint_for_unrelated_message() -> None:
ctx = _ctx_for(["record", "set"])
exc = click.UsageError("No such option: --bogus", ctx=ctx)
assert _format_usage_hint(exc) is None


def test_no_hint_when_no_required_options() -> None:
ctx = _ctx_for(["version"])
exc = click.UsageError("Missing argument 'X'.", ctx=ctx)
assert _format_usage_hint(exc) is None


def test_hint_works_for_record_append() -> None:
ctx = _ctx_for(["record", "append"])
exc = click.UsageError("Got unexpected extra argument (www)", ctx=ctx)
hint = _format_usage_hint(exc)
assert hint is not None
assert "rc0 record append" in hint
assert "--name" in hint
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading