Skip to content

Commit 07e7725

Browse files
Duang777claude
andcommitted
fix(cli): print a runnable help hint for module launches
Before Python 3.14, argparse names 'python -m loopx.cli' after the file, so usage lines and the new '--help' hint said 'cli.py todo --help', which cannot run. Name a LoopX module launch by the command that re-runs it ('<interpreter> -m <module>'), leave console scripts unchanged, and print the hint unquoted so a quoted interpreter path survives. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: duang777 <duangjl007@gmail.com>
1 parent af4c858 commit 07e7725

2 files changed

Lines changed: 49 additions & 3 deletions

File tree

‎loopx/cli_runtime.py‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def __init__(self, *args, **kwargs) -> None:
119119
def error(self, message: str) -> None:
120120
usage = self.format_usage()
121121
if len(usage) > _ERROR_USAGE_LIMIT:
122-
usage = f"usage: {self.prog} [options] (see '{self.prog} --help')\n"
122+
usage = f"usage: {self.prog} [options] (see: {self.prog} --help)\n"
123123
self.exit(2, f"{usage}{self.prog}: error: {message}\n")
124124

125125
def _check_value(self, action: argparse.Action, value: Any) -> None:
@@ -131,7 +131,7 @@ def _check_value(self, action: argparse.Action, value: Any) -> None:
131131
names = [str(choice) for choice in choices]
132132
close = difflib.get_close_matches(str(value), names, n=3)
133133
if len(names) > _INLINE_CHOICE_LIMIT:
134-
detail = f"{len(names)} choices; see '{self.prog} --help'"
134+
detail = f"{len(names)} choices; see: {self.prog} --help"
135135
else:
136136
detail = f"choose from {', '.join(map(repr, names))}"
137137
suggestion = f"; did you mean {' or '.join(map(repr, close))}?" if close else ""
@@ -207,12 +207,31 @@ def resolve_global_output_format(args: argparse.Namespace) -> str:
207207
return "markdown"
208208

209209

210+
def _module_invocation_prog() -> str | None:
211+
"""Name a module launch by the command that re-runs it.
212+
213+
Before Python 3.14 argparse names `python -m loopx.cli` after the file
214+
(`cli.py`), so a usage or `--help` hint copied from an error cannot run.
215+
Console scripts and other launches keep argparse's own name.
216+
"""
217+
main = sys.modules.get("__main__")
218+
spec = getattr(main, "__spec__", None)
219+
module = getattr(spec, "name", None)
220+
if not isinstance(module, str) or not module.startswith("loopx") or not sys.executable:
221+
return None
222+
import shlex
223+
224+
module = module.removesuffix(".__main__")
225+
return f"{shlex.quote(sys.executable)} -m {module}"
226+
227+
210228
def build_cli_parser(
211229
*, parser_class: type[LoopXArgumentParser] = LoopXArgumentParser
212230
) -> tuple[LoopXArgumentParser, argparse._SubParsersAction]:
213231
"""Build the one canonical global grammar and return its command registrar."""
214232

215-
parser = parser_class(description="LoopX control-plane helper.")
233+
prog = _module_invocation_prog()
234+
parser = parser_class(description="LoopX control-plane helper.", **({"prog": prog} if prog else {}))
216235
parser.add_argument("--version", action="version", version=f"loopx {__version__}")
217236
parser.add_argument(
218237
"--registry",

‎tests/test_cli_entrypoint.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import hashlib
44
import json
55
import os
6+
import re
7+
import shlex
68
import shutil
79
import subprocess
810
import sys
@@ -100,6 +102,31 @@ def test_mistyped_choice_names_the_closest_match_without_listing_every_command(
100102
assert len(result.stderr) < 1000, result.stderr
101103

102104

105+
@pytest.mark.parametrize("module", ["loopx.entrypoint", "loopx.cli"])
106+
@pytest.mark.parametrize(
107+
"argv",
108+
[
109+
["stauts"],
110+
["todo", "lst", "--goal-id", "example-goal"],
111+
["quota", "--goal-id", "example-goal", "--runtime-profile", "codex"],
112+
],
113+
)
114+
def test_module_launch_help_hint_runs(tmp_path: Path, module: str, argv: list[str]) -> None:
115+
# Before Python 3.14 argparse names a module launch after its file
116+
# (`cli.py`). The hint printed in the error must be a command that runs.
117+
environment = {**os.environ, "LOOPX_USAGE_PING": "0", "PYTHONPATH": str(REPO_ROOT)}
118+
rejected = subprocess.run([sys.executable, "-m", module, *argv], cwd=tmp_path,
119+
env=environment, capture_output=True, text=True, timeout=120)
120+
assert rejected.returncode == 2, rejected.stderr
121+
hint = re.search(r"see: (.+?) --help\)", rejected.stderr)
122+
assert hint is not None, rejected.stderr
123+
assert not re.search(r"\b(cli|entrypoint)\.py\b", rejected.stderr), rejected.stderr
124+
shown = subprocess.run([*shlex.split(hint.group(1)), "--help"], cwd=tmp_path,
125+
env=environment, capture_output=True, text=True, timeout=120)
126+
assert shown.returncode == 0, (hint.group(1), shown.stderr)
127+
assert shown.stdout.strip()
128+
129+
103130
def test_command_reference_omits_retired_demo_launchers() -> None:
104131
result = run_cli_main("loopx.entrypoint", ["commands", "--format", "json"])
105132
assert result.returncode == 0, result.stderr

0 commit comments

Comments
 (0)