Skip to content
Myr

✨ 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

6 files+189 added−1 removed

modified:docs/tutorial/commands/help.md+24 added
174 unmodified lines
175```176177</div>178179## Suggest Commands180181As 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`:182183{* docs_src/commands/index/tutorial005.py hl[3] *}184185If a user mistypes a command, they'll see a helpful suggestion:186187<div class="termy">188189```console190$ python main.py crate191192<font color="#C4A000">Usage: </font>main.py [OPTIONS] COMMAND [ARGS]...193<font color="#AAAAAA">Try </font><font color="#22436D">&apos;main.py </font><font color="#4C6A8A"><b>--help</b></font><font color="#22436D">&apos;</font><font color="#AAAAAA"> for help.</font>194<font color="#CC0000">╭─ Error ───────────────────────────────────────────────────────────╮</font>195<font color="#CC0000">│</font> No such command &apos;crate&apos;. Did you mean &apos;create&apos;? <font color="#CC0000">│</font>196<font color="#CC0000">╰───────────────────────────────────────────────────────────────────╯</font>197```198199</div>200201If 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.202203## Rich Markdown and Markup204205If 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 lines
added:docs_src/commands/index/tutorial005.py+17 added
1import typer23app = typer.Typer(suggest_commands=True)456@app.command()7def create():8 typer.echo("Creating...")91011@app.command()12def delete():13 typer.echo("Deleting...")141516if __name__ == "__main__":17 app()
added:tests/test_tutorial/test_commands/test_index/test_tutorial005.py+24 added
1from typer.testing import CliRunner23from docs_src.commands.index import tutorial005 as mod45app = mod.app6runner = CliRunner()789def 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.output1415 result = runner.invoke(app, ["delete"])16 assert result.exit_code == 017 assert "Deleting..." in result.output181920def 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.output
added:tests/test_suggest_commands.py+98 added
1import typer2from typer.testing import CliRunner34runner = CliRunner()567def test_typo_suggestion_enabled():8 """Test that typo suggestions work when enabled"""9 app = typer.Typer()1011 @app.command()12 def create(): # pragma: no cover13 typer.echo("Creating...")1415 @app.command()16 def delete(): # pragma: no cover17 typer.echo("Deleting...")1819 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.output232425def test_typo_suggestion_multiple_matches():26 """Test that multiple suggestions are shown when there are multiple close matches"""27 app = typer.Typer()2829 @app.command()30 def create(): # pragma: no cover31 typer.echo("Creating...")3233 @app.command()34 def createnew(): # pragma: no cover35 typer.echo("Creating new...")3637 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.output424344def test_typo_suggestion_no_matches():45 """Test that no suggestions are shown when there are no close matches"""46 app = typer.Typer()4748 @app.command()49 def create(): # pragma: no cover50 typer.echo("Creating...")5152 @app.command()53 def delete(): # pragma: no cover54 typer.echo("Deleting...")5556 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.output606162def test_typo_suggestion_exact_match_works():63 """Test that exact matches still work normally"""64 app = typer.Typer()6566 @app.command()67 def create():68 typer.echo("Creating...")6970 @app.command()71 def delete():72 typer.echo("Deleting...")7374 result = runner.invoke(app, ["create"])75 assert result.exit_code == 076 assert "Creating..." in result.output7778 result = runner.invoke(app, ["delete"])79 assert result.exit_code == 080 assert "Deleting..." in result.output818283def test_typo_suggestion_disabled():84 """Test that typo suggestions can be explicitly disabled"""85 app = typer.Typer(suggest_commands=False)8687 @app.command()88 def create(): # pragma: no cover89 typer.echo("Creating...")9091 @app.command()92 def delete(): # pragma: no cover93 typer.echo("Deleting...")9495 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.output
modified:typer/core.py+20 added-1 removed
1 unmodified line
2import importlib.util3import inspect4import os5import sys6from difflib import get_close_matches7from enum import Enum8from gettext import gettext as _9from typing import (10 Any,
11 unmodified lines
2223import click24import click.core25import click.formatting25import click.parser26import click.shell_completion27import click.types28import click.utils29
719 unmodified lines
749 ] = 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_commands760761 def format_options(762 self, ctx: click.Context, formatter: click.HelpFormatter763 ) -> None:
9 unmodified lines
773 _typer_main_shell_completion(774 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var775 )776777 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 raise793794 def main(795 self,796 args: Optional[Sequence[str]] = None,797 prog_name: Optional[str] = None,
32 unmodified lines
modified:typer/main.py+6 added
133 unmodified lines
134 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 lines
331 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 group338339
118 unmodified lines
458def 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 lines
478 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 lines
527 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 group534535
607 unmodified lines