Skip to content
Myr

Add NoSuchCommand exception with suggestions for misspelled commands (#3228)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by RC2215 · committed by GitHub · parent 19fd4d6 · Browse files · 7 files+86 added−22 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Andreas Backx <andreas@backx.org>

Diff stats

7 files+86 added−22 removed

  • tests:+36 added−4 removed
  • other:+50 added−18 removed

7 files+86 added−22 removed

modified:src/click/__init__.py+1 added
31 unmodified lines
32from .exceptions import BadParameter as BadParameter33from .exceptions import ClickException as ClickException34from .exceptions import FileError as FileError35from .exceptions import MissingParameter as MissingParameter36from .exceptions import NoSuchCommand as NoSuchCommand37from .exceptions import NoSuchOption as NoSuchOption38from .exceptions import UsageError as UsageError39from .formatting import HelpFormatter as HelpFormatter40from .formatting import wrap_text as wrap_text
86 unmodified lines
modified:src/click/core.py+2 added-2 removed
27 unmodified lines
28from .exceptions import ClickException29from .exceptions import Exit30from .exceptions import MissingParameter31from .exceptions import NoArgsIsHelpError32from .exceptions import NoSuchCommand33from .exceptions import UsageError34from .formatting import HelpFormatter35from .formatting import join_options36from .globals import pop_context
1900 unmodified lines
1937 def resolve_command(1938 self, ctx: Context, args: list[str]1939 ) -> tuple[str | None, Command | None, list[str]]:1940 cmd_name = make_str(args[0])1940 original_cmd_name = cmd_name19411942 # Get the command1943 cmd = self.get_command(ctx, cmd_name)1944
11 unmodified lines
1956 # place.1957 if cmd is None and not ctx.resilient_parsing:1958 if _split_opt(cmd_name)[0]:1959 self.parse_args(ctx, args)1960 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1960 raise NoSuchCommand(cmd_name, possibilities=self.commands, ctx=ctx)1961 return cmd_name if cmd else None, cmd, args[1:]19621963 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:1964 """Return a list of completions for the incomplete value. Looks
1531 unmodified lines
modified:src/click/exceptions.py+44 added-12 removed
21 unmodified lines
2223 return param_hint242526def _format_possibilities(possibilities: list[str]) -> str:27 possibility_str = ", ".join(repr(p) for p in sorted(possibilities))28 return ngettext(29 "Did you mean {possibility}?",30 "(Did you mean one of: {possibilities}?)",31 len(possibilities),32 ).format(possibility=possibility_str, possibilities=possibility_str)333435class ClickException(Exception):36 """An exception that Click can handle and show to the user."""3738 #: The exit code for this exception.
179 unmodified lines
218 return self.message219220221class NoSuchOption(UsageError):213 """Raised if click attempted to handle an option that does not214 exist.222 """Raised if Click attempted to handle an option that does not exist.223224 .. versionadded:: 4.0225 """226227 def __init__(228 self,229 option_name: str,230 message: str | None = None,223 possibilities: cabc.Sequence[str] | None = None,231 possibilities: cabc.Iterable[str] | None = None,232 ctx: Context | None = None,233 ) -> None:234 if message is None:227 message = _("No such option: {name}").format(name=option_name)235 message = _("No such option {name!r}.").format(name=option_name)236237 super().__init__(message, ctx)238 self.option_name = option_name231 self.possibilities = possibilities239 self.possibilities: list[str] | None = None240 if possibilities:241 from difflib import get_close_matches242243 self.possibilities = get_close_matches(option_name, possibilities)244245 def format_message(self) -> str:246 if not self.possibilities:247 return self.message248 return f"{self.message} {_format_possibilities(self.possibilities)}"249237 possibility_str = ", ".join(sorted(self.possibilities))238 suggest = ngettext(239 "Did you mean {possibility}?",240 "(Possible options: {possibilities})",241 len(self.possibilities),242 ).format(possibility=possibility_str, possibilities=possibility_str)243 return f"{self.message} {suggest}"250251class NoSuchCommand(UsageError):252 """Raised if Click attempted to handle a command that does not exist."""253254 def __init__(255 self,256 command_name: str,257 message: str | None = None,258 possibilities: cabc.Iterable[str] | None = None,259 ctx: Context | None = None,260 ) -> None:261 if message is None:262 message = _("No such command {name!r}.").format(name=command_name)263264 super().__init__(message, ctx)265 self.command_name = command_name266 self.possibilities: list[str] | None = None267 if possibilities:268 from difflib import get_close_matches269270 self.possibilities = get_close_matches(command_name, possibilities)271272 def format_message(self) -> str:273 if not self.possibilities:274 return self.message275 return f"{self.message} {_format_possibilities(self.possibilities)}"276277278class BadOptionUsage(UsageError):279 """Raised if an option is generally supplied but the use of the option280 was incorrect. This is for instance raised if the number of arguments281 for an option is not correct.
63 unmodified lines
modified:src/click/parser.py+1 added-4 removed
358 unmodified lines
359 def _match_long_opt(360 self, opt: str, explicit_value: str | None, state: _ParsingState361 ) -> None:362 if opt not in self._long_opt:363 from difflib import get_close_matches363 raise NoSuchOption(opt, possibilities=self._long_opt, ctx=self.ctx)364365 possibilities = get_close_matches(opt, self._long_opt)366 raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)367365 option = self._long_opt[opt]366 if option.takes_value:367 # At this point it's safe to modify rargs by injecting the368 # explicit value, because no exception is raised in this
161 unmodified lines
modified:tests/test_commands.py+32 added
571 unmodified lines
572 rv = runner.invoke(cli, standalone_mode=False)573 assert rv.exit_code == 1574 assert isinstance(rv.exception.__cause__, exc)575 assert rv.exception.__cause__.args == ("catch me!",)576577578def test_unknown_command(runner):579 result = runner.invoke(click.Group(), "unknown")580 assert result.exception581 assert "No such command 'unknown'." in result.output582583584@pytest.mark.parametrize(585 ("value", "expect"),586 [587 ("pause", "Did you mean 'push'?"),588 ("decline", "(Did you mean one of: 'declare', 'refine'?)"),589 ],590)591def test_suggest_possible_commands(runner, value, expect):592 cli = click.Group()593594 @cli.command()595 def push():596 pass597598 @cli.command()599 def declare():600 pass601602 @cli.command()603 def refine():604 pass605606 result = runner.invoke(cli, [value])607 assert expect in result.output
modified:tests/test_options.py+4 added-4 removed
139 unmodified lines
140 pass141142 result = runner.invoke(cli, [unknown_flag])143 assert result.exception144 assert f"No such option: {unknown_flag}" in result.output144 assert f"No such option '{unknown_flag}'." in result.output145146147@pytest.mark.parametrize(148 ("value", "expect"),149 [150 ("--cat", "Did you mean --count?"),151 ("--bounds", "(Possible options: --bound, --count)"),152 ("--bount", "(Possible options: --bound, --count)"),150 ("--cat", "Did you mean '--count'?"),151 ("--bounds", "(Did you mean one of: '--bound', '--count'?)"),152 ("--bount", "(Did you mean one of: '--bound', '--count'?)"),153 ],154)155def test_suggest_possible_options(runner, value, expect):156 cli = click.Command(
2468 unmodified lines
modified:CHANGES.rst+2 added
45 unmodified lines
46 replacing the ``start`` built-in which cannot be invoked without47 ``shell=True``. :issue:`3164` :pr:`3186`48- Fix Fish shell completion errors when option help text contains newlines.49 :issue:`3043`50- Add :class:`NoSuchCommand` exception with suggestions for misspelled51 commands. :issue:`3107` :pr:`3228`5253Version 8.3.354-------------55
1366 unmodified lines