✨ Add support for Click 8 while keeping compatibility with Click 7 (#317)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent c3a4c72 · Browse files · 40 files·+1338 added−463 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
40 files+1338 added−463 removed
- tests:+223 added−36 removed
- other:+1115 added−427 removed
Provenance
- Commit
b972981- Tree
6d4e4a3- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
c3a4c72
40 files changed+1338 added−463 removed
modified:.github/workflows/test.yml+8 added-1 removed
9 unmodified lines101112131415161718191920212223242526272829303132333435369 unmodified lines runs-on: ubuntu-latest strategy: matrix: python-version: [3.6, 3.7, 3.8] click-7: [true, false] fail-fast: false steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v1 uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Flit run: pip install flit - name: Install Dependencies run: flit install --deps=develop --symlink - name: Install Click 7 if: matrix.click-7 run: pip install "click<8.0.0" - name: Lint if: ${{ matrix.python-version != '3.6' && matrix.click-7 == false }} run: bash scripts/lint.sh - name: Test run: bash scripts/test.sh - name: Upload coverage uses: codecov/codecov-action@v1modified:docs/tutorial/using-click.md+1 added-11 removed
97 unmodified lines98 99 // Notice we have both subcommands, top and hello100 Usage: main.py [OPTIONS] COMMAND [ARGS]...101 102- Typer app, including Click subapp102+Error: Missing command.103 104-Options:105- --install-completion Install completion for the current shell.106- --show-completion Show completion for the current shell, to copy it or customize the installation.107-108- --help Show this message and exit.109-110-Commands:111- hello Simple program that greets NAME for a total of COUNT times.112- top Top level command, form Typer113-104 // Call the Typer part105 $ python main.py top106 107 The Typer app is at the top level73 unmodified linesadded:scripts/get-pwsh-activate.sh+1 added
1curl https://raw.githubusercontent.com/python/cpython/main/Lib/venv/scripts/common/Activate.ps1 -o Activate.ps1modified:scripts/test.sh-1 removed
2 unmodified lines34567782 unmodified linesset -eset -x
bash ./scripts/test-files.shbash ./scripts/lint.sh# Use xdist-pytest --forked to ensure modified sys.path to import relative modules in examples keeps workingpytest --cov=typer --cov=tests --cov=docs_src --cov-report=term-missing --cov-report=xml -o console_output_style=progress --forked --numprocesses=auto ${@}added:tests/assets/__init__.py
added:tests/assets/compat_click7_8.py+29 added
1+from typing import List2+3+import click4+import typer5+6+app = typer.Typer()7+8+9+def shell_complete(10+ ctx: click.Context, param: click.Parameter, incomplete: str11+) -> List[str]:12+ return ["Jonny"]13+14+15+@app.command(context_settings={"auto_envvar_prefix": "TEST"})16+def main(17+ name: str = typer.Option("John", hidden=True),18+ lastname: str = typer.Option("Doe", "/lastname", show_default="Mr. Doe"),19+ age: int = typer.Option(lambda: 42, show_default=True),20+ nickname: str = typer.Option("", shell_complete=shell_complete),21+):22+ """23+ Say hello.24+ """25+ typer.echo(f"Hello {name} {lastname}, it seems you have {age}, {nickname}")26+27+28+if __name__ == "__main__":29+ app()added:tests/test_compat/__init__.py
added:tests/test_compat/test_option_get_help.py+41 added
1+import os2+import subprocess3+4+from typer.testing import CliRunner5+6+from tests.assets import compat_click7_8 as mod7+8+runner = CliRunner()9+10+11+def test_hidden_option():12+ result = runner.invoke(mod.app, ["--help"])13+ assert result.exit_code == 014+ assert "Say hello" in result.output15+ assert "--name" not in result.output16+ assert "/lastname" in result.output17+ assert "TEST_LASTNAME" in result.output18+ assert "(dynamic)" in result.output19+20+21+def test_coverage_call():22+ result = runner.invoke(mod.app)23+ assert result.exit_code == 024+ assert "Hello John Doe, it seems you have 42" in result.output25+26+27+def test_completion():28+ result = subprocess.run(29+ ["coverage", "run", mod.__file__, " "],30+ stdout=subprocess.PIPE,31+ stderr=subprocess.PIPE,32+ encoding="utf-8",33+ env={34+ **os.environ,35+ "_COMPAT_CLICK7_8.PY_COMPLETE": "complete_zsh",36+ "_TYPER_COMPLETE_ARGS": "compat_click7_8.py --nickname ",37+ "_TYPER_COMPLETE_TESTING": "True",38+ },39+ )40+ # TODO: when deprecating Click 7, remove second option41+ assert "Jonny" in result.stdout or "_files" in result.stdoutmodified:tests/test_completion/test_completion_install.py+5 added-1 removed
24 unmodified lines25 "_TYPER_COMPLETE_TESTING": "True",26 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",27 },28 )29+ # TODO: when deprecating Click 7, remove second option30+ assert (31+ "Error: Option '--install-completion' requires an argument" in result.stderr29- assert "Error: --install-completion option requires an argument" in result.stderr32+ or "Error: --install-completion option requires an argument" in result.stderr33+ )34 35 36 def test_completion_install_bash():37 bash_completion_path: Path = Path.home() / ".bashrc"116 unmodified linesmodified:tests/test_completion/test_completion_show.py+5 added-1 removed
14 unmodified lines15 "_TYPER_COMPLETE_TESTING": "True",16 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",17 },18 )19+ # TODO: when deprecating Click 7, remove second option20+ assert (21+ "Error: Option '--show-completion' requires an argument" in result.stderr19- assert "Error: --show-completion option requires an argument" in result.stderr22+ or "Error: --show-completion option requires an argument" in result.stderr23+ )24 25 26 def test_completion_show_bash():27 result = subprocess.run(80 unmodified linesmodified:tests/test_completion/test_completion.py+1 added-1 removed
104 unmodified lines105 "_TUTORIAL001.PY_COMPLETE": "explode_bash",106 "_TYPER_COMPLETE_TESTING": "True",107 },108 )109- assert "Hello World" in result.stdout109+ assert 'Completion instruction "explode" not supported.' in result.stderr110 111 112 def test_completion_source_zsh():113 result = subprocess.run(62 unmodified linesmodified:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+5 added-1 removed
47 unmodified lines48 49 def test_wrong_verbose():50 result = runner.invoke(app, ["delete", "--verbose", "Camila"])51 assert result.exit_code != 052+ # TODO: when deprecating Click 7, remove second option53+ assert (54+ "Error: No such option: --verbose" in result.output52- assert "Error: no such option: --verbose" in result.output55+ or "Error: no such option: --verbose" in result.output56+ )57 58 59 def test_script():60 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_commands/test_help/test_tutorial001.py+20 added-4 removed
64 unmodified lines65 66 def test_delete():67 result = runner.invoke(app, ["delete", "Camila"], input="y\n")68 assert result.exit_code == 069+ # TODO: when deprecating Click 7, remove second option70+ assert (71+ "Are you sure you want to delete the user? [y/n]:" in result.output69- assert "Are you sure you want to delete the user? [y/N]:" in result.output72+ or "Are you sure you want to delete the user? [y/N]:" in result.output73+ )74 assert "Deleting user: Camila" in result.output75 76 77 def test_no_delete():78 result = runner.invoke(app, ["delete", "Camila"], input="n\n")79 assert result.exit_code == 080+ # TODO: when deprecating Click 7, remove second option81+ assert (82+ "Are you sure you want to delete the user? [y/n]:" in result.output76- assert "Are you sure you want to delete the user? [y/N]:" in result.output83+ or "Are you sure you want to delete the user? [y/N]:" in result.output84+ )85 assert "Operation cancelled" in result.output86 87 88 def test_delete_all():89 result = runner.invoke(app, ["delete-all"], input="y\n")90 assert result.exit_code == 091+ # TODO: when deprecating Click 7, remove second option92+ assert (93+ "Are you sure you want to delete ALL users? [y/n]:" in result.output83- assert "Are you sure you want to delete ALL users? [y/N]:" in result.output94+ or "Are you sure you want to delete ALL users? [y/N]:" in result.output95+ )96 assert "Deleting all users" in result.output97 98 99 def test_no_delete_all():100 result = runner.invoke(app, ["delete-all"], input="n\n")101 assert result.exit_code == 0102+ # TODO: when deprecating Click 7, remove second option103+ assert (104+ "Are you sure you want to delete ALL users? [y/n]:" in result.output90- assert "Are you sure you want to delete ALL users? [y/N]:" in result.output105+ or "Are you sure you want to delete ALL users? [y/N]:" in result.output106+ )107 assert "Operation cancelled" in result.output108 109 110 def test_init():13 unmodified linesmodified:tests/test_tutorial/test_commands/test_options/test_tutorial001.py+25 added-5 removed
26 unmodified lines27 28 def test_delete():29 result = runner.invoke(app, ["delete", "Camila"], input="y\n")30 assert result.exit_code == 031+ # TODO: when deprecating Click 7, remove second option32+ assert (33+ "Are you sure you want to delete the user? [y/n]:" in result.output31- assert "Are you sure you want to delete the user? [y/N]:" in result.output34+ or "Are you sure you want to delete the user? [y/N]:" in result.output35+ )36 assert "Deleting user: Camila" in result.output37 38 39 def test_no_delete():40 result = runner.invoke(app, ["delete", "Camila"], input="n\n")41 assert result.exit_code == 042+ # TODO: when deprecating Click 7, remove second option43+ assert (44+ "Are you sure you want to delete the user? [y/n]:" in result.output38- assert "Are you sure you want to delete the user? [y/N]:" in result.output45+ or "Are you sure you want to delete the user? [y/N]:" in result.output46+ )47 assert "Operation cancelled" in result.output48 49 50 def test_delete_all():51 result = runner.invoke(app, ["delete-all"], input="y\n")52 assert result.exit_code == 053+ # TODO: when deprecating Click 7, remove second option54+ assert (55+ "Are you sure you want to delete ALL users? [y/n]:" in result.output45- assert "Are you sure you want to delete ALL users? [y/N]:" in result.output56+ or "Are you sure you want to delete ALL users? [y/N]:" in result.output57+ )58 assert "Deleting all users" in result.output59 60 61 def test_no_delete_all():62 result = runner.invoke(app, ["delete-all"], input="n\n")63 assert result.exit_code == 064+ # TODO: when deprecating Click 7, remove second option65+ assert (66+ "Are you sure you want to delete ALL users? [y/n]:" in result.output52- assert "Are you sure you want to delete ALL users? [y/N]:" in result.output67+ or "Are you sure you want to delete ALL users? [y/N]:" in result.output68+ )69 assert "Operation cancelled" in result.output70 71 72 def test_delete_all_force():73 result = runner.invoke(app, ["delete-all", "--force"])74 assert result.exit_code == 075+ # TODO: when deprecating Click 7, remove second option76+ assert (77+ "Are you sure you want to delete ALL users? [y/n]:" not in result.output59- assert "Are you sure you want to delete ALL users? [y/N]:" not in result.output78+ or "Are you sure you want to delete ALL users? [y/N]:" not in result.output79+ )80 assert "Deleting all users" in result.output81 82 83 def test_init():13 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002.py+6 added-1 removed
27 unmodified lines28 29 def test_invalid_args():30 result = runner.invoke(app, ["Draco", "Hagrid"])31 assert result.exit_code != 032- assert "Error: argument names takes 3 values" in result.stdout32+ # TODO: when deprecating Click 7, remove second option33 34+ assert (35+ "Error: Argument 'names' takes 3 values" in result.stdout36+ or "Error: argument names takes 3 values" in result.stdout37+ )38 39+40 def test_valid_args():41 result = runner.invoke(app, ["Draco", "Hagrid", "Dobby"])42 assert result.exit_code == 043 assert "Hello Draco" in result.stdout12 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001.py+6 added-1 removed
32 unmodified lines33 34 def test_invalid_user():35 result = runner.invoke(app, ["--user", "Camila", "50"])36 assert result.exit_code != 037- assert "Error: --user option requires 3 arguments" in result.output37+ # TODO: when deprecating Click 7, remove second option38 39+ assert (40+ "Error: Option '--user' requires 3 arguments" in result.output41+ or "Error: --user option requires 3 arguments" in result.output42+ )43 44+45 def test_script():46 result = subprocess.run(47 ["coverage", "run", mod.__file__, "--help"],48 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_options/test_completion/test_tutorial008.py+2 added-1 removed
26 unmodified lines27 )28 assert '"Camila":"The reader of books."' in result.stdout29 assert '"Carlos":"The writer of scripts."' in result.stdout30 assert '"Sebastian":"The type hints guy."' in result.stdout31+ # TODO: when deprecating Click 7, remove second option31- assert "['--name']" in result.stderr32+ assert "[]" in result.stderr or "['--name']" in result.stderr33 34 35 def test_1():36 result = runner.invoke(app, ["--name", "Camila", "--name", "Sebastian"])13 unmodified linesmodified:tests/test_tutorial/test_options/test_completion/test_tutorial009.py+2 added-1 removed
26 unmodified lines27 )28 assert '"Camila":"The reader of books."' in result.stdout29 assert '"Carlos":"The writer of scripts."' in result.stdout30 assert '"Sebastian":"The type hints guy."' not in result.stdout31+ # TODO: when deprecating Click 7, remove second option31- assert "['--name', 'Sebastian', '--name']" in result.stderr32+ assert "[]" in result.stderr or "['--name', 'Sebastian', '--name']" in result.stderr33 34 35 def test_1():36 result = runner.invoke(app, ["--name", "Camila", "--name", "Sebastian"])13 unmodified linesmodified:tests/test_tutorial/test_options/test_prompt/test_tutorial003.py+6 added-1 removed
20 unmodified lines21 result = runner.invoke(22 app, input="Old Project\nNew Spice\nOld Project\nOld Project\n"23 )24 assert result.exit_code == 025+ # TODO: when deprecating Click 7, remove second option26+27+ assert (28+ "Error: The two entered values do not match" in result.output25- assert "Error: the two entered values do not match" in result.output29+ or "Error: the two entered values do not match" in result.output30+ )31 assert "Deleting project Old Project" in result.output32 33 34 def test_option():21 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001.py+6 added-1 removed
31 unmodified lines32 33 def test_invalid_no_force():34 result = runner.invoke(app, ["--no-force"])35 assert result.exit_code != 036- assert "Error: no such option: --no-force" in result.output36+ # TODO: when deprecating Click 7, remove second option37 38+ assert (39+ "Error: No such option: --no-force" in result.output40+ or "Error: no such option: --no-force" in result.output41+ )42 43+44 def test_script():45 result = subprocess.run(46 ["coverage", "run", mod.__file__, "--help"],47 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002.py+6 added-1 removed
37 unmodified lines38 39 def test_invalid_no_accept():40 result = runner.invoke(app, ["--no-accept"])41 assert result.exit_code != 042- assert "Error: no such option: --no-accept" in result.output42+ # TODO: when deprecating Click 7, remove second option43 44+ assert (45+ "Error: No such option: --no-accept" in result.output46+ or "Error: no such option: --no-accept" in result.output47+ )48 49+50 def test_script():51 result = subprocess.run(52 ["coverage", "run", mod.__file__, "--help"],53 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+4 added-1 removed
25 unmodified lines26 27 def test_invalid():28 result = runner.invoke(app, ["july-19-1989"])29 assert result.exit_code != 030+ # TODO: when deprecating Click 7, remove second option31 assert (31- "Error: Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': invalid datetime format: july-19-1989. (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"32+ "Error: Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': 'july-19-1989' does not match the formats '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'"33 in result.output34+ or "Error: Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]': invalid datetime format: july-19-1989. (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"35+ in result.output36 )37 38 39 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+5 added-1 removed
24 unmodified lines25 26 def test_invalid():27 result = runner.invoke(app, ["--network", "capsule"])28 assert result.exit_code != 029+ # TODO: when deprecating Click 7, remove second option30+31 assert (30- "Error: Invalid value for '--network': invalid choice: capsule. (choose from simple, conv, lstm)"32+ "Error: Invalid value for '--network': 'capsule' is not one of 'simple', 'conv', 'lstm'"33 in result.output34+ or "Error: Invalid value for '--network': invalid choice: capsule. (choose from simple, conv, lstm)"35+ in result.output36 )37 38 39 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+6 added-1 removed
30 unmodified lines31 32 def test_invalid():33 result = runner.invoke(app, ["Camila", "--age", "15.3"])34 assert result.exit_code != 035+ # TODO: when deprecating Click 7, remove second option36+37 assert (36- "Error: Invalid value for '--age': 15.3 is not a valid integer" in result.output38+ "Error: Invalid value for '--age': '15.3' is not a valid integer"39+ in result.output40+ or "Error: Invalid value for '--age': 15.3 is not a valid integer"41+ in result.output42 )43 44 45 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+16 added-3 removed
27 unmodified lines28 29 def test_invalid_id():30 result = runner.invoke(app, ["1002"])31 assert result.exit_code != 032+ # TODO: when deprecating Click 7, remove second option33 assert (34+ (35+ "Error: Invalid value for 'ID': 1002 is not in the range 0<=x<=1000."36+ in result.output37+ )33- "Error: Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."38+ or "Error: Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."39 in result.output40 )41 42 43 def test_invalid_age():44 result = runner.invoke(app, ["5", "--age", "15"])45 assert result.exit_code != 046+ # TODO: when deprecating Click 7, remove second option47+48 assert (42- "Error: Invalid value for '--age': 15 is smaller than the minimum valid value 18."49+ "Error: Invalid value for '--age': 15 is not in the range x>=18"50 in result.output51+ or "Error: Invalid value for '--age': 15 is smaller than the minimum valid value 18."52+ in result.output53 )54 55 56 def test_invalid_score():57 result = runner.invoke(app, ["5", "--age", "20", "--score", "100.5"])58 assert result.exit_code != 059+ # TODO: when deprecating Click 7, remove second option60+61 assert (51- "Error: Invalid value for '--score': 100.5 is bigger than the maximum valid value 100."62+ "Error: Invalid value for '--score': 100.5 is not in the range x<=100."63 in result.output64+ or "Error: Invalid value for '--score': 100.5 is bigger than the maximum valid value 100."65+ in result.output66 )67 68 69 def test_negative_score():15 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002.py+5 added-1 removed
12 unmodified lines13 14 def test_invalid_id():15 result = runner.invoke(app, ["1002"])16 assert result.exit_code != 017+ # TODO: when deprecating Click 7, remove second option18+19 assert (18- "Error: Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."20+ "Error: Invalid value for 'ID': 1002 is not in the range 0<=x<=1000"21 in result.output22+ or "Error: Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."23+ in result.output24 )25 26 27 def test_clamped():15 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py+5 added-1 removed
19 unmodified lines20 21 def test_invalid_uuid():22 result = runner.invoke(app, ["7479706572-72756c6573"])23 assert result.exit_code != 024+ # TODO: when deprecating Click 7, remove second option25+26 assert (25- "Error: Invalid value for 'USER_ID': 7479706572-72756c6573 is not a valid UUID value"27+ "Error: Invalid value for 'USER_ID': '7479706572-72756c6573' is not a valid UUID"28 in result.output29+ or "Error: Invalid value for 'USER_ID': 7479706572-72756c6573 is not a valid UUID value"30+ in result.output31 )32 33 34 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_using_click/test_tutorial003.py+2 added-3 removed
7 unmodified lines8 9 10 def test_cli():11 result = runner.invoke(mod.typer_click_object, [])12- assert "Usage" in result.stdout13- assert "hello" in result.stdout14- assert "top" in result.stdout12+ # TODO: when deprecating Click 7, remove second option13+ assert "Error: Missing command" in result.stdout or "Usage" in result.stdout14 15 16 def test_typer():17 result = runner.invoke(mod.typer_click_object, ["top"])16 unmodified linesmodified:tests/test_others.py+15 added-5 removed
139 unmodified lines140 "_TYPER_COMPLETE_TESTING": "True",141 },142 )143 assert "info name is: completion_no_types.py" in result.stderr144+ # TODO: when deprecating Click 7, remove second option145+ assert (146+ "args is: []" in result.stderr144- assert "args is: ['--name', 'Sebastian', '--name']" in result.stderr147+ or "args is: ['--name', 'Sebastian', '--name']" in result.stderr148+ )149 assert "incomplete is: Ca" in result.stderr150 assert '"Camila":"The reader of books."' in result.stdout151 assert '"Carlos":"The writer of scripts."' in result.stdout148- assert '"Sebastian":"The type hints guy."' in result.stdout152 153 result = subprocess.run(154 ["coverage", "run", str(file_path)],155 stdout=subprocess.PIPE,17 unmodified lines173 "_TYPER_COMPLETE_TESTING": "True",174 },175 )176 assert "info name is: completion_no_types_order.py" in result.stderr177+ # TODO: when deprecating Click 7, remove second option178+ assert (179+ "args is: []" in result.stderr174- assert "args is: ['--name', 'Sebastian', '--name']" in result.stderr180+ or "args is: ['--name', 'Sebastian', '--name']" in result.stderr181+ )182 assert "incomplete is: Ca" in result.stderr183 assert '"Camila":"The reader of books."' in result.stdout184 assert '"Carlos":"The writer of scripts."' in result.stdout178- assert '"Sebastian":"The type hints guy."' in result.stdout185 186 result = subprocess.run(187 ["coverage", "run", str(file_path)],188 stdout=subprocess.PIPE,29 unmodified lines218 typer.echo(f"arg4: {type(arg4)} {arg4}")219 typer.echo(f"arg5: {type(arg5)} {arg5}")220 221 result = runner.invoke(app, ["Hello", "2", "invalid"])222+ # TODO: when deprecating Click 7, remove second option223+224 assert (217- "Error: Invalid value for 'ARG3': invalid is not a valid integer"225+ "Error: Invalid value for 'ARG3': 'invalid' is not a valid integer"226 in result.stdout227+ or "Error: Invalid value for 'ARG3': invalid is not a valid integer"228+ in result.stdout229 )230 result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])231 assert (232 "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"2 unmodified linesadded:typer/_completion_click7.py+157 added
1+import os2+import re3+import sys4+5+import click6+import click._bashcomplete7+8+from ._completion_shared import get_completion_script9+10+try:11+ import shellingham12+except ImportError: # pragma: nocover13+ shellingham = None14+15+16+_click_patched = False17+18+19+def do_bash_complete(cli: click.Command, prog_name: str) -> bool:20+ cwords = click.parser.split_arg_string(os.getenv("COMP_WORDS", ""))21+ cword = int(os.getenv("COMP_CWORD", 0))22+ args = cwords[1:cword]23+ try:24+ incomplete = cwords[cword]25+ except IndexError:26+ incomplete = ""27+28+ for item in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):29+ click.echo(item[0])30+ return True31+32+33+def do_zsh_complete(cli: click.Command, prog_name: str) -> bool:34+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")35+ cwords = click.parser.split_arg_string(completion_args)36+ args = cwords[1:]37+ if args and not completion_args.endswith(" "):38+ incomplete = args[-1]39+ args = args[:-1]40+ else:41+ incomplete = ""42+43+ def escape(s: str) -> str:44+ return (45+ s.replace('"', '""')46+ .replace("'", "''")47+ .replace("$", "\\$")48+ .replace("`", "\\`")49+ )50+51+ res = []52+ for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):53+ if help:54+ res.append(f'"{escape(item)}":"{escape(help)}"')55+ else:56+ res.append(f'"{escape(item)}"')57+ if res:58+ args_str = "\n".join(res)59+ click.echo(f"_arguments '*: :(({args_str}))'")60+ else:61+ click.echo("_files")62+ return True63+64+65+def do_fish_complete(cli: click.Command, prog_name: str) -> bool:66+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")67+ complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")68+ cwords = click.parser.split_arg_string(completion_args)69+ args = cwords[1:]70+ if args and not completion_args.endswith(" "):71+ incomplete = args[-1]72+ args = args[:-1]73+ else:74+ incomplete = ""75+ show_args = []76+ for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):77+ if help:78+ formatted_help = re.sub(r"\s", " ", help)79+ show_args.append(f"{item}\t{formatted_help}")80+ else:81+ show_args.append(item)82+ if complete_action == "get-args":83+ if show_args:84+ for arg in show_args:85+ click.echo(arg)86+ elif complete_action == "is-args":87+ if show_args:88+ # Activate complete args (no files)89+ sys.exit(0)90+ else:91+ # Deactivate complete args (allow files)92+ sys.exit(1)93+ return True94+95+96+def do_powershell_complete(cli: click.Command, prog_name: str) -> bool:97+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")98+ incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")99+ cwords = click.parser.split_arg_string(completion_args)100+ args = cwords[1:]101+ for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):102+ click.echo(f"{item}:::{help or ' '}")103+104+ return True105+106+107+def do_shell_complete(*, cli: click.Command, prog_name: str, shell: str) -> bool:108+ if shell == "bash":109+ return do_bash_complete(cli, prog_name)110+ elif shell == "zsh":111+ return do_zsh_complete(cli, prog_name)112+ elif shell == "fish":113+ return do_fish_complete(cli, prog_name)114+ elif shell in {"powershell", "pwsh"}:115+ return do_powershell_complete(cli, prog_name)116+ return False117+118+119+def handle_shell_complete(120+ cli: click.Command, prog_name: str, complete_var: str, complete_instr: str121+) -> bool:122+ if "_" not in complete_instr:123+ click.echo("Invalid completion instruction.", err=True)124+ sys.exit(1)125+ command, shell = complete_instr.split("_", 1)126+ if command == "source":127+ click.echo(128+ get_completion_script(129+ prog_name=prog_name, complete_var=complete_var, shell=shell130+ )131+ )132+ return True133+ elif command == "complete":134+ return do_shell_complete(cli=cli, prog_name=prog_name, shell=shell)135+ click.echo(f'Completion instruction "{command}" not supported.', err=True)136+ return False137+138+139+def completion_init() -> None:140+ global _click_patched141+ if not _click_patched:142+ testing = os.getenv("_TYPER_COMPLETE_TESTING")143+144+ def testing_handle_shell_complete(145+ cli: click.Command, prog_name: str, complete_var: str, complete_instr: str146+ ) -> bool:147+ result = handle_shell_complete(cli, prog_name, complete_var, complete_instr)148+ if result:149+ # Avoid fast_exit(1) in Click so Coverage can finish150+ sys.exit(1)151+ return result152+153+ if testing:154+ click._bashcomplete.bashcomplete = testing_handle_shell_complete155+ else:156+ click._bashcomplete.bashcomplete = handle_shell_complete157+ _click_patched = Trueadded:typer/_completion_click8.py+192 added
1+import os2+import re3+import sys4+from typing import Any, Dict, List, Tuple5+6+import click7+import click.parser8+import click.shell_completion9+10+from ._completion_shared import (11+ COMPLETION_SCRIPT_BASH,12+ COMPLETION_SCRIPT_FISH,13+ COMPLETION_SCRIPT_POWER_SHELL,14+ COMPLETION_SCRIPT_ZSH,15+ Shells,16+)17+18+try:19+ import shellingham20+except ImportError: # pragma: nocover21+ shellingham = None22+23+24+class BashComplete(click.shell_completion.BashComplete):25+ name = Shells.bash.value26+ source_template = COMPLETION_SCRIPT_BASH27+28+ def source_vars(self) -> Dict[str, Any]:29+ return {30+ "complete_func": self.func_name,31+ "autocomplete_var": self.complete_var,32+ "prog_name": self.prog_name,33+ }34+35+ def get_completion_args(self) -> Tuple[List[str], str]:36+ cwords = click.parser.split_arg_string(os.environ["COMP_WORDS"])37+ cword = int(os.environ["COMP_CWORD"])38+ args = cwords[1:cword]39+40+ try:41+ incomplete = cwords[cword]42+ except IndexError:43+ incomplete = ""44+45+ return args, incomplete46+47+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:48+ # TODO: Explore replicating the new behavior from Click, with item types and49+ # triggering completion for files and directories50+ # return f"{item.type},{item.value}"51+ return f"{item.value}"52+53+ def complete(self) -> str:54+ args, incomplete = self.get_completion_args()55+ completions = self.get_completions(args, incomplete)56+ out = [self.format_completion(item) for item in completions]57+ return "\n".join(out)58+59+60+class ZshComplete(click.shell_completion.ZshComplete):61+ name = Shells.zsh.value62+ source_template = COMPLETION_SCRIPT_ZSH63+64+ def source_vars(self) -> Dict[str, Any]:65+ return {66+ "complete_func": self.func_name,67+ "autocomplete_var": self.complete_var,68+ "prog_name": self.prog_name,69+ }70+71+ def get_completion_args(self) -> Tuple[List[str], str]:72+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")73+ cwords = click.parser.split_arg_string(completion_args)74+ args = cwords[1:]75+ if args and not completion_args.endswith(" "):76+ incomplete = args[-1]77+ args = args[:-1]78+ else:79+ incomplete = ""80+ return args, incomplete81+82+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:83+ def escape(s: str) -> str:84+ return (85+ s.replace('"', '""')86+ .replace("'", "''")87+ .replace("$", "\\$")88+ .replace("`", "\\`")89+ )90+91+ # TODO: Explore replicating the new behavior from Click, pay attention to92+ # the difference with and without escape93+ # return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"94+ if item.help:95+ return f'"{escape(item.value)}":"{escape(item.help)}"'96+ else:97+ return f'"{escape(item.value)}"'98+99+ def complete(self) -> str:100+ args, incomplete = self.get_completion_args()101+ completions = self.get_completions(args, incomplete)102+ res = [self.format_completion(item) for item in completions]103+ if res:104+ args_str = "\n".join(res)105+ return f"_arguments '*: :(({args_str}))'"106+ else:107+ return "_files"108+109+110+class FishComplete(click.shell_completion.FishComplete):111+ name = Shells.fish.value112+ source_template = COMPLETION_SCRIPT_FISH113+114+ def source_vars(self) -> Dict[str, Any]:115+ return {116+ "complete_func": self.func_name,117+ "autocomplete_var": self.complete_var,118+ "prog_name": self.prog_name,119+ }120+121+ def get_completion_args(self) -> Tuple[List[str], str]:122+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")123+ cwords = click.parser.split_arg_string(completion_args)124+ args = cwords[1:]125+ if args and not completion_args.endswith(" "):126+ incomplete = args[-1]127+ args = args[:-1]128+ else:129+ incomplete = ""130+ return args, incomplete131+132+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:133+ # TODO: Explore replicating the new behavior from Click, pay attention to134+ # the difference with and without formatted help135+ # if item.help:136+ # return f"{item.type},{item.value}\t{item.help}"137+138+ # return f"{item.type},{item.value}139+ if item.help:140+ formatted_help = re.sub(r"\s", " ", item.help)141+ return f"{item.value}\t{formatted_help}"142+ else:143+ return f"{item.value}"144+145+ def complete(self) -> str:146+ complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")147+ args, incomplete = self.get_completion_args()148+ completions = self.get_completions(args, incomplete)149+ show_args = [self.format_completion(item) for item in completions]150+ if complete_action == "get-args":151+ if show_args:152+ return "\n".join(show_args)153+ elif complete_action == "is-args":154+ if show_args:155+ # Activate complete args (no files)156+ sys.exit(0)157+ else:158+ # Deactivate complete args (allow files)159+ sys.exit(1)160+ return "" # pragma: no cover161+162+163+class PowerShellComplete(click.shell_completion.ShellComplete):164+ name = Shells.powershell.value165+ source_template = COMPLETION_SCRIPT_POWER_SHELL166+167+ def source_vars(self) -> Dict[str, Any]:168+ return {169+ "complete_func": self.func_name,170+ "autocomplete_var": self.complete_var,171+ "prog_name": self.prog_name,172+ }173+174+ def get_completion_args(self) -> Tuple[List[str], str]:175+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")176+ incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")177+ cwords = click.parser.split_arg_string(completion_args)178+ args = cwords[1:]179+ return args, incomplete180+181+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:182+ return f"{item.value}:::{item.help or ' '}"183+184+185+def completion_init() -> None:186+ click.shell_completion.add_completion_class(BashComplete, Shells.bash.value)187+ click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value)188+ click.shell_completion.add_completion_class(FishComplete, Shells.fish.value)189+ click.shell_completion.add_completion_class(190+ PowerShellComplete, Shells.powershell.value191+ )192+ click.shell_completion.add_completion_class(PowerShellComplete, Shells.pwsh.value)added:typer/_completion_shared.py+244 added
1+import os2+import re3+import subprocess4+import sys5+from enum import Enum6+from pathlib import Path7+from typing import Optional, Tuple8+9+import click10+11+try:12+ import shellingham13+except ImportError: # pragma: nocover14+ shellingham = None15+16+17+from typing import Optional18+19+20+class Shells(str, Enum):21+ bash = "bash"22+ zsh = "zsh"23+ fish = "fish"24+ powershell = "powershell"25+ pwsh = "pwsh"26+27+28+COMPLETION_SCRIPT_BASH = """29+%(complete_func)s() {30+ local IFS=$'\n'31+ COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\32+ COMP_CWORD=$COMP_CWORD \\33+ %(autocomplete_var)s=complete_bash $1 ) )34+ return 035+}36+37+complete -o default -F %(complete_func)s %(prog_name)s38+"""39+40+COMPLETION_SCRIPT_ZSH = """41+#compdef %(prog_name)s42+43+%(complete_func)s() {44+ eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s)45+}46+47+compdef %(complete_func)s %(prog_name)s48+"""49+50+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"'51+52+COMPLETION_SCRIPT_POWER_SHELL = """53+Import-Module PSReadLine54+Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete55+$scriptblock = {56+ param($wordToComplete, $commandAst, $cursorPosition)57+ $Env:%(autocomplete_var)s = "complete_powershell"58+ $Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString()59+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete60+ %(prog_name)s | ForEach-Object {61+ $commandArray = $_ -Split ":::"62+ $command = $commandArray[0]63+ $helpString = $commandArray[1]64+ [System.Management.Automation.CompletionResult]::new(65+ $command, $command, 'ParameterValue', $helpString)66+ }67+ $Env:%(autocomplete_var)s = ""68+ $Env:_TYPER_COMPLETE_ARGS = ""69+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = ""70+}71+Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock72+"""73+74+_completion_scripts = {75+ "bash": COMPLETION_SCRIPT_BASH,76+ "zsh": COMPLETION_SCRIPT_ZSH,77+ "fish": COMPLETION_SCRIPT_FISH,78+ "powershell": COMPLETION_SCRIPT_POWER_SHELL,79+ "pwsh": COMPLETION_SCRIPT_POWER_SHELL,80+}81+82+# TODO: Probably refactor this, copied from Click 7.x83+_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")84+85+86+def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str:87+ cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))88+ script = _completion_scripts.get(shell)89+ if script is None:90+ click.echo(f"Shell {shell} not supported.", err=True)91+ sys.exit(1)92+ return (93+ script94+ % dict(95+ complete_func="_{}_completion".format(cf_name),96+ prog_name=prog_name,97+ autocomplete_var=complete_var,98+ )99+ ).strip()100+101+102+def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path:103+ # Ref: https://github.com/scop/bash-completion#faq104+ # It seems bash-completion is the official completion system for bash:105+ # Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html106+ # But installing in the locations from the docs doesn't seem to have effect107+ completion_path = Path.home() / f".bash_completions/{prog_name}.sh"108+ rc_path = Path.home() / ".bashrc"109+ rc_path.parent.mkdir(parents=True, exist_ok=True)110+ rc_content = ""111+ if rc_path.is_file():112+ rc_content = rc_path.read_text()113+ completion_init_lines = [f"source {completion_path}"]114+ for line in completion_init_lines:115+ if line not in rc_content: # pragma: nocover116+ rc_content += f"\n{line}"117+ rc_content += "\n"118+ rc_path.write_text(rc_content)119+ # Install completion120+ completion_path.parent.mkdir(parents=True, exist_ok=True)121+ script_content = get_completion_script(122+ prog_name=prog_name, complete_var=complete_var, shell=shell123+ )124+ completion_path.write_text(script_content)125+ return completion_path126+127+128+def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path:129+ # Setup Zsh and load ~/.zfunc130+ zshrc_path = Path.home() / ".zshrc"131+ zshrc_path.parent.mkdir(parents=True, exist_ok=True)132+ zshrc_content = ""133+ if zshrc_path.is_file():134+ zshrc_content = zshrc_path.read_text()135+ completion_init_lines = [136+ "autoload -Uz compinit",137+ "compinit",138+ "zstyle ':completion:*' menu select",139+ "fpath+=~/.zfunc",140+ ]141+ for line in completion_init_lines:142+ if line not in zshrc_content: # pragma: nocover143+ zshrc_content += f"\n{line}"144+ zshrc_content += "\n"145+ zshrc_path.write_text(zshrc_content)146+ # Install completion under ~/.zfunc/147+ path_obj = Path.home() / f".zfunc/_{prog_name}"148+ path_obj.parent.mkdir(parents=True, exist_ok=True)149+ script_content = get_completion_script(150+ prog_name=prog_name, complete_var=complete_var, shell=shell151+ )152+ path_obj.write_text(script_content)153+ return path_obj154+155+156+def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path:157+ path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"158+ parent_dir: Path = path_obj.parent159+ parent_dir.mkdir(parents=True, exist_ok=True)160+ script_content = get_completion_script(161+ prog_name=prog_name, complete_var=complete_var, shell=shell162+ )163+ path_obj.write_text(f"{script_content}\n")164+ return path_obj165+166+167+def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path:168+ subprocess.run(169+ [170+ shell,171+ "-Command",172+ "Set-ExecutionPolicy",173+ "Unrestricted",174+ "-Scope",175+ "CurrentUser",176+ ]177+ )178+ result = subprocess.run(179+ [shell, "-NoProfile", "-Command", "echo", "$profile"],180+ check=True,181+ stdout=subprocess.PIPE,182+ )183+ if result.returncode != 0: # pragma: nocover184+ click.echo("Couldn't get PowerShell user profile", err=True)185+ raise click.exceptions.Exit(result.returncode)186+ path_str = ""187+ if isinstance(result.stdout, str): # pragma: nocover188+ path_str = result.stdout189+ if isinstance(result.stdout, bytes):190+ try:191+ # PowerShell would be predominant in Windows192+ path_str = result.stdout.decode("windows-1252")193+ except UnicodeDecodeError: # pragma: nocover194+ try:195+ path_str = result.stdout.decode("utf8")196+ except UnicodeDecodeError:197+ click.echo("Couldn't decode the path automatically", err=True)198+ raise click.exceptions.Exit(1)199+ path_obj = Path(path_str.strip())200+ parent_dir: Path = path_obj.parent201+ parent_dir.mkdir(parents=True, exist_ok=True)202+ script_content = get_completion_script(203+ prog_name=prog_name, complete_var=complete_var, shell=shell204+ )205+ with path_obj.open(mode="a") as f:206+ f.write(f"{script_content}\n")207+ return path_obj208+209+210+def install(211+ shell: Optional[str] = None,212+ prog_name: Optional[str] = None,213+ complete_var: Optional[str] = None,214+) -> Tuple[str, Path]:215+ prog_name = prog_name or click.get_current_context().find_root().info_name216+ assert prog_name217+ if complete_var is None:218+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())219+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")220+ if shell is None and shellingham is not None and not test_disable_detection:221+ shell, _ = shellingham.detect_shell()222+ if shell == "bash":223+ installed_path = install_bash(224+ prog_name=prog_name, complete_var=complete_var, shell=shell225+ )226+ return shell, installed_path227+ elif shell == "zsh":228+ installed_path = install_zsh(229+ prog_name=prog_name, complete_var=complete_var, shell=shell230+ )231+ return shell, installed_path232+ elif shell == "fish":233+ installed_path = install_fish(234+ prog_name=prog_name, complete_var=complete_var, shell=shell235+ )236+ return shell, installed_path237+ elif shell in {"powershell", "pwsh"}:238+ installed_path = install_powershell(239+ prog_name=prog_name, complete_var=complete_var, shell=shell240+ )241+ return shell, installed_path242+ else:243+ click.echo(f"Shell {shell} is not supported.")244+ raise click.exceptions.Exit(1)modified:typer/completion.py+48 added-358 removed
1 import os2-import re3-import subprocess2 import sys5-from enum import Enum6-from pathlib import Path7-from typing import Any, Optional, Tuple3+from typing import Any, Dict, Tuple4 5 import click10-import click._bashcomplete6 7+from ._completion_shared import Shells, get_completion_script, install8 from .models import ParamMeta9 from .params import Option14-from .utils import get_params_from_function10+from .utils import _get_click_major, get_params_from_function11 12 try:13 import shellingham14 except ImportError: # pragma: nocover33 unmodified lines48 return value # pragma no cover49 prog_name = ctx.find_root().info_name50 assert prog_name51 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())52+ shell = ""53+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")54 if isinstance(value, str):55 shell = value58- elif shellingham:56+ elif shellingham and not test_disable_detection:57 shell, _ = shellingham.detect_shell()58 script_content = get_completion_script(59 prog_name=prog_name, complete_var=complete_var, shell=shell60 )61 click.echo(script_content)62 sys.exit(0)63 64 67-class Shells(str, Enum):68- bash = "bash"69- zsh = "zsh"70- fish = "fish"71- powershell = "powershell"72- pwsh = "pwsh"73-74-65 # Create a fake command function to extract the completion parameters66 def _install_completion_placeholder_function(67 install_completion: bool = Option(68 None,31 unmodified lines100 ) -> Any:101 pass # pragma no cover102 103 114-COMPLETION_SCRIPT_BASH = """115-%(complete_func)s() {116- local IFS=$'\n'117- COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\118- COMP_CWORD=$COMP_CWORD \\119- %(autocomplete_var)s=complete_bash $1 ) )120- return 0121-}104+def completion_init() -> None:105+ if _get_click_major() < 8:106+ from ._completion_click7 import completion_init107 123-complete -o default -F %(complete_func)s %(prog_name)s124-"""125-126-COMPLETION_SCRIPT_ZSH = """127-#compdef %(prog_name)s128-129-%(complete_func)s() {130- eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s)131-}132-133-compdef %(complete_func)s %(prog_name)s134-"""135-136-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"'137-138-COMPLETION_SCRIPT_POWER_SHELL = """139-Import-Module PSReadLine140-Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete141-$scriptblock = {142- param($wordToComplete, $commandAst, $cursorPosition)143- $Env:%(autocomplete_var)s = "complete_powershell"144- $Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString()145- $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete146- %(prog_name)s | ForEach-Object {147- $commandArray = $_ -Split ":::"148- $command = $commandArray[0]149- $helpString = $commandArray[1]150- [System.Management.Automation.CompletionResult]::new(151- $command, $command, 'ParameterValue', $helpString)152- }153- $Env:%(autocomplete_var)s = ""154- $Env:_TYPER_COMPLETE_ARGS = ""155- $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = ""156-}157-Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock158-"""159-160-161-def install(162- shell: Optional[str] = None,163- prog_name: Optional[str] = None,164- complete_var: Optional[str] = None,165-) -> Tuple[str, Path]:166- prog_name = prog_name or click.get_current_context().find_root().info_name167- assert prog_name168- if complete_var is None:169- complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())170- if shell is None and shellingham is not None:171- shell, _ = shellingham.detect_shell()172- if shell == "bash":173- installed_path = install_bash(174- prog_name=prog_name, complete_var=complete_var, shell=shell175- )176- return shell, installed_path177- elif shell == "zsh":178- installed_path = install_zsh(179- prog_name=prog_name, complete_var=complete_var, shell=shell180- )181- return shell, installed_path182- elif shell == "fish":183- installed_path = install_fish(184- prog_name=prog_name, complete_var=complete_var, shell=shell185- )186- return shell, installed_path187- elif shell in {"powershell", "pwsh"}:188- installed_path = install_powershell(189- prog_name=prog_name, complete_var=complete_var, shell=shell190- )191- return shell, installed_path108+ completion_init()109 else:193- click.echo(f"Shell {shell} is not supported.")194- raise click.exceptions.Exit(1)110+ from ._completion_click8 import completion_init111 112+ completion_init()113 197-def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path:198- # Ref: https://github.com/scop/bash-completion#faq199- # It seems bash-completion is the official completion system for bash:200- # Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html201- # But installing in the locations from the docs doesn't seem to have effect202- completion_path = Path.home() / f".bash_completions/{prog_name}.sh"203- rc_path = Path.home() / ".bashrc"204- rc_path.parent.mkdir(parents=True, exist_ok=True)205- rc_content = ""206- if rc_path.is_file():207- rc_content = rc_path.read_text()208- completion_init_lines = [f"source {completion_path}"]209- for line in completion_init_lines:210- if line not in rc_content: # pragma: nocover211- rc_content += f"\n{line}"212- rc_content += "\n"213- rc_path.write_text(rc_content)214- # Install completion215- completion_path.parent.mkdir(parents=True, exist_ok=True)216- script_content = get_completion_script(217- prog_name=prog_name, complete_var=complete_var, shell=shell218- )219- completion_path.write_text(script_content)220- return completion_path114 115+# Re-implement Click's shell_complete to add error message with:116+# Invalid completion instruction117+# To use 7.x instruction style for compatibility118+# And to add extra error messages, for compatibility with Typer in previous versions119+# This is only called in new Command method, only used by Click 8.x+120+def shell_complete(121+ cli: click.BaseCommand,122+ ctx_args: Dict[str, Any],123+ prog_name: str,124+ complete_var: str,125+ instruction: str,126+) -> int:127+ import click128+ import click.shell_completion129 223-def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path:224- # Setup Zsh and load ~/.zfunc225- zshrc_path = Path.home() / ".zshrc"226- zshrc_path.parent.mkdir(parents=True, exist_ok=True)227- zshrc_content = ""228- if zshrc_path.is_file():229- zshrc_content = zshrc_path.read_text()230- completion_init_lines = [231- "autoload -Uz compinit",232- "compinit",233- "zstyle ':completion:*' menu select",234- "fpath+=~/.zfunc",235- ]236- for line in completion_init_lines:237- if line not in zshrc_content: # pragma: nocover238- zshrc_content += f"\n{line}"239- zshrc_content += "\n"240- zshrc_path.write_text(zshrc_content)241- # Install completion under ~/.zfunc/242- path_obj = Path.home() / f".zfunc/_{prog_name}"243- path_obj.parent.mkdir(parents=True, exist_ok=True)244- script_content = get_completion_script(245- prog_name=prog_name, complete_var=complete_var, shell=shell246- )247- path_obj.write_text(script_content)248- return path_obj130+ if "_" not in instruction:131+ click.echo("Invalid completion instruction.", err=True)132+ return 1133 134+ # Click 8 changed the order/style of shell instructions from e.g.135+ # source_bash to bash_source136+ # Typer override to preserve the old style for compatibility137+ # Original in Click 8.x commented:138+ # shell, _, instruction = instruction.partition("_")139+ instruction, _, shell = instruction.partition("_")140+ # Typer override end141 251-def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path:252- path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"253- parent_dir: Path = path_obj.parent254- parent_dir.mkdir(parents=True, exist_ok=True)255- script_content = get_completion_script(256- prog_name=prog_name, complete_var=complete_var, shell=shell257- )258- path_obj.write_text(f"{script_content}\n")259- return path_obj142+ comp_cls = click.shell_completion.get_completion_class(shell)143 261-262-def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path:263- subprocess.run(264- [265- shell,266- "-Command",267- "Set-ExecutionPolicy",268- "Unrestricted",269- "-Scope",270- "CurrentUser",271- ]272- )273- result = subprocess.run(274- [shell, "-NoProfile", "-Command", "echo", "$profile"],275- check=True,276- stdout=subprocess.PIPE,277- )278- if result.returncode != 0: # pragma: nocover279- click.echo("Couldn't get PowerShell user profile", err=True)280- raise click.exceptions.Exit(result.returncode)281- path_str = ""282- if isinstance(result.stdout, str): # pragma: nocover283- path_str = result.stdout284- if isinstance(result.stdout, bytes):285- try:286- # PowerShell would be predominant in Windows287- path_str = result.stdout.decode("windows-1252")288- except UnicodeDecodeError: # pragma: nocover289- try:290- path_str = result.stdout.decode("utf8")291- except UnicodeDecodeError:292- click.echo("Couldn't decode the path automatically", err=True)293- raise click.exceptions.Exit(1)294- path_obj = Path(path_str.strip())295- parent_dir: Path = path_obj.parent296- parent_dir.mkdir(parents=True, exist_ok=True)297- script_content = get_completion_script(298- prog_name=prog_name, complete_var=complete_var, shell=shell299- )300- with path_obj.open(mode="a") as f:301- f.write(f"{script_content}\n")302- return path_obj303-304-305-def do_bash_complete(cli: click.Command, prog_name: str) -> bool:306- cwords = click.parser.split_arg_string(os.getenv("COMP_WORDS", ""))307- cword = int(os.getenv("COMP_CWORD", 0))308- args = cwords[1:cword]309- try:310- incomplete = cwords[cword]311- except IndexError:312- incomplete = ""313-314- for item in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):315- click.echo(item[0])316- return True317-318-319-def do_zsh_complete(cli: click.Command, prog_name: str) -> bool:320- completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")321- cwords = click.parser.split_arg_string(completion_args)322- args = cwords[1:]323- if args and not completion_args.endswith(" "):324- incomplete = args[-1]325- args = args[:-1]326- else:327- incomplete = ""328-329- def escape(s: str) -> str:330- return (331- s.replace('"', '""')332- .replace("'", "''")333- .replace("$", "\\$")334- .replace("`", "\\`")335- )336-337- res = []338- for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):339- if help:340- res.append(f'"{escape(item)}":"{escape(help)}"')341- else:342- res.append(f'"{escape(item)}"')343- if res:344- args_str = "\n".join(res)345- click.echo(f"_arguments '*: :(({args_str}))'")346- else:347- click.echo("_files")348- return True349-350-351-def do_fish_complete(cli: click.Command, prog_name: str) -> bool:352- completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")353- complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")354- cwords = click.parser.split_arg_string(completion_args)355- args = cwords[1:]356- if args and not completion_args.endswith(" "):357- incomplete = args[-1]358- args = args[:-1]359- else:360- incomplete = ""361- show_args = []362- for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):363- if help:364- formatted_help = re.sub(r"\s", " ", help)365- show_args.append(f"{item}\t{formatted_help}")366- else:367- show_args.append(item)368- if complete_action == "get-args":369- if show_args:370- for arg in show_args:371- click.echo(arg)372- elif complete_action == "is-args":373- if show_args:374- # Activate complete args (no files)375- sys.exit(0)376- else:377- # Deactivate complete args (allow files)378- sys.exit(1)379- return True380-381-382-def do_powershell_complete(cli: click.Command, prog_name: str) -> bool:383- completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")384- incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")385- cwords = click.parser.split_arg_string(completion_args)386- args = cwords[1:]387- for item, help in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):388- click.echo(f"{item}:::{help or ' '}")389-390- return True391-392-393-def do_shell_complete(*, cli: click.Command, prog_name: str, shell: str) -> bool:394- if shell == "bash":395- return do_bash_complete(cli, prog_name)396- elif shell == "zsh":397- return do_zsh_complete(cli, prog_name)398- elif shell == "fish":399- return do_fish_complete(cli, prog_name)400- elif shell in {"powershell", "pwsh"}:401- return do_powershell_complete(cli, prog_name)402- return False403-404-405-_completion_scripts = {406- "bash": COMPLETION_SCRIPT_BASH,407- "zsh": COMPLETION_SCRIPT_ZSH,408- "fish": COMPLETION_SCRIPT_FISH,409- "powershell": COMPLETION_SCRIPT_POWER_SHELL,410- "pwsh": COMPLETION_SCRIPT_POWER_SHELL,411-}412-413-414-def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str:415- cf_name = click._bashcomplete._invalid_ident_char_re.sub(416- "", prog_name.replace("-", "_")417- )418- script = _completion_scripts.get(shell)419- if script is None:144+ if comp_cls is None:145 click.echo(f"Shell {shell} not supported.", err=True)421- sys.exit(1)422- return (146+ return 1423- script424- % dict(425- complete_func="_{}_completion".format(cf_name),426- prog_name=prog_name,427- autocomplete_var=complete_var,428- )429- ).strip()147 148+ comp = comp_cls(cli, ctx_args, prog_name, complete_var)149 432-def handle_shell_complete(433- cli: click.Command, prog_name: str, complete_var: str, complete_instr: str434-) -> bool:435- if "_" not in complete_instr:436- click.echo("Invalid completion instruction.", err=True)437- sys.exit(1)438- command, shell = complete_instr.split("_", 1)439- if command == "source":440- click.echo(441- get_completion_script(442- prog_name=prog_name, complete_var=complete_var, shell=shell443- )444- )445- return True446- elif command == "complete":447- return do_shell_complete(cli=cli, prog_name=prog_name, shell=shell)448- return False150+ if instruction == "source":151+ click.echo(comp.source())152+ return 0153 154+ if instruction == "complete":155+ click.echo(comp.complete())156+ return 0157 451-def completion_init() -> None:452- global _click_patched453- if not _click_patched:454- testing = os.getenv("_TYPER_COMPLETE_TESTING")455-456- def testing_handle_shell_complete(457- cli: click.Command, prog_name: str, complete_var: str, complete_instr: str458- ) -> bool:459- result = handle_shell_complete(cli, prog_name, complete_var, complete_instr)460- if result:461- # Avoid fast_exit(1) in Click so Coverage can finish462- sys.exit(1)463- return result464-465- if testing:466- click._bashcomplete.bashcomplete = testing_handle_shell_complete467- else:468- click._bashcomplete.bashcomplete = handle_shell_complete469- _click_patched = True158+ click.echo(f'Completion instruction "{instruction}" not supported.', err=True)159+ return 1modified:typer/core.py+384 added-33 removed
1 import inspect2-from typing import Any, Callable, List, Optional, Tuple, Union2+import os3+import sys4+from gettext import gettext as _5+from typing import (6+ TYPE_CHECKING,7+ Any,8+ Callable,9+ Dict,10+ List,11+ Optional,12+ Sequence,13+ Tuple,14+ Union,15+ cast,16+)17 18+import click19 import click.core20+import click.formatting21+import click.parser22+import click.types23 24+from .utils import _get_click_major25 26+if TYPE_CHECKING: # pragma: no cover27+ import click.shell_completion28+29+30+# TODO: when deprecating Click 7, remove this31+def _typer_param_shell_complete(32+ self: click.core.Parameter, ctx: click.Context, incomplete: str33+) -> List["click.shell_completion.CompletionItem"]:34+ if self._custom_shell_complete is not None:35+ results = self._custom_shell_complete(ctx, self, incomplete)36+37+ if results and isinstance(results[0], str):38+ from click.shell_completion import CompletionItem39+40+ results = [CompletionItem(c) for c in results]41+42+ return cast(List["click.shell_completion.CompletionItem"], results)43+44+ return self.type.shell_complete(ctx, self, incomplete)45+46+47+def _typer_param_setup_autocompletion_compat(48+ self: click.Parameter,49+ *,50+ autocompletion: Optional[51+ Callable[[click.Context, List[str], str], List[Union[Tuple[str, str], str]]]52+ ] = None,53+) -> None:54+ if autocompletion is not None and self._custom_shell_complete is None:55+ import warnings56+57+ warnings.warn(58+ "'autocompletion' is renamed to 'shell_complete'. The old name is"59+ " deprecated and will be removed in Click 8.1. See the docs about"60+ " 'Parameter' for information about new behavior.",61+ DeprecationWarning,62+ stacklevel=2,63+ )64+65+ def compat_autocompletion(66+ ctx: click.Context, param: click.core.Parameter, incomplete: str67+ ) -> List["click.shell_completion.CompletionItem"]:68+ from click.shell_completion import CompletionItem69+70+ out = []71+72+ for c in autocompletion(ctx, [], incomplete): # type: ignore73+ if isinstance(c, tuple):74+ c = CompletionItem(c[0], help=c[1])75+ elif isinstance(c, str):76+ c = CompletionItem(c)77+78+ if c.value.startswith(incomplete):79+ out.append(c)80+81+ return out82+83+ self._custom_shell_complete = compat_autocompletion84+85+86 class TyperArgument(click.core.Argument):87 def __init__(88 self,89 *,7 unmodified lines97 metavar: Optional[str] = None,98 expose_value: bool = True,99 is_eager: bool = False,100 envvar: Optional[Union[str, List[str]]] = None,101+ shell_complete: Optional[102+ Callable[103+ [click.Context, click.Parameter, str],104+ Union[List["click.shell_completion.CompletionItem"], List[str]],105+ ]106+ ] = None,107 autocompletion: Optional[Callable[..., Any]] = None,108 # TyperArgument109 show_default: Union[bool, str] = True,110 show_choices: bool = True,5 unmodified lines116 self.show_default = show_default117 self.show_choices = show_choices118 self.show_envvar = show_envvar119 self.hidden = hidden35- super().__init__(36- param_decls=param_decls,37- type=type,38- required=required,39- default=default,40- callback=callback,41- nargs=nargs,42- metavar=metavar,43- expose_value=expose_value,44- is_eager=is_eager,45- envvar=envvar,46- autocompletion=autocompletion,47- )120+ kwargs: Dict[str, Any] = {121+ "param_decls": param_decls,122+ "type": type,123+ "required": required,124+ "default": default,125+ "callback": callback,126+ "nargs": nargs,127+ "metavar": metavar,128+ "expose_value": expose_value,129+ "is_eager": is_eager,130+ "envvar": envvar,131+ }132+ if _get_click_major() > 7:133+ kwargs["shell_complete"] = shell_complete134+ else:135+ kwargs["autocompletion"] = autocompletion136+ super().__init__(**kwargs)137+ if _get_click_major() > 7:138+ _typer_param_setup_autocompletion_compat(139+ self, autocompletion=autocompletion140+ )141 49- def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]: # type: ignore142+ def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:143 # Modified version of click.core.Option.get_help_record()144 # to support Arguments145 if self.hidden:146 return None9 unmodified lines156 if isinstance(envvar, (list, tuple))157 else envvar158 )159 extra.append(f"env var: {var_str}")67- if self.default is not None and (self.show_default or ctx.show_default): # type: ignore160+ if self.default is not None and (self.show_default or ctx.show_default):161 if isinstance(self.show_default, str):162 default_string = f"({self.show_default})"163 elif isinstance(self.default, (list, tuple)):164 default_string = ", ".join(str(d) for d in self.default)165 elif inspect.isfunction(self.default):166 default_string = "(dynamic)"167 else:75- default_string = self.default168+ default_string = str(self.default)169 extra.append(f"default: {default_string}")170 if self.required:171 extra.append("required")172 if extra:5 unmodified lines178 # Modified version of click.core.Argument.make_metavar()179 # to include Argument name180 if self.metavar is not None:181 return self.metavar89- var = self.name.upper()182+ var = (self.name or "").upper()183 if not self.required:184 var = "[{}]".format(var)185 type_var = self.type.get_metavar(self)186 if type_var:1 unmodified line188 if self.nargs != 1:189 var += "..."190 return var191 192+ def shell_complete(193+ self, ctx: click.Context, incomplete: str194+ ) -> List["click.shell_completion.CompletionItem"]:195+ return _typer_param_shell_complete(self, ctx=ctx, incomplete=incomplete)196 197+198+class TyperOption(click.core.Option):199+ def __init__(200+ self,201+ *,202+ # Parameter203+ param_decls: List[str],204+ type: Optional[Union[click.types.ParamType, Any]] = None,205+ required: Optional[bool] = None,206+ default: Optional[Any] = None,207+ callback: Optional[Callable[..., Any]] = None,208+ nargs: Optional[int] = None,209+ metavar: Optional[str] = None,210+ expose_value: bool = True,211+ is_eager: bool = False,212+ envvar: Optional[Union[str, List[str]]] = None,213+ shell_complete: Optional[214+ Callable[215+ [click.Context, click.Parameter, str],216+ Union[List["click.shell_completion.CompletionItem"], List[str]],217+ ]218+ ] = None,219+ autocompletion: Optional[Callable[..., Any]] = None,220+ # Option221+ show_default: Union[bool, str] = False,222+ prompt: Union[bool, str] = False,223+ confirmation_prompt: Union[bool, str] = False,224+ prompt_required: bool = True,225+ hide_input: bool = False,226+ is_flag: Optional[bool] = None,227+ flag_value: Optional[Any] = None,228+ multiple: bool = False,229+ count: bool = False,230+ allow_from_autoenv: bool = True,231+ help: Optional[str] = None,232+ hidden: bool = False,233+ show_choices: bool = True,234+ show_envvar: bool = False,235+ ):236+ # TODO: when deprecating Click 7, remove custom kwargs with prompt_required237+ # and call super().__init__() directly238+ kwargs: Dict[str, Any] = {239+ "param_decls": param_decls,240+ "type": type,241+ "required": required,242+ "default": default,243+ "callback": callback,244+ "nargs": nargs,245+ "metavar": metavar,246+ "expose_value": expose_value,247+ "is_eager": is_eager,248+ "envvar": envvar,249+ "show_default": show_default,250+ "prompt": prompt,251+ "confirmation_prompt": confirmation_prompt,252+ "hide_input": hide_input,253+ "is_flag": is_flag,254+ "flag_value": flag_value,255+ "multiple": multiple,256+ "count": count,257+ "allow_from_autoenv": allow_from_autoenv,258+ "help": help,259+ "hidden": hidden,260+ "show_choices": show_choices,261+ "show_envvar": show_envvar,262+ }263+ if _get_click_major() > 7:264+ kwargs["prompt_required"] = prompt_required265+ kwargs["shell_complete"] = shell_complete266+ else:267+ kwargs["autocompletion"] = autocompletion268+ super().__init__(**kwargs)269+ if _get_click_major() > 7:270+ _typer_param_setup_autocompletion_compat(271+ self, autocompletion=autocompletion272+ )273+274+ def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:275+ # Click 7.x was not breaking this use case, so in that case, re-use its logic276+ if _get_click_major() < 8:277+ return super().get_help_record(ctx)278+ # Duplicate all of Click's logic only to modify a single line, to allow boolean279+ # flags with only names for False values as it's currently supported by Typer280+ # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false281+ if self.hidden:282+ return None283+284+ any_prefix_is_slash = False285+286+ def _write_opts(opts: Sequence[str]) -> str:287+ nonlocal any_prefix_is_slash288+289+ rv, any_slashes = click.formatting.join_options(opts)290+291+ if any_slashes:292+ any_prefix_is_slash = True293+294+ if not self.is_flag and not self.count:295+ rv += f" {self.make_metavar()}"296+297+ return rv298+299+ rv = [_write_opts(self.opts)]300+301+ if self.secondary_opts:302+ rv.append(_write_opts(self.secondary_opts))303+304+ help = self.help or ""305+ extra = []306+307+ if self.show_envvar:308+ envvar = self.envvar309+310+ if envvar is None:311+ if (312+ self.allow_from_autoenv313+ and ctx.auto_envvar_prefix is not None314+ and self.name is not None315+ ):316+ envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"317+318+ if envvar is not None:319+ var_str = (320+ envvar321+ if isinstance(envvar, str)322+ else ", ".join(str(d) for d in envvar)323+ )324+ extra.append(_("env var: {var}").format(var=var_str))325+326+ # Temporarily enable resilient parsing to avoid type casting327+ # failing for the default. Might be possible to extend this to328+ # help formatting in general.329+ resilient = ctx.resilient_parsing330+ ctx.resilient_parsing = True331+332+ try:333+ default_value = self.get_default(ctx, call=False)334+ finally:335+ ctx.resilient_parsing = resilient336+337+ show_default_is_str = isinstance(self.show_default, str)338+339+ if show_default_is_str or (340+ default_value is not None and (self.show_default or ctx.show_default)341+ ):342+ if show_default_is_str:343+ default_string = f"({self.show_default})"344+ elif isinstance(default_value, (list, tuple)):345+ default_string = ", ".join(str(d) for d in default_value)346+ elif callable(default_value):347+ default_string = _("(dynamic)")348+ elif self.is_bool_flag and self.secondary_opts:349+ # For boolean flags that have distinct True/False opts,350+ # use the opt without prefix instead of the value.351+ # Typer override, original commented352+ # default_string = click.parser.split_opt(353+ # (self.opts if self.default else self.secondary_opts)[0]354+ # )[1]355+ if self.default:356+ if self.opts:357+ default_string = click.parser.split_opt(self.opts[0])[1]358+ else:359+ default_string = str(default_value)360+ else:361+ default_string = click.parser.split_opt(self.secondary_opts[0])[1]362+ # Typer override end363+ elif self.is_bool_flag and not self.secondary_opts and not default_value:364+ default_string = ""365+ else:366+ default_string = str(default_value)367+368+ if default_string:369+ extra.append(_("default: {default}").format(default=default_string))370+371+ if isinstance(self.type, click.types._NumberRangeBase):372+ range_str = self.type._describe_range()373+374+ if range_str:375+ extra.append(range_str)376+377+ if self.required:378+ extra.append(_("required"))379+380+ if extra:381+ extra_str = "; ".join(extra)382+ help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"383+384+ return ("; " if any_prefix_is_slash else " / ").join(rv), help385+386+ def shell_complete(387+ self, ctx: click.Context, incomplete: str388+ ) -> List["click.shell_completion.CompletionItem"]:389+ return _typer_param_shell_complete(self, ctx=ctx, incomplete=incomplete)390+391+392+def _typer_format_options(393+ self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter394+) -> None:395+ args = []396+ opts = []397+ for param in self.get_params(ctx):398+ rv = param.get_help_record(ctx)399+ if rv is not None:400+ if param.param_type_name == "argument":401+ args.append(rv)402+ elif param.param_type_name == "option":403+ opts.append(rv)404+405+ # TODO: explore adding Click's gettext support, e.g.:406+ # from gettext import gettext as _407+ # with formatter.section(_("Options")):408+ # ...409+ if args:410+ with formatter.section("Arguments"):411+ formatter.write_dl(args)412+ if opts:413+ with formatter.section("Options"):414+ formatter.write_dl(opts)415+416+417+def _typer_main_shell_completion(418+ self: click.core.Command,419+ *,420+ ctx_args: Dict[str, Any],421+ prog_name: str,422+ complete_var: Optional[str] = None,423+) -> None:424+ if complete_var is None:425+ complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()426+427+ instruction = os.environ.get(complete_var)428+429+ if not instruction:430+ return431+432+ from .completion import shell_complete433+434+ rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)435+ sys.exit(rv)436+437+438 class TyperCommand(click.core.Command):439 def format_options(440 self, ctx: click.Context, formatter: click.HelpFormatter441 ) -> None:104- args = []105- opts = []106- for param in self.get_params(ctx):107- rv = param.get_help_record(ctx)108- if rv is not None:109- if param.param_type_name == "argument":110- args.append(rv)111- elif param.param_type_name == "option":112- opts.append(rv)442+ _typer_format_options(self, ctx=ctx, formatter=formatter)443 114- if args:115- with formatter.section("Arguments"):116- formatter.write_dl(args)117- if opts:118- with formatter.section("Options"):119- formatter.write_dl(opts)444+ def _main_shell_completion(445+ self,446+ ctx_args: Dict[str, Any],447+ prog_name: str,448+ complete_var: Optional[str] = None,449+ ) -> None:450+ _typer_main_shell_completion(451+ self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var452+ )453+454+455+class TyperGroup(click.core.Group):456+ def format_options(457+ self, ctx: click.Context, formatter: click.HelpFormatter458+ ) -> None:459+ _typer_format_options(self, ctx=ctx, formatter=formatter)460+ self.format_commands(ctx, formatter)461+462+ def _main_shell_completion(463+ self,464+ ctx_args: Dict[str, Any],465+ prog_name: str,466+ complete_var: Optional[str] = None,467+ ) -> None:468+ _typer_main_shell_completion(469+ self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var470+ )modified:typer/main.py+17 added-12 removed
7 unmodified lines8 9 import click10 11 from .completion import get_completion_inspect_parameters12-from .core import TyperArgument, TyperCommand12+from .core import TyperArgument, TyperCommand, TyperGroup, TyperOption13 from .models import (14 AnyType,15 ArgumentInfo,16 CommandFunctionType,27 unmodified lines44 *,45 name: Optional[str] = Default(None),46 cls: Optional[Type[click.Command]] = Default(None),47 invoke_without_command: bool = Default(False),48- no_args_is_help: Optional[bool] = Default(None),48+ no_args_is_help: bool = Default(False),49 subcommand_metavar: Optional[str] = Default(None),50 chain: bool = Default(False),51 result_callback: Optional[Callable[..., Any]] = Default(None),52 # Command36 unmodified lines89 name: Optional[str] = Default(None),90 *,91 cls: Optional[Type[click.Command]] = Default(None),92 invoke_without_command: bool = Default(False),93- no_args_is_help: Optional[bool] = Default(None),93+ no_args_is_help: bool = Default(False),94 subcommand_metavar: Optional[str] = Default(None),95 chain: bool = Default(False),96 result_callback: Optional[Callable[..., Any]] = Default(None),97 # Command74 unmodified lines172 *,173 name: Optional[str] = Default(None),174 cls: Optional[Type[click.Command]] = Default(None),175 invoke_without_command: bool = Default(False),176- no_args_is_help: Optional[bool] = Default(None),176+ no_args_is_help: bool = Default(False),177 subcommand_metavar: Optional[str] = Default(None),178 chain: bool = Default(False),179 result_callback: Optional[Callable[..., Any]] = Default(None),180 # Command165 unmodified lines346 ), "A Typer instance is needed to generate a Click Group"347 commands: Dict[str, click.Command] = {}348 for command_info in group_info.typer_instance.registered_commands:349 command = get_command_from_info(command_info=command_info)350+ if command.name:350- commands[command.name] = command351+ commands[command.name] = command352 for sub_group_info in group_info.typer_instance.registered_groups:353 sub_group = get_group_from_info(sub_group_info)354+ if sub_group.name:353- commands[sub_group.name] = sub_group355+ commands[sub_group.name] = sub_group356 solved_info = solve_typer_info_defaults(group_info)357 (358 params,359 convertors,360 context_param_name,361 ) = get_params_convertors_ctx_param_name_from_function(solved_info.callback)360- cls = solved_info.cls or click.Group362+ cls = solved_info.cls or TyperGroup363 group = cls( # type: ignore364 name=solved_info.name or "",365 commands=commands,366 invoke_without_command=solved_info.invoke_without_command,56 unmodified lines423 convertors,424 context_param_name,425 ) = get_params_convertors_ctx_param_name_from_function(command_info.callback)426 cls = command_info.cls or TyperCommand425- command = cls( # type: ignore427+ command = cls(428 name=name,429 context_settings=command_info.context_settings,430 callback=get_callback(431 callback=command_info.callback,53 unmodified lines485 use_params: Dict[str, Any] = {}486 for param_name in parameters:487 use_params[param_name] = None488 for param in params:489+ if param.name:487- use_params[param.name] = param.default490+ use_params[param.name] = param.default491 492 def wrapper(**kwargs: Any) -> Any:493 for k, v in kwargs.items():494 if k in convertors:44 unmodified lines539 or parameter_info.allow_dash540 or parameter_info.path_type541 or parameter_info.resolve_path542 ):540- return click.Path( # type: ignore543+ return click.Path(544 exists=parameter_info.exists,545 file_okay=parameter_info.file_okay,546 dir_okay=parameter_info.dir_okay,547 writable=parameter_info.writable,137 unmodified lines685 param_decls.extend(parameter_info.param_decls)686 else:687 param_decls.append(default_option_declaration)688 return (686- click.Option(689+ TyperOption(690 # Option691 param_decls=param_decls,689- show_default=parameter_info.show_default, # type: ignore692+ show_default=parameter_info.show_default,693 prompt=parameter_info.prompt,694 confirmation_prompt=parameter_info.confirmation_prompt,695+ prompt_required=parameter_info.prompt_required,696 hide_input=parameter_info.hide_input,697 is_flag=is_flag,698 flag_value=parameter_info.flag_value,699 multiple=is_list,13 unmodified lines713 metavar=parameter_info.metavar,714 expose_value=parameter_info.expose_value,715 is_eager=parameter_info.is_eager,716 envvar=parameter_info.envvar,717+ shell_complete=parameter_info.shell_complete,718 autocompletion=get_param_completion(parameter_info.autocompletion),719 ),720 convertor,721 )143 unmodified linesmodified:typer/models.py+29 added-4 removed
14 unmodified lines15 16 import click17 18 if TYPE_CHECKING: # pragma: no cover19+ import click.shell_completion20+21 from .main import Typer # noqa22 23 24 NoneType = type(None)95 unmodified lines120 *,121 name: Optional[str] = Default(None),122 cls: Optional[Type[click.Command]] = Default(None),123 invoke_without_command: bool = Default(False),122- no_args_is_help: Optional[bool] = Default(None),124+ no_args_is_help: bool = Default(False),125 subcommand_metavar: Optional[str] = Default(None),126 chain: bool = Default(False),127 result_callback: Optional[Callable[..., Any]] = Default(None),128 # Command36 unmodified lines165 metavar: Optional[str] = None,166 expose_value: bool = True,167 is_eager: bool = False,168 envvar: Optional[Union[str, List[str]]] = None,169+ shell_complete: Optional[170+ Callable[171+ [click.Context, click.Parameter, str],172+ Union[List["click.shell_completion.CompletionItem"], List[str]],173+ ]174+ ] = None,175 autocompletion: Optional[Callable[..., Any]] = None,176 # TyperArgument177 show_default: Union[bool, str] = True,178 show_choices: bool = True,12 unmodified lines191 mode: Optional[str] = None,192 encoding: Optional[str] = None,193 errors: Optional[str] = "strict",194 lazy: Optional[bool] = None,187- atomic: Optional[bool] = False,195+ atomic: bool = False,196 # Path197 exists: bool = False,198 file_okay: bool = True,199 dir_okay: bool = True,9 unmodified lines209 self.metavar = metavar210 self.expose_value = expose_value211 self.is_eager = is_eager212 self.envvar = envvar213+ self.shell_complete = shell_complete214 self.autocompletion = autocompletion215 # TyperArgument216 self.show_default = show_default217 self.show_choices = show_choices36 unmodified lines254 metavar: Optional[str] = None,255 expose_value: bool = True,256 is_eager: bool = False,257 envvar: Optional[Union[str, List[str]]] = None,258+ shell_complete: Optional[259+ Callable[260+ [click.Context, click.Parameter, str],261+ Union[List["click.shell_completion.CompletionItem"], List[str]],262+ ]263+ ] = None,264 autocompletion: Optional[Callable[..., Any]] = None,265 # Option266 show_default: bool = True,267 prompt: Union[bool, str] = False,268 confirmation_prompt: bool = False,269+ prompt_required: bool = True,270 hide_input: bool = False,271 is_flag: Optional[bool] = None,272 flag_value: Optional[Any] = None,273 count: bool = False,14 unmodified lines288 mode: Optional[str] = None,289 encoding: Optional[str] = None,290 errors: Optional[str] = "strict",291 lazy: Optional[bool] = None,276- atomic: Optional[bool] = False,292+ atomic: bool = False,293 # Path294 exists: bool = False,295 file_okay: bool = True,296 dir_okay: bool = True,10 unmodified lines307 metavar=metavar,308 expose_value=expose_value,309 is_eager=is_eager,310 envvar=envvar,311+ shell_complete=shell_complete,312 autocompletion=autocompletion,313 # TyperArgument314 show_default=show_default,315 show_choices=show_choices,25 unmodified lines341 path_type=path_type,342 )343 self.prompt = prompt344 self.confirmation_prompt = confirmation_prompt345+ self.prompt_required = prompt_required346 self.hide_input = hide_input347 self.is_flag = is_flag348 self.flag_value = flag_value349 self.count = count11 unmodified lines361 metavar: Optional[str] = None,362 expose_value: bool = True,363 is_eager: bool = False,364 envvar: Optional[Union[str, List[str]]] = None,365+ shell_complete: Optional[366+ Callable[367+ [click.Context, click.Parameter, str],368+ Union[List["click.shell_completion.CompletionItem"], List[str]],369+ ]370+ ] = None,371 autocompletion: Optional[Callable[..., Any]] = None,372 # TyperArgument373 show_default: Union[bool, str] = True,374 show_choices: bool = True,12 unmodified lines387 mode: Optional[str] = None,388 encoding: Optional[str] = None,389 errors: Optional[str] = "strict",390 lazy: Optional[bool] = None,367- atomic: Optional[bool] = False,391+ atomic: bool = False,392 # Path393 exists: bool = False,394 file_okay: bool = True,395 dir_okay: bool = True,10 unmodified lines406 metavar=metavar,407 expose_value=expose_value,408 is_eager=is_eager,409 envvar=envvar,410+ shell_complete=shell_complete,411 autocompletion=autocompletion,412 # TyperArgument413 show_default=show_default,414 show_choices=show_choices,42 unmodified linesmodified:typer/params.py+24 added-3 removed
1-from typing import Any, Callable, List, Optional, Type, Union1+from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union2 3+import click4+5 from .models import ArgumentInfo, OptionInfo6 7+if TYPE_CHECKING: # pragma: no cover8+ import click.shell_completion9 10+11 def Option(12 # Parameter13 default: Optional[Any],14 *param_decls: str,1 unmodified line16 metavar: Optional[str] = None,17 expose_value: bool = True,18 is_eager: bool = False,19 envvar: Optional[Union[str, List[str]]] = None,20+ shell_complete: Optional[21+ Callable[22+ [click.Context, click.Parameter, str],23+ Union[List["click.shell_completion.CompletionItem"], List[str]],24+ ]25+ ] = None,26 autocompletion: Optional[Callable[..., Any]] = None,27 # Option28 show_default: bool = True,29 prompt: Union[bool, str] = False,30 confirmation_prompt: bool = False,31+ prompt_required: bool = True,32 hide_input: bool = False,33 is_flag: Optional[bool] = None,34 flag_value: Optional[Any] = None,35 count: bool = False,14 unmodified lines50 mode: Optional[str] = None,51 encoding: Optional[str] = None,52 errors: Optional[str] = "strict",53 lazy: Optional[bool] = None,42- atomic: Optional[bool] = False,54+ atomic: bool = False,55 # Path56 exists: bool = False,57 file_okay: bool = True,58 dir_okay: bool = True,11 unmodified lines70 metavar=metavar,71 expose_value=expose_value,72 is_eager=is_eager,73 envvar=envvar,74+ shell_complete=shell_complete,75 autocompletion=autocompletion,76 # Option77 show_default=show_default,78 prompt=prompt,79 confirmation_prompt=confirmation_prompt,80+ prompt_required=prompt_required,81 hide_input=hide_input,82 is_flag=is_flag,83 flag_value=flag_value,84 count=count,36 unmodified lines121 metavar: Optional[str] = None,122 expose_value: bool = True,123 is_eager: bool = False,124 envvar: Optional[Union[str, List[str]]] = None,125+ shell_complete: Optional[126+ Callable[127+ [click.Context, click.Parameter, str],128+ Union[List["click.shell_completion.CompletionItem"], List[str]],129+ ]130+ ] = None,131 autocompletion: Optional[Callable[..., Any]] = None,132 # TyperArgument133 show_default: Union[bool, str] = True,134 show_choices: bool = True,12 unmodified lines147 mode: Optional[str] = None,148 encoding: Optional[str] = None,149 errors: Optional[str] = "strict",150 lazy: Optional[bool] = None,131- atomic: Optional[bool] = False,151+ atomic: bool = False,152 # Path153 exists: bool = False,154 file_okay: bool = True,155 dir_okay: bool = True,13 unmodified lines169 metavar=metavar,170 expose_value=expose_value,171 is_eager=is_eager,172 envvar=envvar,173+ shell_complete=shell_complete,174 autocompletion=autocompletion,175 # TyperArgument176 show_default=show_default,177 show_choices=show_choices,27 unmodified linesmodified:typer/testing.py+2 added-2 removed
1-from typing import IO, Any, Iterable, Mapping, Optional, Text, Union1+from typing import IO, Any, Mapping, Optional, Sequence, Text, Union2 3 from click.testing import CliRunner as ClickCliRunner # noqa4 from click.testing import Result5 from typer.main import Typer3 unmodified lines9 class CliRunner(ClickCliRunner):10 def invoke( # type: ignore11 self,12 app: Typer,13- args: Optional[Union[str, Iterable[str]]] = None,13+ args: Optional[Union[str, Sequence[str]]] = None,14 input: Optional[Union[bytes, Text, IO[Any]]] = None,15 env: Optional[Mapping[str, str]] = None,16 catch_exceptions: bool = True,17 color: bool = False,12 unmodified linesmodified:typer/utils.py+6 added
1 import inspect2 from typing import Any, Callable, Dict, get_type_hints3 4+import click5+6 from .models import ParamMeta7 8 9 def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]:7 unmodified lines17 params[param.name] = ParamMeta(18 name=param.name, default=param.default, annotation=annotation19 )20 return params21+22+23+def _get_click_major() -> int:24+ return int(click.__version__.split(".")[0])modified:pyproject.toml+2 added-2 removed
25 unmodified lines26 "Programming Language :: Python :: 3.8",27 "License :: OSI Approved :: MIT License"28 ]29 requires = [30- "click >= 7.1.1, <7.2.0"30+ "click >= 7.1.1, <9.0.0"31 ]32 description-file = "README.md"33 requires-python = ">=3.6"34 7 unmodified lines42 "pytest-cov >=2.10.0,<3.0.0",43 "coverage >=5.2,<6.0",44 "pytest-xdist >=1.32.0,<2.0.0",45 "pytest-sugar >=0.9.4,<0.10.0",46- "mypy ==0.782",46+ "mypy ==0.910",47 "black >=19.10b0,<20.0b0",48 "isort >=5.0.6,<6.0.0"49 ]50 doc = [21 unmodified lines