Skip to content
Myr

🔥 Remove support for Click 7, require Click 8+ (#760)

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 d6921fb · Browse files · 54 files+386 added−812 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

Diff stats

54 files+386 added−812 removed

  • tests:+86 added−275 removed
  • other:+300 added−537 removed

54 files+386 added−812 removed

modified:.github/workflows/test.yml+2 added-9 removed
modified:docs/tutorial/options/callback-and-context.md+9 added-9 removed
6 unmodified lines
7For example, you could do some validation before the rest of the code is executed.89=== "Python 3.7+"1011 ```Python hl_lines="5-8 11"11 ```Python hl_lines="7-10 13"12 {!> ../docs_src/options/callback/tutorial001_an.py!}13 ```1415=== "Python 3.7+ non-Annotated"1617 !!! tip18 Prefer to use the `Annotated` version if possible.1920 ```Python hl_lines="4-7 10"20 ```Python hl_lines="6-9 12"21 {!> ../docs_src/options/callback/tutorial001.py!}22 ```2324Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.
81 unmodified lines
106Let's say that when the callback is running, we want to show a message saying that it's validating the name:107108=== "Python 3.7+"109110 ```Python hl_lines="6"110 ```Python hl_lines="8"111 {!> ../docs_src/options/callback/tutorial002_an.py!}112 ```113114=== "Python 3.7+ non-Annotated"115116 !!! tip117 Prefer to use the `Annotated` version if possible.118119 ```Python hl_lines="5"119 ```Python hl_lines="7"120 {!> ../docs_src/options/callback/tutorial002.py!}121 ```122123And because the callback will be called when the shell calls your program asking for completion, that message `"Validating name"` will be printed and it will break completion.
30 unmodified lines
154The "context" has some additional data about the current execution of your program:155156=== "Python 3.7+"157158 ```Python hl_lines="5-7"158 ```Python hl_lines="7-9"159 {!> ../docs_src/options/callback/tutorial003_an.py!}160 ```161162=== "Python 3.7+ non-Annotated"163164 !!! tip165 Prefer to use the `Annotated` version if possible.166167 ```Python hl_lines="4-6"167 ```Python hl_lines="6-8"168 {!> ../docs_src/options/callback/tutorial003.py!}169 ```170171The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.172173But it will be `False` when calling the program normally. So you can continue the execution of your previous code.174175That's all is needed to fix completion 🚀175That's all is needed to fix completion. 🚀176177Check it:178179<div class="termy">
19 unmodified lines
199The same way you can access the `typer.Context` by declaring a function parameter with its value, you can declare another function parameter with type `typer.CallbackParam` to get the specific Click `Parameter` object.200201=== "Python 3.7+"202203 ```Python hl_lines="5 8"203 ```Python hl_lines="7 10"204 {!> ../docs_src/options/callback/tutorial004_an.py!}205 ```206207=== "Python 3.7+ non-Annotated"208209 !!! tip210 Prefer to use the `Annotated` version if possible.211212 ```Python hl_lines="4 7"212 ```Python hl_lines="6 9"213 {!> ../docs_src/options/callback/tutorial004.py!}214 ```215216It's probably not very common, but you could do it if you need it.
45 unmodified lines
modified:docs_src/options/callback/tutorial001_an.py+3 added-1 removed
1from typing import Optional23import typer4from typing_extensions import Annotated56
2 unmodified lines
9 raise typer.BadParameter("Only Camila is allowed")10 return value111211def main(name: Annotated[str, typer.Option(callback=name_callback)]):13def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):14 print(f"Hello {name}")151617if __name__ == "__main__":
1 unmodified line
modified:docs_src/options/callback/tutorial001.py+3 added-1 removed
1from typing import Optional23import typer456def name_callback(value: str):
1 unmodified line
8 raise typer.BadParameter("Only Camila is allowed")9 return value101110def main(name: str = typer.Option(..., callback=name_callback)):12def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):13 print(f"Hello {name}")141516if __name__ == "__main__":
1 unmodified line
modified:docs_src/options/callback/tutorial002_an.py+3 added-1 removed
1from typing import Optional23import typer4from typing_extensions import Annotated56
3 unmodified lines
10 raise typer.BadParameter("Only Camila is allowed")11 return value121312def main(name: Annotated[str, typer.Option(callback=name_callback)]):14def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):15 print(f"Hello {name}")161718if __name__ == "__main__":
1 unmodified line
modified:docs_src/options/callback/tutorial002.py+3 added-1 removed
1from typing import Optional23import typer456def name_callback(value: str):
2 unmodified lines
9 raise typer.BadParameter("Only Camila is allowed")10 return value111211def main(name: str = typer.Option(..., callback=name_callback)):13def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):14 print(f"Hello {name}")151617if __name__ == "__main__":
1 unmodified line
modified:docs_src/options/callback/tutorial003_an.py+3 added-1 removed
1from typing import Optional23import typer4from typing_extensions import Annotated56
5 unmodified lines
12 raise typer.BadParameter("Only Camila is allowed")13 return value141514def main(name: Annotated[str, typer.Option(callback=name_callback)]):16def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):17 print(f"Hello {name}")181920if __name__ == "__main__":
1 unmodified line
modified:docs_src/options/callback/tutorial003.py+3 added-1 removed
1from typing import Optional23import typer456def name_callback(ctx: typer.Context, value: str):
4 unmodified lines
11 raise typer.BadParameter("Only Camila is allowed")12 return value131413def main(name: str = typer.Option(..., callback=name_callback)):15def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):16 print(f"Hello {name}")171819if __name__ == "__main__":
1 unmodified line
modified:docs_src/options/callback/tutorial004_an.py+3 added-1 removed
1from typing import Optional23import typer4from typing_extensions import Annotated56
5 unmodified lines
12 raise typer.BadParameter("Only Camila is allowed")13 return value141514def main(name: Annotated[str, typer.Option(callback=name_callback)]):16def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):17 print(f"Hello {name}")181920if __name__ == "__main__":
1 unmodified line
modified:docs_src/options/callback/tutorial004.py+3 added-1 removed
1from typing import Optional23import typer456def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):
4 unmodified lines
11 raise typer.BadParameter("Only Camila is allowed")12 return value131413def main(name: str = typer.Option(..., callback=name_callback)):15def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):16 print(f"Hello {name}")171819if __name__ == "__main__":
1 unmodified line
modified:tests/test_compat/test_option_get_help.py+1 added-2 removed
50 unmodified lines
51 "_TYPER_COMPLETE_ARGS": "compat_click7_8.py --nickname ",52 "_TYPER_COMPLETE_TESTING": "True",53 },54 )55 # TODO: when deprecating Click 7, remove second option56 assert "Jonny" in result.stdout or "_files" in result.stdout55 assert "Jonny" in result.stdout
modified:tests/test_completion/test_completion_install.py+1 added-5 removed
25 unmodified lines
26 "_TYPER_COMPLETE_TESTING": "True",27 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",28 },29 )30 # TODO: when deprecating Click 7, remove second option31 assert (32 "Option '--install-completion' requires an argument" in result.stderr30 assert "Option '--install-completion' requires an argument" in result.stderr33 or "--install-completion option requires an argument" in result.stderr34 )313233def test_completion_install_bash():34 bash_completion_path: Path = Path.home() / ".bashrc"
144 unmodified lines
modified:tests/test_completion/test_completion_show.py+18 added-5 removed
1import os2import subprocess3import sys4from unittest import mock56import shellingham7import typer8from typer.testing import CliRunner910from docs_src.commands.index import tutorial001 as mod1112runner = CliRunner()13app = typer.Typer()14app.command()(mod.main)151617def test_completion_show_no_shell():18 result = subprocess.run(19 [sys.executable, "-m", "coverage", "run", mod.__file__, "--show-completion"],20 stdout=subprocess.PIPE,
4 unmodified lines
25 "_TYPER_COMPLETE_TESTING": "True",26 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",27 },28 )20 # TODO: when deprecating Click 7, remove second option21 assert (22 "Option '--show-completion' requires an argument" in result.stderr29 assert "Option '--show-completion' requires an argument" in result.stderr23 or "--show-completion option requires an argument" in result.stderr24 )303132def test_completion_show_bash():33 result = subprocess.run(
116 unmodified lines
150 assert (151 "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"152 in result.stdout153 )154155156def test_completion_show_invalid_shell():157 with mock.patch.object(158 shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")159 ):160 result = runner.invoke(app, ["--show-completion"])161 assert "Shell xshell not supported" in result.stdout
modified:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+1 added-5 removed
61 unmodified lines
6263def test_wrong_verbose():64 result = runner.invoke(app, ["delete", "--verbose", "Camila"])65 assert result.exit_code != 066 # TODO: when deprecating Click 7, remove second option67 assert (68 "No such option: --verbose" in result.output66 assert "No such option: --verbose" in result.output69 or "no such option: --verbose" in result.output70 )676869def test_script():70 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_commands/test_help/test_tutorial001_an.py+4 added-20 removed
67 unmodified lines
6869def test_delete():70 result = runner.invoke(app, ["delete", "Camila"], input="y\n")71 assert result.exit_code == 072 # TODO: when deprecating Click 7, remove second option73 assert (74 "Are you sure you want to delete the user? [y/n]:" in result.output72 assert "Are you sure you want to delete the user? [y/n]:" in result.output75 or "Are you sure you want to delete the user? [y/N]:" in result.output76 )73 assert "Deleting user: Camila" in result.output747576def test_no_delete():77 result = runner.invoke(app, ["delete", "Camila"], input="n\n")78 assert result.exit_code == 083 # TODO: when deprecating Click 7, remove second option84 assert (85 "Are you sure you want to delete the user? [y/n]:" in result.output79 assert "Are you sure you want to delete the user? [y/n]:" in result.output86 or "Are you sure you want to delete the user? [y/N]:" in result.output87 )80 assert "Operation cancelled" in result.output818283def test_delete_all():84 result = runner.invoke(app, ["delete-all"], input="y\n")85 assert result.exit_code == 094 # TODO: when deprecating Click 7, remove second option95 assert (96 "Are you sure you want to delete ALL users? [y/n]:" in result.output86 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output97 or "Are you sure you want to delete ALL users? [y/N]:" in result.output98 )87 assert "Deleting all users" in result.output888990def test_no_delete_all():91 result = runner.invoke(app, ["delete-all"], input="n\n")92 assert result.exit_code == 0105 # TODO: when deprecating Click 7, remove second option106 assert (107 "Are you sure you want to delete ALL users? [y/n]:" in result.output93 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output108 or "Are you sure you want to delete ALL users? [y/N]:" in result.output109 )94 assert "Operation cancelled" in result.output959697def test_init():
13 unmodified lines
modified:tests/test_tutorial/test_commands/test_help/test_tutorial001.py+4 added-20 removed
67 unmodified lines
6869def test_delete():70 result = runner.invoke(app, ["delete", "Camila"], input="y\n")71 assert result.exit_code == 072 # TODO: when deprecating Click 7, remove second option73 assert (74 "Are you sure you want to delete the user? [y/n]:" in result.output72 assert "Are you sure you want to delete the user? [y/n]:" in result.output75 or "Are you sure you want to delete the user? [y/N]:" in result.output76 )73 assert "Deleting user: Camila" in result.output747576def test_no_delete():77 result = runner.invoke(app, ["delete", "Camila"], input="n\n")78 assert result.exit_code == 083 # TODO: when deprecating Click 7, remove second option84 assert (85 "Are you sure you want to delete the user? [y/n]:" in result.output79 assert "Are you sure you want to delete the user? [y/n]:" in result.output86 or "Are you sure you want to delete the user? [y/N]:" in result.output87 )80 assert "Operation cancelled" in result.output818283def test_delete_all():84 result = runner.invoke(app, ["delete-all"], input="y\n")85 assert result.exit_code == 094 # TODO: when deprecating Click 7, remove second option95 assert (96 "Are you sure you want to delete ALL users? [y/n]:" in result.output86 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output97 or "Are you sure you want to delete ALL users? [y/N]:" in result.output98 )87 assert "Deleting all users" in result.output888990def test_no_delete_all():91 result = runner.invoke(app, ["delete-all"], input="n\n")92 assert result.exit_code == 0105 # TODO: when deprecating Click 7, remove second option106 assert (107 "Are you sure you want to delete ALL users? [y/n]:" in result.output93 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output108 or "Are you sure you want to delete ALL users? [y/N]:" in result.output109 )94 assert "Operation cancelled" in result.output959697def test_init():
13 unmodified lines
modified:tests/test_tutorial/test_commands/test_options/test_tutorial001_an.py+5 added-25 removed
27 unmodified lines
2829def test_delete():30 result = runner.invoke(app, ["delete", "Camila"], input="y\n")31 assert result.exit_code == 032 # TODO: when deprecating Click 7, remove second option33 assert (34 "Are you sure you want to delete the user? [y/n]:" in result.output32 assert "Are you sure you want to delete the user? [y/n]:" in result.output35 or "Are you sure you want to delete the user? [y/N]:" in result.output36 )33 assert "Deleting user: Camila" in result.output343536def test_no_delete():37 result = runner.invoke(app, ["delete", "Camila"], input="n\n")38 assert result.exit_code == 043 # TODO: when deprecating Click 7, remove second option44 assert (45 "Are you sure you want to delete the user? [y/n]:" in result.output39 assert "Are you sure you want to delete the user? [y/n]:" in result.output46 or "Are you sure you want to delete the user? [y/N]:" in result.output47 )40 assert "Operation cancelled" in result.output414243def test_delete_all():44 result = runner.invoke(app, ["delete-all"], input="y\n")45 assert result.exit_code == 054 # TODO: when deprecating Click 7, remove second option55 assert (56 "Are you sure you want to delete ALL users? [y/n]:" in result.output46 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output57 or "Are you sure you want to delete ALL users? [y/N]:" in result.output58 )47 assert "Deleting all users" in result.output484950def test_no_delete_all():51 result = runner.invoke(app, ["delete-all"], input="n\n")52 assert result.exit_code == 065 # TODO: when deprecating Click 7, remove second option66 assert (67 "Are you sure you want to delete ALL users? [y/n]:" in result.output53 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output68 or "Are you sure you want to delete ALL users? [y/N]:" in result.output69 )54 assert "Operation cancelled" in result.output555657def test_delete_all_force():58 result = runner.invoke(app, ["delete-all", "--force"])59 assert result.exit_code == 076 # TODO: when deprecating Click 7, remove second option77 assert (78 "Are you sure you want to delete ALL users? [y/n]:" not in result.output60 assert "Are you sure you want to delete ALL users? [y/n]:" not in result.output79 or "Are you sure you want to delete ALL users? [y/N]:" not in result.output80 )61 assert "Deleting all users" in result.output626364def test_init():
13 unmodified lines
modified:tests/test_tutorial/test_commands/test_options/test_tutorial001.py+5 added-25 removed
27 unmodified lines
2829def test_delete():30 result = runner.invoke(app, ["delete", "Camila"], input="y\n")31 assert result.exit_code == 032 # TODO: when deprecating Click 7, remove second option33 assert (34 "Are you sure you want to delete the user? [y/n]:" in result.output32 assert "Are you sure you want to delete the user? [y/n]:" in result.output35 or "Are you sure you want to delete the user? [y/N]:" in result.output36 )33 assert "Deleting user: Camila" in result.output343536def test_no_delete():37 result = runner.invoke(app, ["delete", "Camila"], input="n\n")38 assert result.exit_code == 043 # TODO: when deprecating Click 7, remove second option44 assert (45 "Are you sure you want to delete the user? [y/n]:" in result.output39 assert "Are you sure you want to delete the user? [y/n]:" in result.output46 or "Are you sure you want to delete the user? [y/N]:" in result.output47 )40 assert "Operation cancelled" in result.output414243def test_delete_all():44 result = runner.invoke(app, ["delete-all"], input="y\n")45 assert result.exit_code == 054 # TODO: when deprecating Click 7, remove second option55 assert (56 "Are you sure you want to delete ALL users? [y/n]:" in result.output46 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output57 or "Are you sure you want to delete ALL users? [y/N]:" in result.output58 )47 assert "Deleting all users" in result.output484950def test_no_delete_all():51 result = runner.invoke(app, ["delete-all"], input="n\n")52 assert result.exit_code == 065 # TODO: when deprecating Click 7, remove second option66 assert (67 "Are you sure you want to delete ALL users? [y/n]:" in result.output53 assert "Are you sure you want to delete ALL users? [y/n]:" in result.output68 or "Are you sure you want to delete ALL users? [y/N]:" in result.output69 )54 assert "Operation cancelled" in result.output555657def test_delete_all_force():58 result = runner.invoke(app, ["delete-all", "--force"])59 assert result.exit_code == 076 # TODO: when deprecating Click 7, remove second option77 assert (78 "Are you sure you want to delete ALL users? [y/n]:" not in result.output60 assert "Are you sure you want to delete ALL users? [y/n]:" not in result.output79 or "Are you sure you want to delete ALL users? [y/N]:" not in result.output80 )61 assert "Deleting all users" in result.output626364def test_init():
13 unmodified lines
modified:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002_an.py+1 added-6 removed
30 unmodified lines
3132def test_invalid_args():33 result = runner.invoke(app, ["Draco", "Hagrid"])34 assert result.exit_code != 035 # TODO: when deprecating Click 7, remove second option35 assert "Argument 'names' takes 3 values" in result.stdout3637 assert (38 "Argument 'names' takes 3 values" in result.stdout39 or "argument names takes 3 values" in result.stdout40 )374238def test_valid_args():39 result = runner.invoke(app, ["Draco", "Hagrid", "Dobby"])40 assert result.exit_code == 041 assert "Hello Draco" in result.stdout
12 unmodified lines
modified:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002.py+1 added-6 removed
28 unmodified lines
2930def test_invalid_args():31 result = runner.invoke(app, ["Draco", "Hagrid"])32 assert result.exit_code != 033 # TODO: when deprecating Click 7, remove second option33 assert "Argument 'names' takes 3 values" in result.stdout3435 assert (36 "Argument 'names' takes 3 values" in result.stdout37 or "argument names takes 3 values" in result.stdout38 )354036def test_valid_args():37 result = runner.invoke(app, ["Draco", "Hagrid", "Dobby"])38 assert result.exit_code == 039 assert "Hello Draco" in result.stdout
12 unmodified lines
modified:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001_an.py+1 added-6 removed
33 unmodified lines
3435def test_invalid_user():36 result = runner.invoke(app, ["--user", "Camila", "50"])37 assert result.exit_code != 038 # TODO: when deprecating Click 7, remove second option38 assert "Option '--user' requires 3 arguments" in result.output3940 assert (41 "Option '--user' requires 3 arguments" in result.output42 or "--user option requires 3 arguments" in result.output43 )404541def test_script():42 result = subprocess.run(43 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001.py+1 added-6 removed
33 unmodified lines
3435def test_invalid_user():36 result = runner.invoke(app, ["--user", "Camila", "50"])37 assert result.exit_code != 038 # TODO: when deprecating Click 7, remove second option38 assert "Option '--user' requires 3 arguments" in result.output3940 assert (41 "Option '--user' requires 3 arguments" in result.output42 or "--user option requires 3 arguments" in result.output43 )404541def test_script():42 result = subprocess.run(43 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_options/test_name/test_tutorial001_an.py+1 added-5 removed
27 unmodified lines
2829def test_call_no_args():30 result = runner.invoke(app, ["--name"])31 assert result.exit_code != 032 # TODO: when deprecating Click 7, remove second option33 assert (34 "Option '--name' requires an argument" in result.output32 assert "Option '--name' requires an argument" in result.output35 or "--name option requires an argument" in result.output36 )333435def test_script():36 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_options/test_name/test_tutorial001.py+1 added-5 removed
27 unmodified lines
2829def test_call_no_args():30 result = runner.invoke(app, ["--name"])31 assert result.exit_code != 032 # TODO: when deprecating Click 7, remove second option33 assert (34 "Option '--name' requires an argument" in result.output32 assert "Option '--name' requires an argument" in result.output35 or "--name option requires an argument" in result.output36 )333435def test_script():36 result = subprocess.run(
6 unmodified lines
modified:tests/test_tutorial/test_options/test_prompt/test_tutorial003_an.py+1 added-6 removed
21 unmodified lines
22 result = runner.invoke(23 app, input="Old Project\nNew Spice\nOld Project\nOld Project\n"24 )25 assert result.exit_code == 026 # TODO: when deprecating Click 7, remove second option2728 assert (29 "Error: The two entered values do not match" in result.output26 assert "Error: The two entered values do not match" in result.output30 or "Error: the two entered values do not match" in result.output31 )27 assert "Deleting project Old Project" in result.output282930def test_option():
22 unmodified lines
modified:tests/test_tutorial/test_options/test_prompt/test_tutorial003.py+1 added-6 removed
21 unmodified lines
22 result = runner.invoke(23 app, input="Old Project\nNew Spice\nOld Project\nOld Project\n"24 )25 assert result.exit_code == 026 # TODO: when deprecating Click 7, remove second option2728 assert (29 "Error: The two entered values do not match" in result.output26 assert "Error: The two entered values do not match" in result.output30 or "Error: the two entered values do not match" in result.output31 )27 assert "Deleting project Old Project" in result.output282930def test_option():
22 unmodified lines
modified:tests/test_tutorial/test_options_autocompletion/test_tutorial008_an.py+1 added-2 removed
23 unmodified lines
24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' in result.stdout28 # TODO: when deprecating Click 7, remove second option29 assert "[]" in result.stderr or "['--name']" in result.stderr28 assert "[]" in result.stderr293031def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])
13 unmodified lines
modified:tests/test_tutorial/test_options_autocompletion/test_tutorial008.py+1 added-2 removed
23 unmodified lines
24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' in result.stdout28 # TODO: when deprecating Click 7, remove second option29 assert "[]" in result.stderr or "['--name']" in result.stderr28 assert "[]" in result.stderr293031def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])
13 unmodified lines
modified:tests/test_tutorial/test_options_autocompletion/test_tutorial009_an.py+1 added-2 removed
23 unmodified lines
24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' not in result.stdout28 # TODO: when deprecating Click 7, remove second option29 assert "[]" in result.stderr or "['--name', 'Sebastian', '--name']" in result.stderr28 assert "[]" in result.stderr293031def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])
13 unmodified lines
modified:tests/test_tutorial/test_options_autocompletion/test_tutorial009.py+1 added-2 removed
23 unmodified lines
24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' not in result.stdout28 # TODO: when deprecating Click 7, remove second option29 assert "[]" in result.stderr or "['--name', 'Sebastian', '--name']" in result.stderr28 assert "[]" in result.stderr293031def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])
13 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001_an.py+1 added-6 removed
32 unmodified lines
3334def test_invalid_no_force():35 result = runner.invoke(app, ["--no-force"])36 assert result.exit_code != 037 # TODO: when deprecating Click 7, remove second option37 assert "No such option: --no-force" in result.output3839 assert (40 "No such option: --no-force" in result.output41 or "no such option: --no-force" in result.output42 )394440def test_script():41 result = subprocess.run(42 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001.py+1 added-6 removed
32 unmodified lines
3334def test_invalid_no_force():35 result = runner.invoke(app, ["--no-force"])36 assert result.exit_code != 037 # TODO: when deprecating Click 7, remove second option37 assert "No such option: --no-force" in result.output3839 assert (40 "No such option: --no-force" in result.output41 or "no such option: --no-force" in result.output42 )394440def test_script():41 result = subprocess.run(42 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002_an.py+1 added-6 removed
51 unmodified lines
5253def test_invalid_no_accept():54 result = runner.invoke(app, ["--no-accept"])55 assert result.exit_code != 056 # TODO: when deprecating Click 7, remove second option56 assert "No such option: --no-accept" in result.output5758 assert (59 "No such option: --no-accept" in result.output60 or "no such option: --no-accept" in result.output61 )586359def test_script():60 result = subprocess.run(61 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],62 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002.py+1 added-6 removed
51 unmodified lines
5253def test_invalid_no_accept():54 result = runner.invoke(app, ["--no-accept"])55 assert result.exit_code != 056 # TODO: when deprecating Click 7, remove second option56 assert "No such option: --no-accept" in result.output5758 assert (59 "No such option: --no-accept" in result.output60 or "no such option: --no-accept" in result.output61 )586359def test_script():60 result = subprocess.run(61 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],62 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+1 added-5 removed
30 unmodified lines
31 assert (32 "Invalid value for 'BIRTH:[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]':"33 in result.stdout34 )35 # TODO: when deprecating Click 7, remove second option36 assert (37 "'july-19-1989' does not match the formats" in result.output35 assert "'july-19-1989' does not match the formats" in result.output38 or "invalid datetime format: july-19-1989. (choose from" in result.output39 )36 assert "%Y-%m-%d" in result.output37 assert "%Y-%m-%dT%H:%M:%S" in result.output38 assert "%Y-%m-%d %H:%M:%S" in result.output39
9 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+2 added-14 removed
27 unmodified lines
2829def test_invalid_case():30 result = runner.invoke(app, ["--network", "CONV"])31 assert result.exit_code != 032 # TODO: when deprecating Click 7, remove second option3334 assert (35 "Invalid value for '--network': 'CONV' is not one of" in result.output32 assert "Invalid value for '--network': 'CONV' is not one of" in result.output36 or "Invalid value for '--network': invalid choice: CONV. (choose from"37 in result.output38 )33 assert "simple" in result.output34 assert "conv" in result.output35 assert "lstm" in result.output363738def test_invalid_other():39 result = runner.invoke(app, ["--network", "capsule"])40 assert result.exit_code != 047 # TODO: when deprecating Click 7, remove second option4849 assert (50 "Invalid value for '--network': 'capsule' is not one of" in result.output41 assert "Invalid value for '--network': 'capsule' is not one of" in result.output51 or "Invalid value for '--network': invalid choice: capsule. (choose from"52 in result.output53 )42 assert "simple" in result.output43 assert "conv" in result.output44 assert "lstm" in result.output45
9 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+1 added-6 removed
33 unmodified lines
3435def test_invalid():36 result = runner.invoke(app, ["Camila", "--age", "15.3"])37 assert result.exit_code != 038 # TODO: when deprecating Click 7, remove second option38 assert "Invalid value for '--age': '15.3' is not a valid integer" in result.output3940 assert (41 "Invalid value for '--age': '15.3' is not a valid integer" in result.output42 or "Invalid value for '--age': 15.3 is not a valid integer" in result.output43 )404541def test_script():42 result = subprocess.run(43 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,
4 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001_an.py+2 added-18 removed
43 unmodified lines
4445def test_invalid_id():46 result = runner.invoke(app, ["1002"])47 assert result.exit_code != 048 # TODO: when deprecating Click 7, remove second option48 assert (50 (51 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000."49 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000." in result.output52 in result.output53 )54 or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."55 in result.output50 )515253def test_invalid_age():54 result = runner.invoke(app, ["5", "--age", "15"])55 assert result.exit_code != 062 # TODO: when deprecating Click 7, remove second option56 assert "Invalid value for '--age': 15 is not in the range x>=18" in result.output5764 assert (65 "Invalid value for '--age': 15 is not in the range x>=18" in result.output66 or "Invalid value for '--age': 15 is smaller than the minimum valid value 18."67 in result.output68 )587059def test_invalid_score():60 result = runner.invoke(app, ["5", "--age", "20", "--score", "100.5"])61 assert result.exit_code != 074 # TODO: when deprecating Click 7, remove second option7562 assert (63 "Invalid value for '--score': 100.5 is not in the range x<=100."64 in result.output79 or "Invalid value for '--score': 100.5 is bigger than the maximum valid value"80 in result.output65 )666768def test_negative_score():
15 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+2 added-18 removed
43 unmodified lines
4445def test_invalid_id():46 result = runner.invoke(app, ["1002"])47 assert result.exit_code != 048 # TODO: when deprecating Click 7, remove second option48 assert (50 (51 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000."49 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000." in result.output52 in result.output53 )54 or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."55 in result.output50 )515253def test_invalid_age():54 result = runner.invoke(app, ["5", "--age", "15"])55 assert result.exit_code != 062 # TODO: when deprecating Click 7, remove second option56 assert "Invalid value for '--age': 15 is not in the range x>=18" in result.output5764 assert (65 "Invalid value for '--age': 15 is not in the range x>=18" in result.output66 or "Invalid value for '--age': 15 is smaller than the minimum valid value 18."67 in result.output68 )587059def test_invalid_score():60 result = runner.invoke(app, ["5", "--age", "20", "--score", "100.5"])61 assert result.exit_code != 074 # TODO: when deprecating Click 7, remove second option7562 assert (63 "Invalid value for '--score': 100.5 is not in the range x<=100."64 in result.output79 or "Invalid value for '--score': 100.5 is bigger than the maximum valid value"80 in result.output65 )666768def test_negative_score():
15 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002_an.py-4 removed
13 unmodified lines
1415def test_invalid_id():16 result = runner.invoke(app, ["1002"])17 assert result.exit_code != 018 # TODO: when deprecating Click 7, remove second option1918 assert (19 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000" in result.output22 or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."23 in result.output20 )212223def test_clamped():
15 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002.py-4 removed
13 unmodified lines
1415def test_invalid_id():16 result = runner.invoke(app, ["1002"])17 assert result.exit_code != 018 # TODO: when deprecating Click 7, remove second option1918 assert (19 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000" in result.output22 or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."23 in result.output20 )212223def test_clamped():
15 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py-4 removed
20 unmodified lines
2122def test_invalid_uuid():23 result = runner.invoke(app, ["7479706572-72756c6573"])24 assert result.exit_code != 025 # TODO: when deprecating Click 7, remove second option2625 assert (26 "Invalid value for 'USER_ID': '7479706572-72756c6573' is not a valid UUID"27 in result.output30 or "Invalid value for 'USER_ID': 7479706572-72756c6573 is not a valid UUID value"31 in result.output28 )293031def test_script():
7 unmodified lines
modified:tests/test_tutorial/test_using_click/test_tutorial003.py+1 added-2 removed
8 unmodified lines
91011def test_cli():12 result = runner.invoke(mod.typer_click_object, [])13 # TODO: when deprecating Click 7, remove second option14 assert "Missing command" in result.stdout or "Usage" in result.stdout13 assert "Missing command" in result.stdout141516def test_help():17 result = runner.invoke(mod.typer_click_object, ["--help"])
24 unmodified lines
modified:tests/test_others.py+22 added-15 removed
8 unmodified lines
9import pytest10import shellingham11import typer12import typer.completion13from typer.core import _split_opt14from typer.main import solve_typer_info_defaults, solve_typer_info_help15from typer.models import ParameterInfo, TyperInfo16from typer.testing import CliRunner17
137 unmodified lines
155 "_TYPER_COMPLETE_TESTING": "True",156 },157 )158 assert "info name is: completion_no_types.py" in result.stderr158 # TODO: when deprecating Click 7, remove second option159 assert (160 "args is: []" in result.stderr159 assert "args is: []" in result.stderr161 or "args is: ['--name', 'Sebastian', '--name']" in result.stderr162 )160 assert "incomplete is: Ca" in result.stderr161 assert '"Camila":"The reader of books."' in result.stdout162 assert '"Carlos":"The writer of scripts."' in result.stdout163
20 unmodified lines
184 "_TYPER_COMPLETE_TESTING": "True",185 },186 )187 assert "info name is: completion_no_types_order.py" in result.stderr191 # TODO: when deprecating Click 7, remove second option192 assert (193 "args is: []" in result.stderr188 assert "args is: []" in result.stderr194 or "args is: ['--name', 'Sebastian', '--name']" in result.stderr195 )189 assert "incomplete is: Ca" in result.stderr190 assert '"Camila":"The reader of books."' in result.stdout191 assert '"Carlos":"The writer of scripts."' in result.stdout192
32 unmodified lines
225 print(f"arg4: {type(arg4)} {arg4}")226 print(f"arg5: {type(arg5)} {arg5}")227228 result = runner.invoke(app, ["Hello", "2", "invalid"])236 # TODO: when deprecating Click 7, remove second option229238 assert (239 "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout230 assert "Invalid value for 'ARG3': 'invalid' is not a valid integer" in result.stdout240 or "Invalid value for 'ARG3': invalid is not a valid integer" in result.stdout241 )231 result = runner.invoke(app, ["Hello", "2", "3", "--arg4", "--arg5"])232 assert (233 "arg1: <class 'str'> Hello\narg2: <class 'int'> 2\narg3: <class 'int'> 3\narg4: <class 'bool'> True\narg5: <class 'bool'> True\n"234 in result.stdout
8 unmodified lines
243 pass # pragma: nocover244245 result = runner.invoke(app, ["main", "-h"])246 assert "Show this message and exit." in result.stdout247248249def test_split_opt():250 prefix, opt = _split_opt("--verbose")251 assert prefix == "--"252 assert opt == "verbose"253254 prefix, opt = _split_opt("//verbose")255 assert prefix == "//"256 assert opt == "verbose"257258 prefix, opt = _split_opt("-verbose")259 assert prefix == "-"260 assert opt == "verbose"261262 prefix, opt = _split_opt("verbose")263 assert prefix == ""264 assert opt == "verbose"
deleted:typer/_compat_utils.py-5 removed
1import click234def _get_click_major() -> int:5 return int(click.__version__.split(".")[0])
added:typer/_completion_classes.py+192 added
1import os2import re3import sys4from typing import Any, Dict, List, Tuple56import click7import click.parser8import click.shell_completion910from ._completion_shared import (11 COMPLETION_SCRIPT_BASH,12 COMPLETION_SCRIPT_FISH,13 COMPLETION_SCRIPT_POWER_SHELL,14 COMPLETION_SCRIPT_ZSH,15 Shells,16)1718try:19 import shellingham20except ImportError: # pragma: nocover21 shellingham = None222324class BashComplete(click.shell_completion.BashComplete):25 name = Shells.bash.value26 source_template = COMPLETION_SCRIPT_BASH2728 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 }3435 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]3940 try:41 incomplete = cwords[cword]42 except IndexError:43 incomplete = ""4445 return args, incomplete4647 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}"5253 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)585960class ZshComplete(click.shell_completion.ZshComplete):61 name = Shells.zsh.value62 source_template = COMPLETION_SCRIPT_ZSH6364 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 }7071 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, incomplete8182 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 )9091 # 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)}"'9899 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"108109110class FishComplete(click.shell_completion.FishComplete):111 name = Shells.fish.value112 source_template = COMPLETION_SCRIPT_FISH113114 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 }120121 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, incomplete131132 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}"137138 # 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}"144145 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 cover161162163class PowerShellComplete(click.shell_completion.ShellComplete):164 name = Shells.powershell.value165 source_template = COMPLETION_SCRIPT_POWER_SHELL166167 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 }173174 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, incomplete180181 def format_completion(self, item: click.shell_completion.CompletionItem) -> str:182 return f"{item.value}:::{item.help or ' '}"183184185def 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)
deleted:typer/_completion_click7.py-157 removed
1import os2import re3import sys45import click6import click._bashcomplete78from ._completion_shared import get_completion_script910try:11 import shellingham12except ImportError: # pragma: nocover13 shellingham = None141516_click_patched = False171819def 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 = ""2728 for item in click._bashcomplete.get_choices(cli, prog_name, args, incomplete):29 click.echo(item[0])30 return True313233def 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 = ""4243 def escape(s: str) -> str:44 return (45 s.replace('"', '""')46 .replace("'", "''")47 .replace("$", "\\$")48 .replace("`", "\\`")49 )5051 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 True636465def 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 True949596def 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 ' '}")103104 return True105106107def 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 False117118119def 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 False137138139def completion_init() -> None:140 global _click_patched141 if not _click_patched:142 testing = os.getenv("_TYPER_COMPLETE_TESTING")143144 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 result152153 if testing:154 click._bashcomplete.bashcomplete = testing_handle_shell_complete155 else:156 click._bashcomplete.bashcomplete = handle_shell_complete157 _click_patched = True
deleted:typer/_completion_click8.py-192 removed
1import os2import re3import sys4from typing import Any, Dict, List, Tuple56import click7import click.parser8import click.shell_completion910from ._completion_shared import (11 COMPLETION_SCRIPT_BASH,12 COMPLETION_SCRIPT_FISH,13 COMPLETION_SCRIPT_POWER_SHELL,14 COMPLETION_SCRIPT_ZSH,15 Shells,16)1718try:19 import shellingham20except ImportError: # pragma: nocover21 shellingham = None222324class BashComplete(click.shell_completion.BashComplete):25 name = Shells.bash.value26 source_template = COMPLETION_SCRIPT_BASH2728 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 }3435 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]3940 try:41 incomplete = cwords[cword]42 except IndexError:43 incomplete = ""4445 return args, incomplete4647 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}"5253 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)585960class ZshComplete(click.shell_completion.ZshComplete):61 name = Shells.zsh.value62 source_template = COMPLETION_SCRIPT_ZSH6364 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 }7071 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, incomplete8182 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 )9091 # 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)}"'9899 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"108109110class FishComplete(click.shell_completion.FishComplete):111 name = Shells.fish.value112 source_template = COMPLETION_SCRIPT_FISH113114 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 }120121 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, incomplete131132 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}"137138 # 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}"144145 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 cover161162163class PowerShellComplete(click.shell_completion.ShellComplete):164 name = Shells.powershell.value165 source_template = COMPLETION_SCRIPT_POWER_SHELL166167 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 }173174 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, incomplete180181 def format_completion(self, item: click.shell_completion.CompletionItem) -> str:182 return f"{item.value}:::{item.help or ' '}"183184185def 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)
modified:typer/_completion_shared.py+1 added-5 removed
1import os2import re3import subprocess4import sys4from enum import Enum5from pathlib import Path6from typing import Optional, Tuple7
4 unmodified lines
12except ImportError: # pragma: nocover13 shellingham = None141517from typing import Optional181916class Shells(str, Enum):17 bash = "bash"18 zsh = "zsh"19 fish = "fish"
63 unmodified lines
83 cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))84 script = _completion_scripts.get(shell)85 if script is None:86 click.echo(f"Shell {shell} not supported.", err=True)91 sys.exit(1)87 raise click.exceptions.Exit(1)88 return (89 script90 % dict(91 complete_func="_{}_completion".format(cf_name),
149 unmodified lines
modified:typer/completion.py+2 added-13 removed
2 unmodified lines
3from typing import Any, MutableMapping, Tuple45import click67from ._compat_utils import _get_click_major7from ._completion_classes import completion_init8from ._completion_shared import Shells, get_completion_script, install9from .models import ParamMeta10from .params import Option11from .utils import get_params_from_function
89 unmodified lines
101) -> Any:102 pass # pragma no cover103104105def completion_init() -> None:106 if _get_click_major() < 8:107 from ._completion_click7 import completion_init108109 completion_init()110 else:111 from ._completion_click8 import completion_init112113 completion_init()114115105# Re-implement Click's shell_complete to add error message with:106# Invalid completion instruction107# To use 7.x instruction style for compatibility108# And to add extra error messages, for compatibility with Typer in previous versions109# This is only called in new Command method, only used by Click 8.x+110def shell_complete(122 cli: click.BaseCommand,111 cli: click.Command,112 ctx_args: MutableMapping[str, Any],113 prog_name: str,114 complete_var: str,115 instruction: str,
34 unmodified lines
modified:typer/core.py+58 added-119 removed
3 unmodified lines
4import sys5from enum import Enum6from gettext import gettext as _7from typing import (8 TYPE_CHECKING,8 Any,9 Callable,10 Dict,11 List,
9 unmodified lines
21import click22import click.core23import click.formatting24import click.parser25import click.shell_completion26import click.types27import click.utils28from typer.completion import completion_init2830from ._compat_utils import _get_click_major3129if sys.version_info >= (3, 8):30 from typing import Literal31else:32 from typing_extensions import Literal
5 unmodified lines
3839except ImportError: # pragma: nocover40 rich = None # type: ignore4145if TYPE_CHECKING: # pragma: no cover46 if _get_click_major() == 7:47 import click.shell_completion4842MarkupMode = Literal["markdown", "rich", None]434452# TODO: when deprecating Click 7, remove this53def _typer_param_shell_complete(54 self: click.core.Parameter, ctx: click.Context, incomplete: str55) -> List["click.shell_completion.CompletionItem"]:56 if self._custom_shell_complete is not None:57 results = self._custom_shell_complete(ctx, self, incomplete)45# Copy from click.parser._split_opt46def _split_opt(opt: str) -> Tuple[str, str]:47 first = opt[:1]48 if first.isalnum():49 return "", opt50 if opt[1:2] == first:51 return opt[:2], opt[2:]52 return first, opt[1:]5359 if results and isinstance(results[0], str):60 from click.shell_completion import CompletionItem5462 results = [CompletionItem(c) for c in results]6364 return cast(List["click.shell_completion.CompletionItem"], results)6566 return self.type.shell_complete(ctx, self, incomplete)676855def _typer_param_setup_autocompletion_compat(56 self: click.Parameter,57 *,58 autocompletion: Optional[
51 unmodified lines
110 for d in default_value111 )112 elif isinstance(default_value, Enum):113 default_string = str(default_value.value)128 elif callable(default_value):114 elif inspect.isfunction(default_value):115 default_string = _("(dynamic)")116 elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts:117 # For boolean flags that have distinct True/False opts,118 # use the opt without prefix instead of the value.
2 unmodified lines
121 # (self.opts if self.default else self.secondary_opts)[0]122 # )[1]123 if obj.default:124 if obj.opts:139 default_string = click.parser.split_opt(obj.opts[0])[1]125 default_string = _split_opt(obj.opts[0])[1]126 else:127 default_string = str(default_value)128 else:143 default_string = click.parser.split_opt(obj.secondary_opts[0])[1]129 default_string = _split_opt(obj.secondary_opts[0])[1]130 # Typer override end131 elif (132 isinstance(obj, TyperOption)133 and obj.is_bool_flag
17 unmodified lines
151 resilient = ctx.resilient_parsing152 ctx.resilient_parsing = True153154 try:169 if _get_click_major() > 7:170 default_value = obj.get_default(ctx, call=False)155 default_value = obj.get_default(ctx, call=False)171 else:172 if inspect.isfunction(obj.default):173 default_value = _("(dynamic)")174 else:175 default_value = obj.default156 finally:157 ctx.resilient_parsing = resilient158 return default_value159
20 unmodified lines
180 else:181 args = list(args)182183 if prog_name is None:204 if _get_click_major() > 7:205 prog_name = click.utils._detect_program_name()184 prog_name = click.utils._detect_program_name()206 else:207 from click.utils import make_str185209 prog_name = make_str(210 os.path.basename(sys.argv[0] if sys.argv else __file__)211 )212186 # Process shell completion requests and exit early.214 if _get_click_major() > 7:215 self._main_shell_completion(extra, prog_name, complete_var)187 self._main_shell_completion(extra, prog_name, complete_var)216 else:217 completion_init()218 from click.core import _bashcomplete # type: ignore188220 _bashcomplete(self, prog_name, complete_var)221189 try:190 try:191 with self.make_context(prog_name, args, **extra) as ctx:192 rv = self.invoke(ctx)
88 unmodified lines
281 self.show_choices = show_choices282 self.show_envvar = show_envvar283 self.hidden = hidden284 self.rich_help_panel = rich_help_panel318 kwargs: Dict[str, Any] = {319 "param_decls": param_decls,320 "type": type,321 "required": required,322 "default": default,323 "callback": callback,324 "nargs": nargs,325 "metavar": metavar,326 "expose_value": expose_value,327 "is_eager": is_eager,328 "envvar": envvar,329 }330 if _get_click_major() > 7:331 kwargs["shell_complete"] = shell_complete332 else:333 kwargs["autocompletion"] = autocompletion334 super().__init__(**kwargs)335 if _get_click_major() > 7:336 _typer_param_setup_autocompletion_compat(337 self, autocompletion=autocompletion338 )285286 super().__init__(287 param_decls=param_decls,288 type=type,289 required=required,290 default=default,291 callback=callback,292 nargs=nargs,293 metavar=metavar,294 expose_value=expose_value,295 is_eager=is_eager,296 envvar=envvar,297 shell_complete=shell_complete,298 )299 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)300301 def _get_default_string(302 self,303 *,304 ctx: click.Context,
72 unmodified lines
377 if self.nargs != 1:378 var += "..."379 return var380420 def shell_complete(421 self, ctx: click.Context, incomplete: str422 ) -> List["click.shell_completion.CompletionItem"]:423 return _typer_param_shell_complete(self, ctx=ctx, incomplete=incomplete)381425382class TyperOption(click.core.Option):383 def __init__(384 self,385 *,
32 unmodified lines
418 show_envvar: bool = False,419 # Rich settings420 rich_help_panel: Union[str, None] = None,421 ):466 # TODO: when deprecating Click 7, remove custom kwargs with prompt_required467 # and call super().__init__() directly468 kwargs: Dict[str, Any] = {469 "param_decls": param_decls,470 "type": type,471 "required": required,472 "default": default,473 "callback": callback,474 "nargs": nargs,475 "metavar": metavar,476 "expose_value": expose_value,477 "is_eager": is_eager,478 "envvar": envvar,479 "show_default": show_default,480 "prompt": prompt,481 "confirmation_prompt": confirmation_prompt,482 "hide_input": hide_input,483 "is_flag": is_flag,484 "flag_value": flag_value,485 "multiple": multiple,486 "count": count,487 "allow_from_autoenv": allow_from_autoenv,488 "help": help,489 "hidden": hidden,490 "show_choices": show_choices,491 "show_envvar": show_envvar,492 }493 if _get_click_major() > 7:494 kwargs["prompt_required"] = prompt_required495 kwargs["shell_complete"] = shell_complete496 else:497 kwargs["autocompletion"] = autocompletion498 super().__init__(**kwargs)499 if _get_click_major() > 7:500 _typer_param_setup_autocompletion_compat(501 self, autocompletion=autocompletion502 )422 super().__init__(423 param_decls=param_decls,424 type=type,425 required=required,426 default=default,427 callback=callback,428 nargs=nargs,429 metavar=metavar,430 expose_value=expose_value,431 is_eager=is_eager,432 envvar=envvar,433 show_default=show_default,434 prompt=prompt,435 confirmation_prompt=confirmation_prompt,436 hide_input=hide_input,437 is_flag=is_flag,438 flag_value=flag_value,439 multiple=multiple,440 count=count,441 allow_from_autoenv=allow_from_autoenv,442 help=help,443 hidden=hidden,444 show_choices=show_choices,445 show_envvar=show_envvar,446 prompt_required=prompt_required,447 shell_complete=shell_complete,448 )449 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)450 self.rich_help_panel = rich_help_panel451452 def _get_default_string(453 self,
14 unmodified lines
468 ) -> Optional[Union[Any, Callable[[], Any]]]:469 return _extract_default_help_str(self, ctx=ctx)470471 def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:525 # Click 7.x was not breaking this use case, so in that case, re-use its logic526 if _get_click_major() < 8:527 return super().get_help_record(ctx)472 # Duplicate all of Click's logic only to modify a single line, to allow boolean473 # flags with only names for False values as it's currently supported by Typer474 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false475 if self.hidden:
76 unmodified lines
552 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"553554 return ("; " if any_prefix_is_slash else " / ").join(rv), help555612 def shell_complete(613 self, ctx: click.Context, incomplete: str614 ) -> List["click.shell_completion.CompletionItem"]:615 return _typer_param_shell_complete(self, ctx=ctx, incomplete=incomplete)556617557def _typer_format_options(558 self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter559) -> None:560 args = []
179 unmodified lines
modified:typer/models.py+1 added-5 removed
12 unmodified lines
13 Union,14)1516import click17import click.shell_completion1818from ._compat_utils import _get_click_major1919if TYPE_CHECKING: # pragma: no cover21 if _get_click_major() > 7:22 import click.shell_completion2320 from .core import TyperCommand, TyperGroup21 from .main import Typer2223
496 unmodified lines
modified:typer/rich_utils.py+10 added-14 removed
381 unmodified lines
382 metavar.append(metavar_str)383384 # Range - from385 # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501386 try:387 # skip count with default range type388 if (389 isinstance(param.type, click.types._NumberRangeBase)390 and isinstance(param, click.Option)391 and not (param.count and param.type.min == 0 and param.type.max is None)392 ):393 range_str = param.type._describe_range()394 if range_str:395 metavar.append(RANGE_STRING.format(range_str))386 # skip count with default range type387 if (388 isinstance(param.type, click.types._NumberRangeBase)389 and isinstance(param, click.Option)390 and not (param.count and param.type.min == 0 and param.type.max is None)391 ):392 range_str = param.type._describe_range()393 if range_str:394 metavar.append(RANGE_STRING.format(range_str))396 except AttributeError: # pragma: no cover397 # click.types._NumberRangeBase is only in Click 8x onwards398 pass395396 # Required asterisk397 required: Union[str, Text] = ""398 if param.required:
217 unmodified lines
616 markup_mode=markup_mode,617 console=console,618 )619624 if isinstance(obj, click.MultiCommand):620 if isinstance(obj, click.Group):621 panel_to_commands: DefaultDict[str, List[click.Command]] = defaultdict(list)622 for command_name in obj.list_commands(ctx):623 command = obj.get_command(ctx, command_name)624 if command and not command.hidden:
65 unmodified lines
modified:pyproject.toml+1 added-1 removed
27 unmodified lines
28 "Programming Language :: Python :: 3.11",29 "License :: OSI Approved :: MIT License"30 ]31requires = [32 "click >= 7.1.1, <9.0.0",32 "click >= 8.0.0",33 "typing-extensions >= 3.7.4.3",34]35description-file = "README.md"36requires-python = ">=3.7"
59 unmodified lines