:sparkles: Re-implement completion, fixes, add PowerShell support (#66)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* :sparkles: Re-implement completion * :white_check_mark: Add tests for re-implemented completion * :art: Move mypy config to file * :see_no_evil: Update .gitignore * :heavy_plus_sign: Remove click-completion, add support for autodetection with shellingham * :white_check_mark: Fix test for PowerShell * :bug: Fix PowerShell permissions/test * :art: Format test * :checkered_flag: Fix PowerShell script for Windows and PowerShell 5 * :memo: Update docs, internal implementation of completion
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+1198 added−86 removed
- tests:+791 added−51 removed
- other:+407 added−35 removed
Provenance
- Commit
1d3337a- Tree
b7e90d0- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
d651b7d
19 files changed+1198 added−86 removed
modified:docs/alternatives.md+11 added
61 unmodified lines626364656667686970717273747576777879803 unmodified lines61 unmodified lines **Typer** mainly adds a layer on top of Click, making the code simpler and easier to use, with autocompletion everywhere, etc, but providing all the powerful features of Click underneath.
As someone pointed out: <em><a href="https://twitter.com/fishnets88/status/1210126833745838080" class="external-link" target="_blank">"Nice to see it is built on Click but adds the type stuff. Me gusta!"</a></em>
### <a href="https://github.com/click-contrib/click-completion" class="external-link" target="_blank">`click-completion`</a>
`click-completion` is a plug-in for Click. It was created to extend completion support for shells when Click only had support for Bash completion.
Previous versions of **Typer** had deep integrations with `click-completion` and used it as an optional dependency. But now all the completion logic is implemented internally in **Typer** itself, the internal logic was heavily inspired and using some parts of `click-completion`.
And now **Typer** improved it to have new features, tests, some bug fixes (for issues in plain `click-completion` and Click), and better support for shells, including modern versions of PowerShell (e.g. the default versions that come with Windows 10).
!!! check "Inspired **Typer** to" Provide auto completion for all the shells.
### <a href="https://fastapi.tiangolo.com/" class="external-link" target="_blank">FastAPI</a>
I created **FastAPI** to provide an easy way to build APIs with autocompletion for everything in the code (and some other <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">features</a>).
3 unmodified linesmodified:docs/features.md+16 added-6 removed
40 unmodified lines4142434445454647484950505152525354555655575857596061626359646566676869707172737413 unmodified lines40 unmodified lines## User friendly CLI apps
The resulting CLI apps created with **Typer** have the nice features of many "pro" command line programs you probably already love.
* Automatic help options for the main CLI program and all the its subcommands.* Automatic help options for the main CLI program and all its subcommands.* Automatic command and subcommand structure handling (you will see more about subcommands in the Tutorial - User Guide).* Automatic completion for the CLI app in all operating systems, in all the shells (Bash, Zsh, Fish, PowerShell), so that the final user of your app can just hit <kbd>TAB</kbd> and get the available options or subcommands. *
!!! note "* Auto completion" For the autocompletion to work on all shells you also need to add the dependency `click-completion`. Auto completion works when you create a package (installable with `pip`). Or when using [Typer CLI](typer-cli.md){.internal-link target=_blank}.
If **Typer** detects `click-completion` installed, it will automatically create 2 *CLI options*: If you also add `shellingham` as a dependency, **Typer** will use it to auto-detect the current shell when installing completion.
**Typer** will automatically create 2 *CLI options*:
* `--install-completion`: Install completion for the current shell. * `--show-completion`: Show completion for the current shell, to copy it or customize the installation. * `--show-completion`: Show completion for the current shell, to copy it or customize the installation.
Then you can tell the user to run that command and the rest will just work. If you didn't add `shellingham` those *CLI Options* take a parameter with the name of the shell to install completion for, e.g.: * `--install-completion bash`. * `--show-completion powershell`.
It works when you create a package (installable with `pip`). Or when using [Typer CLI](typer-cli.md){.internal-link target=_blank}. Then you can tell the user to install completion after installing your CLI program and the rest will just work.
!!! tip **Typer**'s completion is implemented internally, it uses ideas and components from Click and ideas from `click-completion`, but it doesn't use `click-completion` internally.
Then it extends those ideas with features and bug fixes. For example, **Typer** programs also support modern versions of PowerShell (e.g. in Windows 10) among all the other shells.
## The power of Click
<a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a> is one of the most popular tools for building CLIs in Python.
13 unmodified linesmodified:docs/index.md+6 added-4 removed
29 unmodified lines30 31 The key features are:32 33 * **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.34-* **Easy to use**: It's easy to use for the final users. Automatic help, and (optional) automatic completion for all shells.34+* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.35 * **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36 * **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37 * **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.38 203 unmodified lines242 And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.243 244 **You get**: great editor support, including **completion** and **type checks** everywhere.245 246-**Your users get**: automatic **`--help`**, (optional) **auto completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.246+**Your users get**: automatic **`--help`**, **auto completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.247 248 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.249 250 ## Optional Dependencies4 unmodified lines255 256 * <a href="https://pypi.org/project/colorama/" class="external-link" target="_blank"><code>colorama</code></a>: and Click will automatically use it to make sure your terminal's colors always work correctly, even in Windows.257 * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).258 * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.259-* <a href="https://github.com/click-contrib/click-completion" class="external-link" target="_blank"><code>click-completion</code></a>: and Typer will automatically configure it to provide completion for all the shells, including installation commands.259+* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.260+ * With `shellingham` you can just use `--install-completion`.261+ * Without `shellingham`, you have to pass a *CLI Option value* with the name of the shell to install completion, e.g. `--install-completion bash`.262 261-You can install `typer` with `colorama` and `click-completion` with `pip install typer[all]`.263+You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.264 265 ## Other tools and plug-ins266 267 Click has many plug-ins available that you can use. And there are many tools that help with command line applications that you can use as well, even if they are not related to Typer or Click.12 unmodified linesmodified:scripts/lint.sh+1 added-1 removed
123456678#!/usr/bin/env bash
set -eset -x
mypy typer --disallow-untyped-defsmypy typerblack typer tests --checkisort --multi-line=3 --trailing-comma --force-grid-wrap=0 --combine-as --line-width 88 --recursive --check-only --thirdparty typer typer testsadded:tests/test_completion/__init__.py
added:tests/test_completion/test_completion_complete_no_help.py+69 added
1+import os2+import subprocess3+from commands.index import tutorial002 as mod4+5+6+def test_completion_complete_subcommand_zsh():7+ result = subprocess.run(8+ ["coverage", "run", mod.__file__, " "],9+ stdout=subprocess.PIPE,10+ stderr=subprocess.PIPE,11+ encoding="utf-8",12+ env={13+ **os.environ,14+ "_TUTORIAL002.PY_COMPLETE": "complete_zsh",15+ "_TYPER_COMPLETE_ARGS": "tutorial002.py ",16+ "_TYPER_COMPLETE_TESTING": "True",17+ },18+ )19+ assert "create" in result.stdout20+ assert "delete" in result.stdout21+22+23+def test_completion_complete_subcommand_fish():24+ result = subprocess.run(25+ ["coverage", "run", mod.__file__, " "],26+ stdout=subprocess.PIPE,27+ stderr=subprocess.PIPE,28+ encoding="utf-8",29+ env={30+ **os.environ,31+ "_TUTORIAL002.PY_COMPLETE": "complete_fish",32+ "_TYPER_COMPLETE_ARGS": "tutorial002.py ",33+ "_TYPER_COMPLETE_FISH_ACTION": "get-args",34+ "_TYPER_COMPLETE_TESTING": "True",35+ },36+ )37+ assert "create\ndelete" in result.stdout38+39+40+def test_completion_complete_subcommand_powershell():41+ result = subprocess.run(42+ ["coverage", "run", mod.__file__, " "],43+ stdout=subprocess.PIPE,44+ stderr=subprocess.PIPE,45+ encoding="utf-8",46+ env={47+ **os.environ,48+ "_TUTORIAL002.PY_COMPLETE": "complete_powershell",49+ "_TYPER_COMPLETE_ARGS": "tutorial002.py ",50+ "_TYPER_COMPLETE_TESTING": "True",51+ },52+ )53+ assert ("create::: \ndelete::: ") in result.stdout54+55+56+def test_completion_complete_subcommand_pwsh():57+ result = subprocess.run(58+ ["coverage", "run", mod.__file__, " "],59+ stdout=subprocess.PIPE,60+ stderr=subprocess.PIPE,61+ encoding="utf-8",62+ env={63+ **os.environ,64+ "_TUTORIAL002.PY_COMPLETE": "complete_pwsh",65+ "_TYPER_COMPLETE_ARGS": "tutorial002.py ",66+ "_TYPER_COMPLETE_TESTING": "True",67+ },68+ )69+ assert ("create::: \ndelete::: ") in result.stdoutadded:tests/test_completion/test_completion_complete.py+178 added
1+import os2+import subprocess3+from commands.help import tutorial001 as mod4+5+6+def test_completion_complete_subcommand_bash():7+ result = subprocess.run(8+ ["coverage", "run", mod.__file__, " "],9+ stdout=subprocess.PIPE,10+ stderr=subprocess.PIPE,11+ encoding="utf-8",12+ env={13+ **os.environ,14+ "_TUTORIAL001.PY_COMPLETE": "complete_bash",15+ "COMP_WORDS": "tutorial001.py del",16+ "COMP_CWORD": "1",17+ "_TYPER_COMPLETE_TESTING": "True",18+ },19+ )20+ assert "delete\ndelete-all" in result.stdout21+22+23+def test_completion_complete_subcommand_bash_invalid():24+ result = subprocess.run(25+ ["coverage", "run", mod.__file__, " "],26+ stdout=subprocess.PIPE,27+ stderr=subprocess.PIPE,28+ encoding="utf-8",29+ env={30+ **os.environ,31+ "_TUTORIAL001.PY_COMPLETE": "complete_bash",32+ "COMP_WORDS": "tutorial001.py del",33+ "COMP_CWORD": "42",34+ "_TYPER_COMPLETE_TESTING": "True",35+ },36+ )37+ assert "create\ndelete\ndelete-all\ninit" in result.stdout38+39+40+def test_completion_complete_subcommand_zsh():41+ result = subprocess.run(42+ ["coverage", "run", mod.__file__, " "],43+ stdout=subprocess.PIPE,44+ stderr=subprocess.PIPE,45+ encoding="utf-8",46+ env={47+ **os.environ,48+ "_TUTORIAL001.PY_COMPLETE": "complete_zsh",49+ "_TYPER_COMPLETE_ARGS": "tutorial001.py del",50+ "_TYPER_COMPLETE_TESTING": "True",51+ },52+ )53+ assert (54+ """_arguments '*: :(("delete":"Delete a user with USERNAME."\n"""55+ """\"delete-all":"Delete ALL users in the database."))'"""56+ ) in result.stdout57+58+59+def test_completion_complete_subcommand_zsh_files():60+ result = subprocess.run(61+ ["coverage", "run", mod.__file__, " "],62+ stdout=subprocess.PIPE,63+ stderr=subprocess.PIPE,64+ encoding="utf-8",65+ env={66+ **os.environ,67+ "_TUTORIAL001.PY_COMPLETE": "complete_zsh",68+ "_TYPER_COMPLETE_ARGS": "tutorial001.py delete ",69+ "_TYPER_COMPLETE_TESTING": "True",70+ },71+ )72+ assert ("_files") in result.stdout73+74+75+def test_completion_complete_subcommand_fish():76+ result = subprocess.run(77+ ["coverage", "run", mod.__file__, " "],78+ stdout=subprocess.PIPE,79+ stderr=subprocess.PIPE,80+ encoding="utf-8",81+ env={82+ **os.environ,83+ "_TUTORIAL001.PY_COMPLETE": "complete_fish",84+ "_TYPER_COMPLETE_ARGS": "tutorial001.py del",85+ "_TYPER_COMPLETE_FISH_ACTION": "get-args",86+ "_TYPER_COMPLETE_TESTING": "True",87+ },88+ )89+ assert (90+ "delete\tDelete a user with USERNAME.\ndelete-all\tDelete ALL users in the database."91+ in result.stdout92+ )93+94+95+def test_completion_complete_subcommand_fish_should_complete():96+ result = subprocess.run(97+ ["coverage", "run", mod.__file__, " "],98+ stdout=subprocess.PIPE,99+ stderr=subprocess.PIPE,100+ encoding="utf-8",101+ env={102+ **os.environ,103+ "_TUTORIAL001.PY_COMPLETE": "complete_fish",104+ "_TYPER_COMPLETE_ARGS": "tutorial001.py del",105+ "_TYPER_COMPLETE_FISH_ACTION": "is-args",106+ "_TYPER_COMPLETE_TESTING": "True",107+ },108+ )109+ assert result.returncode == 0110+111+112+def test_completion_complete_subcommand_fish_should_complete_no():113+ result = subprocess.run(114+ ["coverage", "run", mod.__file__, " "],115+ stdout=subprocess.PIPE,116+ stderr=subprocess.PIPE,117+ encoding="utf-8",118+ env={119+ **os.environ,120+ "_TUTORIAL001.PY_COMPLETE": "complete_fish",121+ "_TYPER_COMPLETE_ARGS": "tutorial001.py delete ",122+ "_TYPER_COMPLETE_FISH_ACTION": "is-args",123+ "_TYPER_COMPLETE_TESTING": "True",124+ },125+ )126+ assert result.returncode != 0127+128+129+def test_completion_complete_subcommand_powershell():130+ result = subprocess.run(131+ ["coverage", "run", mod.__file__, " "],132+ stdout=subprocess.PIPE,133+ stderr=subprocess.PIPE,134+ encoding="utf-8",135+ env={136+ **os.environ,137+ "_TUTORIAL001.PY_COMPLETE": "complete_powershell",138+ "_TYPER_COMPLETE_ARGS": "tutorial001.py del",139+ "_TYPER_COMPLETE_TESTING": "True",140+ },141+ )142+ assert (143+ "delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."144+ ) in result.stdout145+146+147+def test_completion_complete_subcommand_pwsh():148+ result = subprocess.run(149+ ["coverage", "run", mod.__file__, " "],150+ stdout=subprocess.PIPE,151+ stderr=subprocess.PIPE,152+ encoding="utf-8",153+ env={154+ **os.environ,155+ "_TUTORIAL001.PY_COMPLETE": "complete_pwsh",156+ "_TYPER_COMPLETE_ARGS": "tutorial001.py del",157+ "_TYPER_COMPLETE_TESTING": "True",158+ },159+ )160+ assert (161+ "delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."162+ ) in result.stdout163+164+165+def test_completion_complete_subcommand_noshell():166+ result = subprocess.run(167+ ["coverage", "run", mod.__file__, " "],168+ stdout=subprocess.PIPE,169+ stderr=subprocess.PIPE,170+ encoding="utf-8",171+ env={172+ **os.environ,173+ "_TUTORIAL001.PY_COMPLETE": "complete_noshell",174+ "_TYPER_COMPLETE_ARGS": "tutorial001.py del",175+ "_TYPER_COMPLETE_TESTING": "True",176+ },177+ )178+ assert ("") in result.stdoutadded:tests/test_completion/test_completion_install_source.py+107 added
1+import os2+import subprocess3+4+from first_steps import tutorial001 as mod5+6+7+def test_completion_install_source_bash():8+ result = subprocess.run(9+ ["coverage", "run", mod.__file__],10+ stdout=subprocess.PIPE,11+ stderr=subprocess.PIPE,12+ encoding="utf-8",13+ env={14+ **os.environ,15+ "_TUTORIAL001.PY_COMPLETE": "install-source_bash",16+ "_TYPER_COMPLETE_TESTING": "True",17+ },18+ )19+ assert (20+ 'eval "$(_TUTORIAL001.PY_COMPLETE=source_bash tutorial001.py)"' in result.stdout21+ )22+23+24+def test_completion_install_source_zsh():25+ result = subprocess.run(26+ ["coverage", "run", mod.__file__],27+ stdout=subprocess.PIPE,28+ stderr=subprocess.PIPE,29+ encoding="utf-8",30+ env={31+ **os.environ,32+ "_TUTORIAL001.PY_COMPLETE": "install-source_zsh",33+ "_TYPER_COMPLETE_TESTING": "True",34+ },35+ )36+ assert (37+ 'eval "$(_TUTORIAL001.PY_COMPLETE=source_szh tutorial001.py)"' in result.stdout38+ )39+40+41+def test_completion_install_source_fish():42+ result = subprocess.run(43+ ["coverage", "run", mod.__file__],44+ stdout=subprocess.PIPE,45+ stderr=subprocess.PIPE,46+ encoding="utf-8",47+ env={48+ **os.environ,49+ "_TUTORIAL001.PY_COMPLETE": "install-source_fish",50+ "_TYPER_COMPLETE_TESTING": "True",51+ },52+ )53+ assert (54+ "eval (env _TUTORIAL001.PY_COMPLETE=source_fish tutorial001.py)"55+ in result.stdout56+ )57+58+59+def test_completion_install_source_powershell():60+ result = subprocess.run(61+ ["coverage", "run", mod.__file__],62+ stdout=subprocess.PIPE,63+ stderr=subprocess.PIPE,64+ encoding="utf-8",65+ env={66+ **os.environ,67+ "_TUTORIAL001.PY_COMPLETE": "install-source_powershell",68+ "_TYPER_COMPLETE_TESTING": "True",69+ },70+ )71+ assert (72+ "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"73+ in result.stdout74+ )75+76+77+def test_completion_install_source_pwsh():78+ result = subprocess.run(79+ ["coverage", "run", mod.__file__],80+ stdout=subprocess.PIPE,81+ stderr=subprocess.PIPE,82+ encoding="utf-8",83+ env={84+ **os.environ,85+ "_TUTORIAL001.PY_COMPLETE": "install-source_pwsh",86+ "_TYPER_COMPLETE_TESTING": "True",87+ },88+ )89+ assert (90+ "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"91+ in result.stdout92+ )93+94+95+def test_completion_install_source_noshell():96+ result = subprocess.run(97+ ["coverage", "run", mod.__file__],98+ stdout=subprocess.PIPE,99+ stderr=subprocess.PIPE,100+ encoding="utf-8",101+ env={102+ **os.environ,103+ "_TUTORIAL001.PY_COMPLETE": "install-source_noshell",104+ "_TYPER_COMPLETE_TESTING": "True",105+ },106+ )107+ assert "" in result.stdoutadded:tests/test_completion/test_completion_install.py+140 added
1+import os2+import subprocess3+from pathlib import Path4+from unittest import mock5+6+import shellingham7+import typer8+from typer.testing import CliRunner9+10+from first_steps import tutorial001 as mod11+12+runner = CliRunner()13+app = typer.Typer()14+app.command()(mod.main)15+16+17+def test_completion_install_no_shell():18+ result = subprocess.run(19+ ["coverage", "run", mod.__file__, "--install-completion"],20+ stdout=subprocess.PIPE,21+ stderr=subprocess.PIPE,22+ encoding="utf-8",23+ env={24+ **os.environ,25+ "_TYPER_COMPLETE_TESTING": "True",26+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",27+ },28+ )29+ assert "Error: --install-completion option requires an argument" in result.stderr30+31+32+def test_completion_install_bash():33+ bash_completion_path: Path = Path.home() / ".bash_completion"34+ text = ""35+ if bash_completion_path.is_file():36+ text = bash_completion_path.read_text()37+ result = subprocess.run(38+ ["coverage", "run", mod.__file__, "--install-completion", "bash"],39+ stdout=subprocess.PIPE,40+ stderr=subprocess.PIPE,41+ encoding="utf-8",42+ env={43+ **os.environ,44+ "_TYPER_COMPLETE_TESTING": "True",45+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",46+ },47+ )48+ new_text = bash_completion_path.read_text()49+ bash_completion_path.write_text(text)50+ install_script = 'eval "$(_TUTORIAL001.PY_COMPLETE=source_bash tutorial001.py)'51+ assert install_script not in text52+ assert install_script in new_text53+ assert "completion installed in" in result.stdout54+ assert "Completion will take effect once you restart the terminal." in result.stdout55+56+57+def test_completion_install_zsh():58+ completion_path: Path = Path.home() / ".zshrc"59+ text = ""60+ if completion_path.is_file():61+ text = completion_path.read_text()62+ result = subprocess.run(63+ ["coverage", "run", mod.__file__, "--install-completion", "zsh"],64+ stdout=subprocess.PIPE,65+ stderr=subprocess.PIPE,66+ encoding="utf-8",67+ env={68+ **os.environ,69+ "_TYPER_COMPLETE_TESTING": "True",70+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",71+ },72+ )73+ new_text = completion_path.read_text()74+ completion_path.write_text(text)75+ install_script = 'eval "$(_TUTORIAL001.PY_COMPLETE=source_szh tutorial001.py)"'76+ assert install_script not in text77+ assert install_script in new_text78+ assert "completion installed in" in result.stdout79+ assert "Completion will take effect once you restart the terminal." in result.stdout80+81+82+def test_completion_install_fish():83+ script_path = Path(mod.__file__)84+ completion_path: Path = Path.home() / f".config/fish/completions/{script_path.name}.fish"85+ text = ""86+ if completion_path.is_file():87+ text = completion_path.read_text()88+ result = subprocess.run(89+ ["coverage", "run", mod.__file__, "--install-completion", "fish"],90+ stdout=subprocess.PIPE,91+ stderr=subprocess.PIPE,92+ encoding="utf-8",93+ env={94+ **os.environ,95+ "_TYPER_COMPLETE_TESTING": "True",96+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",97+ },98+ )99+ new_text = completion_path.read_text()100+ completion_path.write_text(text)101+ install_script = "eval (env _TUTORIAL001.PY_COMPLETE=source_fish tutorial001.py)"102+ assert install_script not in text103+ assert install_script in new_text104+ assert "completion installed in" in result.stdout105+ assert "Completion will take effect once you restart the terminal." in result.stdout106+107+108+runner = CliRunner()109+app = typer.Typer()110+app.command()(mod.main)111+112+113+def test_completion_install_powershell():114+ completion_path: Path = Path.home() / f".config/powershell/Microsoft.PowerShell_profile.ps1"115+ completion_path_bytes = f"{completion_path}\n".encode("windows-1252")116+ text = ""117+ if completion_path.is_file():118+ text = completion_path.read_text()119+120+ with mock.patch.object(121+ shellingham, "detect_shell", return_value=("pwsh", "/usr/bin/pwsh")122+ ):123+ with mock.patch.object(124+ subprocess,125+ "run",126+ return_value=subprocess.CompletedProcess(127+ ["pwsh"], returncode=0, stdout=completion_path_bytes,128+ ),129+ ):130+ result = runner.invoke(app, ["--install-completion"])131+ install_script = "Register-ArgumentCompleter -Native -CommandName typer -ScriptBlock $scriptblock"132+ parent: Path = completion_path.parent133+ parent.mkdir(parents=True, exist_ok=True)134+ completion_path.write_text(install_script)135+ new_text = completion_path.read_text()136+ completion_path.write_text(text)137+ assert install_script not in text138+ assert install_script in new_text139+ assert "completion installed in" in result.stdout140+ assert "Completion will take effect once you restart the terminal." in result.stdoutadded:tests/test_completion/test_completion_show.py+103 added
1+import os2+import subprocess3+4+from first_steps import tutorial001 as mod5+6+7+def test_completion_show_no_shell():8+ result = subprocess.run(9+ ["coverage", "run", mod.__file__, "--show-completion"],10+ stdout=subprocess.PIPE,11+ stderr=subprocess.PIPE,12+ encoding="utf-8",13+ env={14+ **os.environ,15+ "_TYPER_COMPLETE_TESTING": "True",16+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",17+ },18+ )19+ assert "Error: --show-completion option requires an argument" in result.stderr20+21+22+def test_completion_show_bash():23+ result = subprocess.run(24+ ["coverage", "run", mod.__file__, "--show-completion", "bash"],25+ stdout=subprocess.PIPE,26+ stderr=subprocess.PIPE,27+ encoding="utf-8",28+ env={29+ **os.environ,30+ "_TYPER_COMPLETE_TESTING": "True",31+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",32+ },33+ )34+ assert (35+ "complete -o default -F _tutorial001py_completion tutorial001.py"36+ in result.stdout37+ )38+39+40+def test_completion_source_zsh():41+ result = subprocess.run(42+ ["coverage", "run", mod.__file__, "--show-completion", "zsh"],43+ stdout=subprocess.PIPE,44+ stderr=subprocess.PIPE,45+ encoding="utf-8",46+ env={47+ **os.environ,48+ "_TYPER_COMPLETE_TESTING": "True",49+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",50+ },51+ )52+ assert "compdef _tutorial001py_completion tutorial001.py" in result.stdout53+54+55+def test_completion_source_fish():56+ result = subprocess.run(57+ ["coverage", "run", mod.__file__, "--show-completion", "fish"],58+ stdout=subprocess.PIPE,59+ stderr=subprocess.PIPE,60+ encoding="utf-8",61+ env={62+ **os.environ,63+ "_TYPER_COMPLETE_TESTING": "True",64+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",65+ },66+ )67+ assert "complete --command tutorial001.py --no-files" in result.stdout68+69+70+def test_completion_source_powershell():71+ result = subprocess.run(72+ ["coverage", "run", mod.__file__, "--show-completion", "powershell"],73+ stdout=subprocess.PIPE,74+ stderr=subprocess.PIPE,75+ encoding="utf-8",76+ env={77+ **os.environ,78+ "_TYPER_COMPLETE_TESTING": "True",79+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",80+ },81+ )82+ assert (83+ "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"84+ in result.stdout85+ )86+87+88+def test_completion_source_pwsh():89+ result = subprocess.run(90+ ["coverage", "run", mod.__file__, "--show-completion", "pwsh"],91+ stdout=subprocess.PIPE,92+ stderr=subprocess.PIPE,93+ encoding="utf-8",94+ env={95+ **os.environ,96+ "_TYPER_COMPLETE_TESTING": "True",97+ "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",98+ },99+ )100+ assert (101+ "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"102+ in result.stdout103+ )added:tests/test_completion/test_completion.py+174 added
1+import os2+import subprocess3+import sys4+from pathlib import Path5+6+from first_steps import tutorial001 as mod7+8+9+def test_show_completion():10+ result = subprocess.run(11+ [12+ "bash",13+ "-c",14+ f"{sys.executable} -m coverage run {mod.__file__} --show-completion",15+ ],16+ stdout=subprocess.PIPE,17+ stderr=subprocess.PIPE,18+ encoding="utf-8",19+ env={**os.environ, "SHELL": "/bin/bash", "_TYPER_COMPLETE_TESTING": "True",},20+ )21+ assert "_TUTORIAL001.PY_COMPLETE=complete_bash" in result.stdout22+23+24+def test_install_completion():25+ bash_completion_path: Path = Path.home() / ".bash_completion"26+ text = ""27+ if bash_completion_path.is_file():28+ text = bash_completion_path.read_text()29+ result = subprocess.run(30+ [31+ "bash",32+ "-c",33+ f"{sys.executable} -m coverage run {mod.__file__} --install-completion",34+ ],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ env={**os.environ, "SHELL": "/bin/bash", "_TYPER_COMPLETE_TESTING": "True",},39+ )40+ new_text = bash_completion_path.read_text()41+ bash_completion_path.write_text(text)42+ assert 'eval "$(_TUTORIAL001.PY_COMPLETE=source_bash tutorial001.py)' in new_text43+ assert "completion installed in" in result.stdout44+ assert "Completion will take effect once you restart the terminal." in result.stdout45+46+47+def test_completion_invalid_instruction():48+ result = subprocess.run(49+ ["coverage", "run", mod.__file__],50+ stdout=subprocess.PIPE,51+ stderr=subprocess.PIPE,52+ encoding="utf-8",53+ env={54+ **os.environ,55+ "_TUTORIAL001.PY_COMPLETE": "sourcebash",56+ "_TYPER_COMPLETE_TESTING": "True",57+ },58+ )59+ assert result.returncode != 060+ assert "Invalid completion instruction." in result.stderr61+62+63+def test_completion_source_bash():64+ result = subprocess.run(65+ ["coverage", "run", mod.__file__],66+ stdout=subprocess.PIPE,67+ stderr=subprocess.PIPE,68+ encoding="utf-8",69+ env={70+ **os.environ,71+ "_TUTORIAL001.PY_COMPLETE": "source_bash",72+ "_TYPER_COMPLETE_TESTING": "True",73+ },74+ )75+ assert (76+ "complete -o default -F _tutorial001py_completion tutorial001.py"77+ in result.stdout78+ )79+80+81+def test_completion_source_invalid_shell():82+ result = subprocess.run(83+ ["coverage", "run", mod.__file__],84+ stdout=subprocess.PIPE,85+ stderr=subprocess.PIPE,86+ encoding="utf-8",87+ env={88+ **os.environ,89+ "_TUTORIAL001.PY_COMPLETE": "source_xxx",90+ "_TYPER_COMPLETE_TESTING": "True",91+ },92+ )93+ assert "Shell xxx not supported." in result.stderr94+95+96+def test_completion_source_invalid_instruction():97+ result = subprocess.run(98+ ["coverage", "run", mod.__file__],99+ stdout=subprocess.PIPE,100+ stderr=subprocess.PIPE,101+ encoding="utf-8",102+ env={103+ **os.environ,104+ "_TUTORIAL001.PY_COMPLETE": "explode_bash",105+ "_TYPER_COMPLETE_TESTING": "True",106+ },107+ )108+ assert "Hello World" in result.stdout109+110+111+def test_completion_source_zsh():112+ result = subprocess.run(113+ ["coverage", "run", mod.__file__],114+ stdout=subprocess.PIPE,115+ stderr=subprocess.PIPE,116+ encoding="utf-8",117+ env={118+ **os.environ,119+ "_TUTORIAL001.PY_COMPLETE": "source_zsh",120+ "_TYPER_COMPLETE_TESTING": "True",121+ },122+ )123+ assert "compdef _tutorial001py_completion tutorial001.py" in result.stdout124+125+126+def test_completion_source_fish():127+ result = subprocess.run(128+ ["coverage", "run", mod.__file__],129+ stdout=subprocess.PIPE,130+ stderr=subprocess.PIPE,131+ encoding="utf-8",132+ env={133+ **os.environ,134+ "_TUTORIAL001.PY_COMPLETE": "source_fish",135+ "_TYPER_COMPLETE_TESTING": "True",136+ },137+ )138+ assert "complete --command tutorial001.py --no-files" in result.stdout139+140+141+def test_completion_source_powershell():142+ result = subprocess.run(143+ ["coverage", "run", mod.__file__],144+ stdout=subprocess.PIPE,145+ stderr=subprocess.PIPE,146+ encoding="utf-8",147+ env={148+ **os.environ,149+ "_TUTORIAL001.PY_COMPLETE": "source_powershell",150+ "_TYPER_COMPLETE_TESTING": "True",151+ },152+ )153+ assert (154+ "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"155+ in result.stdout156+ )157+158+159+def test_completion_source_pwsh():160+ result = subprocess.run(161+ ["coverage", "run", mod.__file__],162+ stdout=subprocess.PIPE,163+ stderr=subprocess.PIPE,164+ encoding="utf-8",165+ env={166+ **os.environ,167+ "_TUTORIAL001.PY_COMPLETE": "source_pwsh",168+ "_TYPER_COMPLETE_TESTING": "True",169+ },170+ )171+ assert (172+ "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"173+ in result.stdout174+ )deleted:tests/test_completion.py-51 removed
1-import os2-import subprocess3-import sys4-from pathlib import Path5-6-import typer7-from typer.testing import CliRunner8-9-from first_steps import tutorial001 as mod10-11-runner = CliRunner()12-app = typer.Typer()13-app.command()(mod.main)14-15-16-def test_show_completion():17- result = subprocess.run(18- [19- "bash",20- "-c",21- f"{sys.executable} -m coverage run {mod.__file__} --show-completion",22- ],23- stdout=subprocess.PIPE,24- stderr=subprocess.PIPE,25- encoding="utf-8",26- env={**os.environ, "SHELL": "/bin/bash"},27- )28- assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in result.stdout29-30-31-def test_install_completion():32- bash_completion_path: Path = Path.home() / ".bash_completion"33- text = ""34- if bash_completion_path.is_file():35- text = bash_completion_path.read_text()36- result = subprocess.run(37- [38- "bash",39- "-c",40- f"{sys.executable} -m coverage run {mod.__file__} --install-completion",41- ],42- stdout=subprocess.PIPE,43- stderr=subprocess.PIPE,44- encoding="utf-8",45- env={**os.environ, "SHELL": "/bin/bash"},46- )47- new_text = bash_completion_path.read_text()48- bash_completion_path.write_text(text)49- assert "_TUTORIAL001.PY_COMPLETE=complete-bash" in new_text50- assert "completion installed in" in result.stdout51- assert "Completion will take effect once you restart the terminal." in result.stdoutmodified:tests/test_others.py+20 added
1 from typing import Optional2+from unittest import mock3 4+import shellingham5 import typer6+import typer.completion7 from typer.main import solve_typer_info_defaults, solve_typer_info_help8 from typer.models import TyperInfo9 from typer.testing import CliRunner10 40 unmodified lines51 def test_defaults_from_info():52 # Mainly for coverage/completeness53 value = solve_typer_info_defaults(TyperInfo())54 assert value55+56+57+def test_install_invalid_shell():58+ app = typer.Typer()59+60+ @app.command()61+ def main():62+ typer.echo("Hello World")63+64+ typer.completion.Shells65+ with mock.patch.object(66+ shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")67+ ):68+ result = runner.invoke(app, ["--install-completion"])69+ assert "Shell xshell is not supported." in result.stdout70+ result = runner.invoke(app)71+ assert "Hello World" in result.stdoutmodified:typer/completion.py+355 added-6 removed
1+import inspect2+import os3+import re4+import subprocess5 import sys2-from typing import Any6+from enum import Enum7+from pathlib import Path8+from typing import Any, Optional, Tuple9 10 import click5-import click_completion6-import click_completion.core11+import click._bashcomplete12 13 from .params import Option14 10-click_completion.init()15+try:16+ import shellingham17+except ImportError: # pragma: nocover18+ shellingham = None19 20 21+_click_patched = False22+23+24+def get_completion_inspect_parameters() -> Tuple[inspect.Parameter, inspect.Parameter]:25+ completion_init()26+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")27+ if shellingham and not test_disable_detection:28+ signature = inspect.signature(_install_completion_placeholder_function)29+ else:30+ signature = inspect.signature(_install_completion_no_auto_placeholder_function)31+ install_param, show_param = signature.parameters.values()32+ return install_param, show_param33+34+35 def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:36 if not value or ctx.resilient_parsing:37 return value # pragma no cover16- shell, path = click_completion.core.install()38+ if isinstance(value, str):39+ shell, path = install(shell=value)40+ else:41+ shell, path = install()42 click.secho(f"{shell} completion installed in {path}.", fg="green")43 click.echo("Completion will take effect once you restart the terminal.")44 sys.exit(0)45 46 47 def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:48 if not value or ctx.resilient_parsing:49 return value # pragma no cover25- click.echo(click_completion.core.get_code())50+ prog_name = ctx.find_root().info_name51+ assert prog_name52+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())53+ if isinstance(value, str):54+ shell = value55+ elif shellingham:56+ shell, _ = shellingham.detect_shell()57+ script_content = get_completion_script(prog_name, complete_var, shell)58+ click.echo(script_content)59 sys.exit(0)60 61 62+class Shells(str, Enum):63+ bash = "bash"64+ zsh = "zsh"65+ fish = "fish"66+ powershell = "powershell"67+ pwsh = "pwsh"68+69+70 # Create a fake command function to extract the completion parameters71 def _install_completion_placeholder_function(72 install_completion: bool = Option(73 None,12 unmodified lines86 help="Show completion for the current shell, to copy it or customize the installation.",87 ),88 ) -> Any:89 pass # pragma no cover90+91+92+def _install_completion_no_auto_placeholder_function(93+ install_completion: Shells = Option(94+ None,95+ callback=install_callback,96+ expose_value=False,97+ help="Install completion for the specified shell.",98+ ),99+ show_completion: Shells = Option(100+ None,101+ callback=show_callback,102+ expose_value=False,103+ help="Show completion for the specified shell, to copy it or customize the installation.",104+ ),105+) -> Any:106+ pass # pragma no cover107+108+109+COMPLETION_SCRIPT_BASH = """110+%(complete_func)s() {111+ local IFS=$'\n'112+ COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\113+ COMP_CWORD=$COMP_CWORD \\114+ %(autocomplete_var)s=complete_bash $1 ) )115+ return 0116+}117+118+complete -o default -F %(complete_func)s %(prog_name)s119+"""120+121+COMPLETION_SCRIPT_ZSH = """122+#compdef %(prog_name)s123+124+%(complete_func)s() {125+ eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s)126+}127+128+compdef %(complete_func)s %(prog_name)s129+"""130+131+COMPLETION_SCRIPT_FISH = 'complete --command %(prog_name)s --no-files --arguments "(env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=get-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s)" --condition "env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=is-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s'132+133+COMPLETION_SCRIPT_POWER_SHELL = """134+Import-Module PSReadLine135+Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete136+$scriptblock = {137+ param($wordToComplete, $commandAst, $cursorPosition)138+ $Env:%(autocomplete_var)s = "complete_powershell"139+ $Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString()140+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete141+ %(prog_name)s | ForEach-Object {142+ $commandArray = $_ -Split ":::"143+ $command = $commandArray[0]144+ $helpString = $commandArray[1]145+ [System.Management.Automation.CompletionResult]::new(146+ $command, $command, 'ParameterValue', $helpString)147+ }148+ $Env:%(autocomplete_var)s = ""149+ $Env:_TYPER_COMPLETE_ARGS = ""150+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = ""151+}152+Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock153+"""154+155+156+def install(157+ shell: Optional[str] = None,158+ prog_name: Optional[str] = None,159+ complete_var: Optional[str] = None,160+) -> Tuple[str, Path]:161+ prog_name = prog_name or click.get_current_context().find_root().info_name162+ assert prog_name163+ if complete_var is None:164+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())165+ if shell is None and shellingham is not None:166+ shell, _ = shellingham.detect_shell()167+ mode = None168+ if shell == "bash":169+ path_obj = Path.home() / ".bash_completion"170+ mode = mode or "a"171+ elif shell == "zsh":172+ path_obj = Path.home() / ".zshrc"173+ mode = mode or "a"174+ elif shell == "fish":175+ path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"176+ mode = mode or "w"177+ elif shell in {"powershell", "pwsh"}:178+ subprocess.run(179+ [180+ shell,181+ "-Command",182+ "Set-ExecutionPolicy",183+ "Unrestricted",184+ "-Scope",185+ "CurrentUser",186+ ]187+ )188+ result = subprocess.run(189+ [shell, "-NoProfile", "-Command", "echo", "$profile"],190+ check=True,191+ stdout=subprocess.PIPE,192+ )193+ if result.returncode != 0: # pragma: nocover194+ click.echo("Couldn't get PowerShell user profile", err=True)195+ raise click.exceptions.Exit(result.returncode)196+ path_str = ""197+ if isinstance(result.stdout, str): # pragma: nocover198+ path_str = result.stdout199+ if isinstance(result.stdout, bytes):200+ try:201+ # PowerShell would be predominant in Windows202+ path_str = result.stdout.decode("windows-1252")203+ except UnicodeDecodeError: # pragma: nocover204+ try:205+ path_str = result.stdout.decode("utf8")206+ except UnicodeDecodeError:207+ click.echo("Couldn't decode the path automatically", err=True)208+ raise click.exceptions.Exit(1)209+ path_obj = Path(path_str.strip())210+ mode = mode or "a"211+ else:212+ click.echo(f"Shell {shell} is not supported.")213+ raise click.exceptions.Exit(1)214+ parent_dir: Path = path_obj.parent215+ parent_dir.mkdir(parents=True, exist_ok=True)216+ script_content = get_installable_script(prog_name, complete_var, shell)217+ with path_obj.open(mode=mode) as f:218+ f.write(f"{script_content}\n")219+ return shell, path_obj220+221+222+def get_installable_script(prog_name: str, complete_var: str, shell: str) -> str:223+ if shell == "bash":224+ return f'eval "$({complete_var}=source_bash {prog_name})"'225+ elif shell == "zsh":226+ return f'eval "$({complete_var}=source_szh {prog_name})"'227+ elif shell == "fish":228+ return f"eval (env {complete_var}=source_fish {prog_name})"229+ elif shell in {"powershell", "pwsh"}:230+ return get_completion_script(prog_name, complete_var, shell)231+ return ""232+233+234+def do_bash_complete(cli: click.Command, prog_name: str) -> bool:235+ cwords = click.parser.split_arg_string(os.getenv("COMP_WORDS", ""))236+ cword = int(os.getenv("COMP_CWORD", 0))237+ args = cwords[1:cword]238+ try:239+ incomplete = cwords[cword]240+ except IndexError:241+ incomplete = ""242+243+ for item in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):244+ click.echo(item[0])245+ return True246+247+248+def do_zsh_complete(cli: click.Command, prog_name: str) -> bool:249+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")250+ cwords = click.parser.split_arg_string(completion_args)251+ args = cwords[1:]252+ if args and not completion_args.endswith(" "):253+ incomplete = args[-1]254+ args = args[:-1]255+ else:256+ incomplete = ""257+258+ def escape(s: str) -> str:259+ return (260+ s.replace('"', '""')261+ .replace("'", "''")262+ .replace("$", "\\$")263+ .replace("`", "\\`")264+ )265+266+ res = []267+ for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):268+ if help:269+ res.append(f'"{escape(item)}":"{escape(help)}"')270+ else:271+ res.append(f'"{escape(item)}"')272+ if res:273+ args_str = "\n".join(res)274+ click.echo(f"_arguments '*: :(({args_str}))'")275+ else:276+ click.echo("_files")277+ return True278+279+280+def do_fish_complete(cli: click.Command, prog_name: str) -> bool:281+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")282+ complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")283+ cwords = click.parser.split_arg_string(completion_args)284+ args = cwords[1:]285+ if args and not completion_args.endswith(" "):286+ incomplete = args[-1]287+ args = args[:-1]288+ else:289+ incomplete = ""290+ show_args = []291+ for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):292+ if help:293+ formatted_help = re.sub(r"\s", " ", help)294+ show_args.append(f"{item}\t{formatted_help}")295+ else:296+ show_args.append(item)297+ if complete_action == "get-args":298+ if show_args:299+ for arg in show_args:300+ click.echo(arg)301+ elif complete_action == "is-args":302+ if show_args:303+ # Activate complete args (no files)304+ sys.exit(0)305+ else:306+ # Deactivate complete args (allow files)307+ sys.exit(1)308+ return True309+310+311+def do_powershell_complete(cli: click.Command, prog_name: str) -> bool:312+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")313+ incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")314+ cwords = click.parser.split_arg_string(completion_args)315+ args = cwords[1:]316+ for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):317+ click.echo(f"{item}:::{help or ' '}")318+319+ return True320+321+322+def do_shell_complete(*, cli: click.Command, prog_name: str, shell: str) -> bool:323+ if shell == "bash":324+ return do_bash_complete(cli, prog_name)325+ elif shell == "zsh":326+ return do_zsh_complete(cli, prog_name)327+ elif shell == "fish":328+ return do_fish_complete(cli, prog_name)329+ elif shell in {"powershell", "pwsh"}:330+ return do_powershell_complete(cli, prog_name)331+ return False332+333+334+_completion_scripts = {335+ "bash": COMPLETION_SCRIPT_BASH,336+ "zsh": COMPLETION_SCRIPT_ZSH,337+ "fish": COMPLETION_SCRIPT_FISH,338+ "powershell": COMPLETION_SCRIPT_POWER_SHELL,339+ "pwsh": COMPLETION_SCRIPT_POWER_SHELL,340+}341+342+343+def get_completion_script(prog_name: str, complete_var: str, shell: str) -> str:344+ cf_name = click._bashcomplete._invalid_ident_char_re.sub(345+ "", prog_name.replace("-", "_")346+ )347+ script = _completion_scripts.get(shell)348+ if script is None:349+ click.echo(f"Shell {shell} not supported.", err=True)350+ sys.exit(1)351+ return (352+ script353+ % dict(354+ complete_func="_{}_completion".format(cf_name),355+ prog_name=prog_name,356+ autocomplete_var=complete_var,357+ )358+ ).strip()359+360+361+def handle_shell_complete(362+ cli: click.Command, prog_name: str, complete_var: str, complete_instr: str363+) -> bool:364+ if "_" not in complete_instr:365+ click.echo("Invalid completion instruction.", err=True)366+ sys.exit(1)367+ command, shell = complete_instr.split("_", 1)368+ if command == "source":369+ click.echo(get_completion_script(prog_name, complete_var, shell))370+ return True371+ elif command == "install-source":372+ click.echo(get_installable_script(prog_name, complete_var, shell))373+ return True374+ elif command == "complete":375+ return do_shell_complete(cli=cli, prog_name=prog_name, shell=shell)376+ return False377+378+379+def completion_init() -> None:380+ global _click_patched381+ if not _click_patched:382+ testing = os.getenv("_TYPER_COMPLETE_TESTING")383+384+ def testing_handle_shell_complete(385+ cli: click.Command, prog_name: str, complete_var: str, complete_instr: str386+ ) -> bool:387+ result = handle_shell_complete(cli, prog_name, complete_var, complete_instr)388+ if result:389+ # Avoid fast_exit(1) in Click so Coverage can finish390+ sys.exit(1)391+ return result392+393+ if testing:394+ click._bashcomplete.bashcomplete = testing_handle_shell_complete395+ else:396+ click._bashcomplete.bashcomplete = handle_shell_complete397+ _click_patched = Truemodified:typer/main.py+5 added-12 removed
6 unmodified lines7 from uuid import UUID8 9 import click10 11+from .completion import get_completion_inspect_parameters12 from .models import (13 AnyType,14 ArgumentInfo,15 CommandFunctionType,10 unmodified lines26 Required,27 TyperInfo,28 )29 29-try:30- import click_completion31- from .completion import _install_completion_placeholder_function32-except ImportError: # pragma: no cover33- click_completion = None30 35-31 def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]:37- signature = inspect.signature(_install_completion_placeholder_function)38- install_param, show_param = signature.parameters.values()32+ install_param, show_param = get_completion_inspect_parameters()33 click_install_param, _ = get_click_param(install_param)34 click_show_param, _ = get_click_param(show_param)35 return click_install_param, click_show_param36 179 unmodified lines216 return group217 218 219 def get_command(typer_instance: Typer) -> click.Command:226- if typer_instance._add_completion and click_completion:227- click_completion.init()220+ if typer_instance._add_completion:221 click_install_param, click_show_param = get_install_completion_arguments()222 if (223 typer_instance.registered_callback224 or typer_instance.info.callback1 unmodified line226 or len(typer_instance.registered_commands) > 1227 ):228 # Create a Group229 click_command = get_group(typer_instance)237- if typer_instance._add_completion and click_completion:230+ if typer_instance._add_completion:231 click_command.params.append(click_install_param)232 click_command.params.append(click_show_param)233 return click_command234 elif len(typer_instance.registered_commands) == 1:235 # Create a single Command236 click_command = get_command_from_info(typer_instance.registered_commands[0])244- if typer_instance._add_completion and click_completion:237+ if typer_instance._add_completion:238 click_command.params.append(click_install_param)239 click_command.params.append(click_show_param)240 return click_command241 assert False, "Could not get a command for this Typer instance" # pragma no cover498 unmodified linesmodified:.gitignore+1 added
7 unmodified lines8 .idea9 site10 .coverage11 htmlcov12+.pytest_cachemodified:mypy.ini+4 added
1 [mypy]2 ignore_missing_imports = True3+disallow_untyped_defs = True4+5+[mypy-tests.*]6+disallow_untyped_defs = Falsemodified:pyproject.toml+2 added-2 removed
35 unmodified lines36 Documentation = "https://typer.tiangolo.com/"37 38 [tool.flit.metadata.requires-extra]39 test = [40- "click-completion",40+ "shellingham",41 "pytest >=4.4.0",42 "pytest-cov",43 "coverage",44 "pytest-xdist",8 unmodified lines53 "markdown-include"54 ]55 all = [56 "colorama",57- "click-completion"57+ "shellingham"58 ]modified:README.md+6 added-4 removed
29 unmodified lines30 31 The key features are:32 33 * **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.34-* **Easy to use**: It's easy to use for the final users. Automatic help, and (optional) automatic completion for all shells.34+* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.35 * **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36 * **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37 * **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.38 203 unmodified lines242 And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.243 244 **You get**: great editor support, including **completion** and **type checks** everywhere.245 246-**Your users get**: automatic **`--help`**, (optional) **auto completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.246+**Your users get**: automatic **`--help`**, **auto completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.247 248 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.249 250 ## Optional Dependencies4 unmodified lines255 256 * <a href="https://pypi.org/project/colorama/" class="external-link" target="_blank"><code>colorama</code></a>: and Click will automatically use it to make sure your terminal's colors always work correctly, even in Windows.257 * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).258 * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.259-* <a href="https://github.com/click-contrib/click-completion" class="external-link" target="_blank"><code>click-completion</code></a>: and Typer will automatically configure it to provide completion for all the shells, including installation commands.259+* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.260+ * With `shellingham` you can just use `--install-completion`.261+ * Without `shellingham`, you have to pass a *CLI Option value* with the name of the shell to install completion, e.g. `--install-completion bash`.262 261-You can install `typer` with `colorama` and `click-completion` with `pip install typer[all]`.263+You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.264 265 ## Other tools and plug-ins266 267 Click has many plug-ins available that you can use. And there are many tools that help with command line applications that you can use as well, even if they are not related to Typer or Click.12 unmodified lines