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
Provenance
- Commit
831c8f0- Tree
1e65e01- Author
RC2215 <88962047+RC2215@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
19fd4d6
7 files changed+86 added−22 removed
modified:src/click/__init__.py+1 added
31 unmodified lines32 from .exceptions import BadParameter as BadParameter33 from .exceptions import ClickException as ClickException34 from .exceptions import FileError as FileError35 from .exceptions import MissingParameter as MissingParameter36+from .exceptions import NoSuchCommand as NoSuchCommand37 from .exceptions import NoSuchOption as NoSuchOption38 from .exceptions import UsageError as UsageError39 from .formatting import HelpFormatter as HelpFormatter40 from .formatting import wrap_text as wrap_text86 unmodified linesmodified:src/click/core.py+2 added-2 removed
27 unmodified lines28 from .exceptions import ClickException29 from .exceptions import Exit30 from .exceptions import MissingParameter31 from .exceptions import NoArgsIsHelpError32+from .exceptions import NoSuchCommand33 from .exceptions import UsageError34 from .formatting import HelpFormatter35 from .formatting import join_options36 from .globals import pop_context1900 unmodified lines1937 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_name1941 1942 # Get the command1943 cmd = self.get_command(ctx, cmd_name)1944 11 unmodified lines1956 # 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:]1962 1963 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:1964 """Return a list of completions for the incomplete value. Looks1531 unmodified linesmodified:src/click/exceptions.py+44 added-12 removed
21 unmodified lines22 23 return param_hint24 25 26+def _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)33+34+35 class ClickException(Exception):36 """An exception that Click can handle and show to the user."""37 38 #: The exit code for this exception.179 unmodified lines218 return self.message219 220 221 class 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.223 224 .. versionadded:: 4.0225 """226 227 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)236 237 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_matches242 243+ self.possibilities = get_close_matches(option_name, possibilities)244+245 def format_message(self) -> str:246 if not self.possibilities:247 return self.message248+ return f"{self.message} {_format_possibilities(self.possibilities)}"249 237- 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}"250 251+class NoSuchCommand(UsageError):252+ """Raised if Click attempted to handle a command that does not exist."""253 254+ 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)263+264+ super().__init__(message, ctx)265+ self.command_name = command_name266+ self.possibilities: list[str] | None = None267+ if possibilities:268+ from difflib import get_close_matches269+270+ self.possibilities = get_close_matches(command_name, possibilities)271+272+ def format_message(self) -> str:273+ if not self.possibilities:274+ return self.message275+ return f"{self.message} {_format_possibilities(self.possibilities)}"276+277+278 class 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 linesmodified:src/click/parser.py+1 added-4 removed
358 unmodified lines359 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)364 365- possibilities = get_close_matches(opt, self._long_opt)366- raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)367-365 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 this161 unmodified linesmodified:tests/test_commands.py+32 added
571 unmodified lines572 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!",)576+577+578+def test_unknown_command(runner):579+ result = runner.invoke(click.Group(), "unknown")580+ assert result.exception581+ assert "No such command 'unknown'." in result.output582+583+584+@pytest.mark.parametrize(585+ ("value", "expect"),586+ [587+ ("pause", "Did you mean 'push'?"),588+ ("decline", "(Did you mean one of: 'declare', 'refine'?)"),589+ ],590+)591+def test_suggest_possible_commands(runner, value, expect):592+ cli = click.Group()593+594+ @cli.command()595+ def push():596+ pass597+598+ @cli.command()599+ def declare():600+ pass601+602+ @cli.command()603+ def refine():604+ pass605+606+ result = runner.invoke(cli, [value])607+ assert expect in result.outputmodified:tests/test_options.py+4 added-4 removed
139 unmodified lines140 pass141 142 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.output145 146 147 @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 )155 def test_suggest_possible_options(runner, value, expect):156 cli = click.Command(2468 unmodified linesmodified:CHANGES.rst+2 added
45 unmodified lines46 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`52 53 Version 8.3.354 -------------55 1366 unmodified lines