Skip to content

Commit 2fb9813

Browse files
committed
feat(cli): add suggestion for option --version and -V
1 parent c604f8e commit 2fb9813

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

litestar/cli/_suggestions.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import Final, NoReturn
2+
3+
try:
4+
import rich_click as click
5+
except ImportError:
6+
import click # type: ignore[no-redef]
7+
8+
_SUGGEST_OPTION_POSSIBILITIES: Final = {
9+
"-V": ["command `version`"],
10+
"--version": ["command `version`"],
11+
}
12+
13+
14+
def suggest_option(error: click.NoSuchOption) -> NoReturn:
15+
if error.possibilities:
16+
raise error
17+
18+
new_possibilities = _SUGGEST_OPTION_POSSIBILITIES.get(error.option_name)
19+
if new_possibilities is None:
20+
raise error
21+
22+
new_error = click.NoSuchOption(
23+
option_name=error.option_name,
24+
possibilities=new_possibilities,
25+
message=error.message,
26+
ctx=error.ctx,
27+
)
28+
raise new_error from error

litestar/cli/_utils.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,14 @@
1515
from pathlib import Path
1616
from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
1717

18+
from litestar.cli._suggestions import suggest_option
19+
1820
try:
21+
from rich_click import NoSuchOption
1922
from rich_click import RichCommand as Command
2023
from rich_click import RichGroup as Group
2124
except ImportError:
22-
from click import Command, Group # type: ignore[assignment]
25+
from click import Command, Group, NoSuchOption # type: ignore[assignment]
2326

2427
from typing import get_type_hints
2528

@@ -183,6 +186,12 @@ def decorator(f: AnyCallable) -> Command:
183186

184187
return decorator
185188

189+
def parse_args(self, *args: Any, **kwargs: Any) -> list[str]:
190+
try:
191+
return super().parse_args(*args, **kwargs)
192+
except NoSuchOption as e:
193+
suggest_option(e)
194+
186195

187196
class LitestarExtensionGroup(LitestarGroup):
188197
"""``LitestarGroup`` subclass that will load Litestar-CLI extensions from the `litestar.commands` entry_point.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import pytest
2+
from click.testing import CliRunner
3+
4+
from litestar.cli.main import litestar_group as cli_command
5+
6+
7+
@pytest.mark.parametrize("option", ["--version", "-V"])
8+
def test_suggest_version(option: str, runner: CliRunner) -> None:
9+
result = runner.invoke(cli_command, option)
10+
11+
assert "Did you mean command `version`?" in result.output

0 commit comments

Comments
 (0)