✨ Enable command suggestions on typo by default (#1371)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Savannah Ostrowski · committed by GitHub · parent ffbaed5 · Browse files · 6 files·+189 added−1 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: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
- Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Diff stats
6 files+189 added−1 removed
- tests:+122 added−0 removed
- other:+67 added−1 removed
Provenance
- Commit
f6718b8- Tree
593fc51- Author
Savannah Ostrowski <savannah@python.org>- Committer
GitHub <noreply@github.com>- Parent
ffbaed5
6 files changed+189 added−1 removed
modified:docs/tutorial/commands/help.md+24 added
174 unmodified lines175 ```176 177 </div>178 179+## Suggest Commands180+181+As of version 0.20.0, Typer added support for suggesting mistyped command names. This feature is **enabled by default**, but you can disable it with the parameter `suggest_commands=False`:182+183+{* docs_src/commands/index/tutorial005.py hl[3] *}184+185+If a user mistypes a command, they'll see a helpful suggestion:186+187+<div class="termy">188+189+```console190+$ python main.py crate191+192+<font color="#C4A000">Usage: </font>main.py [OPTIONS] COMMAND [ARGS]...193+<font color="#AAAAAA">Try </font><font color="#22436D">'main.py </font><font color="#4C6A8A"><b>--help</b></font><font color="#22436D">'</font><font color="#AAAAAA"> for help.</font>194+<font color="#CC0000">╭─ Error ───────────────────────────────────────────────────────────╮</font>195+<font color="#CC0000">│</font> No such command 'crate'. Did you mean 'create'? <font color="#CC0000">│</font>196+<font color="#CC0000">╰───────────────────────────────────────────────────────────────────╯</font>197+```198+199+</div>200+201+If there are multiple close matches, Typer will suggest them all. This feature uses Python's built-in `difflib.get_close_matches()` to find similar command names, making your CLI more user-friendly by helping users recover from typos.202+203 ## Rich Markdown and Markup204 205 If you have **Rich** installed as described in [Printing and Colors](../printing.md){.internal-link target=_blank}, you can configure your app to enable markup text with the parameter `rich_markup_mode`.206 299 unmodified linesadded:docs_src/commands/index/tutorial005.py+17 added
1+import typer2+3+app = typer.Typer(suggest_commands=True)4+5+6+@app.command()7+def create():8+ typer.echo("Creating...")9+10+11+@app.command()12+def delete():13+ typer.echo("Deleting...")14+15+16+if __name__ == "__main__":17+ app()added:tests/test_tutorial/test_commands/test_index/test_tutorial005.py+24 added
1+from typer.testing import CliRunner2+3+from docs_src.commands.index import tutorial005 as mod4+5+app = mod.app6+runner = CliRunner()7+8+9+def test_creates_successfully():10+ """Verify the example runs without errors"""11+ result = runner.invoke(app, ["create"])12+ assert result.exit_code == 013+ assert "Creating..." in result.output14+15+ result = runner.invoke(app, ["delete"])16+ assert result.exit_code == 017+ assert "Deleting..." in result.output18+19+20+def test_shows_suggestion():21+ """Verify command suggestions appear for typos"""22+ result = runner.invoke(app, ["crate"])23+ assert result.exit_code != 024+ assert "Did you mean 'create'?" in result.outputadded:tests/test_suggest_commands.py+98 added
1+import typer2+from typer.testing import CliRunner3+4+runner = CliRunner()5+6+7+def test_typo_suggestion_enabled():8+ """Test that typo suggestions work when enabled"""9+ app = typer.Typer()10+11+ @app.command()12+ def create(): # pragma: no cover13+ typer.echo("Creating...")14+15+ @app.command()16+ def delete(): # pragma: no cover17+ typer.echo("Deleting...")18+19+ result = runner.invoke(app, ["crate"])20+ assert result.exit_code != 021+ assert "No such command" in result.output22+ assert "Did you mean 'create'?" in result.output23+24+25+def test_typo_suggestion_multiple_matches():26+ """Test that multiple suggestions are shown when there are multiple close matches"""27+ app = typer.Typer()28+29+ @app.command()30+ def create(): # pragma: no cover31+ typer.echo("Creating...")32+33+ @app.command()34+ def createnew(): # pragma: no cover35+ typer.echo("Creating new...")36+37+ result = runner.invoke(app, ["crate"])38+ assert result.exit_code != 039+ assert "No such command" in result.output40+ assert "Did you mean" in result.output41+ assert "create" in result.output and "createnew" in result.output42+43+44+def test_typo_suggestion_no_matches():45+ """Test that no suggestions are shown when there are no close matches"""46+ app = typer.Typer()47+48+ @app.command()49+ def create(): # pragma: no cover50+ typer.echo("Creating...")51+52+ @app.command()53+ def delete(): # pragma: no cover54+ typer.echo("Deleting...")55+56+ result = runner.invoke(app, ["xyz"])57+ assert result.exit_code != 058+ assert "No such command" in result.output59+ assert "Did you mean" not in result.output60+61+62+def test_typo_suggestion_exact_match_works():63+ """Test that exact matches still work normally"""64+ app = typer.Typer()65+66+ @app.command()67+ def create():68+ typer.echo("Creating...")69+70+ @app.command()71+ def delete():72+ typer.echo("Deleting...")73+74+ result = runner.invoke(app, ["create"])75+ assert result.exit_code == 076+ assert "Creating..." in result.output77+78+ result = runner.invoke(app, ["delete"])79+ assert result.exit_code == 080+ assert "Deleting..." in result.output81+82+83+def test_typo_suggestion_disabled():84+ """Test that typo suggestions can be explicitly disabled"""85+ app = typer.Typer(suggest_commands=False)86+87+ @app.command()88+ def create(): # pragma: no cover89+ typer.echo("Creating...")90+91+ @app.command()92+ def delete(): # pragma: no cover93+ typer.echo("Deleting...")94+95+ result = runner.invoke(app, ["crate"])96+ assert result.exit_code != 097+ assert "No such command" in result.output98+ assert "Did you mean" not in result.outputmodified:typer/core.py+20 added-1 removed
1 unmodified line2 import importlib.util3 import inspect4 import os5 import sys6+from difflib import get_close_matches7 from enum import Enum8 from gettext import gettext as _9 from typing import (10 Any,11 unmodified lines22 23 import click24 import click.core25 import click.formatting25-import click.parser26 import click.shell_completion27 import click.types28 import click.utils29 719 unmodified lines749 ] = None,750 # Rich settings751 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,752 rich_help_panel: Union[str, None] = None,753+ suggest_commands: bool = True,754 **attrs: Any,755 ) -> None:756 super().__init__(name=name, commands=commands, **attrs)757 self.rich_markup_mode: MarkupMode = rich_markup_mode758 self.rich_help_panel = rich_help_panel759+ self.suggest_commands = suggest_commands760 761 def format_options(762 self, ctx: click.Context, formatter: click.HelpFormatter763 ) -> None:9 unmodified lines773 _typer_main_shell_completion(774 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var775 )776 777+ def resolve_command(778+ self, ctx: click.Context, args: List[str]779+ ) -> Tuple[Optional[str], Optional[click.Command], List[str]]:780+ try:781+ return super().resolve_command(ctx, args)782+ except click.UsageError as e:783+ if self.suggest_commands:784+ available_commands = list(self.commands.keys())785+ if available_commands and args:786+ typo = args[0]787+ matches = get_close_matches(typo, available_commands)788+ if matches:789+ suggestions = ", ".join(f"{m!r}" for m in matches)790+ message = e.message.rstrip(".")791+ e.message = f"{message}. Did you mean {suggestions}?"792+ raise793+794 def main(795 self,796 args: Optional[Sequence[str]] = None,797 prog_name: Optional[str] = None,32 unmodified linesmodified:typer/main.py+6 added
133 unmodified lines134 add_completion: bool = True,135 # Rich settings136 rich_markup_mode: MarkupMode = Default(DEFAULT_MARKUP_MODE),137 rich_help_panel: Union[str, None] = Default(None),138+ suggest_commands: bool = True,139 pretty_exceptions_enable: bool = True,140 pretty_exceptions_show_locals: bool = True,141 pretty_exceptions_short: bool = True,142 ):143 self._add_completion = add_completion144 self.rich_markup_mode: MarkupMode = rich_markup_mode145 self.rich_help_panel = rich_help_panel146+ self.suggest_commands = suggest_commands147 self.pretty_exceptions_enable = pretty_exceptions_enable148 self.pretty_exceptions_show_locals = pretty_exceptions_show_locals149 self.pretty_exceptions_short = pretty_exceptions_short150 self.info = TyperInfo(180 unmodified lines331 group = get_group_from_info(332 TyperInfo(typer_instance),333 pretty_exceptions_short=typer_instance.pretty_exceptions_short,334 rich_markup_mode=typer_instance.rich_markup_mode,335+ suggest_commands=typer_instance.suggest_commands,336 )337 return group338 339 118 unmodified lines458 def get_group_from_info(459 group_info: TyperInfo,460 *,461 pretty_exceptions_short: bool,462+ suggest_commands: bool,463 rich_markup_mode: MarkupMode,464 ) -> TyperGroup:465 assert group_info.typer_instance, (466 "A Typer instance is needed to generate a Click Group"11 unmodified lines478 sub_group = get_group_from_info(479 sub_group_info,480 pretty_exceptions_short=pretty_exceptions_short,481 rich_markup_mode=rich_markup_mode,482+ suggest_commands=suggest_commands,483 )484 if sub_group.name:485 commands[sub_group.name] = sub_group486 else:40 unmodified lines527 deprecated=solved_info.deprecated,528 rich_markup_mode=rich_markup_mode,529 # Rich settings530 rich_help_panel=solved_info.rich_help_panel,531+ suggest_commands=suggest_commands,532 )533 return group534 535 607 unmodified lines