Skip to content

Commit a7bf1b8

Browse files
Duang777claude
andcommitted
feat(cli): suggest the closest choice and keep usage errors short
A mistyped command or choice printed every top-level command twice and, for large subcommands, a 4-5 KB usage block. Name the closest match, replace large choice lists with a pointer to --help, and shorten usage lines over 1000 characters in error output. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: duang777 <duangjl007@gmail.com>
1 parent dc0505e commit a7bf1b8

2 files changed

Lines changed: 57 additions & 1 deletion

File tree

‎loopx/cli_runtime.py‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,13 +100,42 @@
100100
_CORE_UPDATE_COMMANDS = frozenset({"update", "upgrade"})
101101

102102

103+
# Above this many choices an invalid-choice error names the closest match
104+
# instead of repeating every choice; the full set stays in --help.
105+
_INLINE_CHOICE_LIMIT = 12
106+
# A usage line longer than this (24 of 470 parsers; `todo` and `quota` exceed
107+
# 4 KB) is replaced in error output by a pointer to the command's --help.
108+
_ERROR_USAGE_LIMIT = 1000
109+
110+
103111
class LoopXArgumentParser(argparse.ArgumentParser):
104112
"""Require complete option names across the automation-facing CLI."""
105113

106114
def __init__(self, *args, **kwargs) -> None:
107115
kwargs.setdefault("allow_abbrev", False)
108116
super().__init__(*args, **kwargs)
109117

118+
def error(self, message: str) -> None:
119+
usage = self.format_usage()
120+
if len(usage) > _ERROR_USAGE_LIMIT:
121+
usage = f"usage: {self.prog} [options] (see '{self.prog} --help')\n"
122+
self.exit(2, f"{usage}{self.prog}: error: {message}\n")
123+
124+
def _check_value(self, action: argparse.Action, value: Any) -> None:
125+
choices = action.choices
126+
if choices is None or value in choices:
127+
return
128+
import difflib
129+
130+
names = [str(choice) for choice in choices]
131+
close = difflib.get_close_matches(str(value), names, n=3)
132+
if len(names) > _INLINE_CHOICE_LIMIT:
133+
detail = f"{len(names)} choices; see '{self.prog} --help'"
134+
else:
135+
detail = f"choose from {', '.join(map(repr, names))}"
136+
suggestion = f"; did you mean {' or '.join(map(repr, close))}?" if close else ""
137+
raise argparse.ArgumentError(action, f"invalid choice: {value!r} ({detail}){suggestion}")
138+
110139

111140
class _SelectedParseRejected(Exception):
112141
"""A usage error from a command-specific parser."""
@@ -196,7 +225,9 @@ def build_cli_parser(
196225
"--cli-bin", dest="control_cli_bin", type=validate_cli_bin,
197226
help="Preserve this executable name/path in generated control commands; does not execute it or change permissions.",
198227
)
199-
return parser, parser.add_subparsers(dest="command", required=True)
228+
# The command list belongs to `loopx --help`; spelling every command into
229+
# each usage line made one mistyped word print several kilobytes.
230+
return parser, parser.add_subparsers(dest="command", required=True, metavar="<command>")
200231

201232

202233
def user_supplied_registry(argv: list[str] | None) -> bool:

‎tests/test_cli_entrypoint.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,31 @@ def test_retired_demo_commands_reject_execution_without_writing_state(
7575
assert {p.relative_to(tmp_path): p.read_bytes() for p in tmp_path.rglob("*") if p.is_file()} == before
7676

7777

78+
@pytest.mark.parametrize("module", ["loopx.entrypoint", "loopx.cli"])
79+
@pytest.mark.parametrize(
80+
("argv", "suggestion"),
81+
[
82+
(["stauts"], "did you mean 'status'?"),
83+
(["todo", "lst", "--goal-id", "example-goal"], "did you mean 'list'?"),
84+
(["quota", "--goal-id", "example-goal", "--include-detail", "vison"], "did you mean 'vision'?"),
85+
],
86+
)
87+
def test_mistyped_choice_names_the_closest_match_without_listing_every_command(
88+
tmp_path: Path, module: str, argv: list[str], suggestion: str,
89+
) -> None:
90+
registry, runtime = write_command_fixture(tmp_path)
91+
result = run_cli_main(module, [
92+
"--registry", str(registry), "--runtime-root", str(runtime), *argv,
93+
], environment={"LOOPX_USAGE_PING": "0"})
94+
assert result.returncode == 2, result.stderr
95+
assert not result.stdout
96+
assert "invalid choice" in result.stderr and suggestion in result.stderr
97+
# Neither the top-level command list nor a multi-kilobyte option list
98+
# is repeated for one mistyped word.
99+
assert "bootstrap-command-pack" not in result.stderr
100+
assert len(result.stderr) < 1000, result.stderr
101+
102+
78103
def test_command_reference_omits_retired_demo_launchers() -> None:
79104
result = run_cli_main("loopx.entrypoint", ["commands", "--format", "json"])
80105
assert result.returncode == 0, result.stderr

0 commit comments

Comments
 (0)