🔥 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
Provenance
- Commit
5bea9cf- Tree
95e6738- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
d6921fb
54 files changed+386 added−812 removed
modified:.github/workflows/test.yml+2 added-9 removed
11 unmodified lines12131415161718161718194 unmodified lines2425262731323328352930313233414234353637383947 unmodified lines11 unmodified lines runs-on: ubuntu-20.04 strategy: matrix: python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"] click-version: - click-7 - click-8 fail-fast: false
steps: - uses: actions/checkout@v34 unmodified lines - name: Install Flit run: pip install flit - name: Install Dependencies run: python -m flit install --symlink - name: Install Click 7 if: matrix.click-version == 'click-7' run: pip install "click<8.0.0" - name: Lint if: ${{ matrix.click-version == 'click-8' }} run: bash scripts/lint.sh - run: mkdir coverage - name: Test run: bash scripts/test.sh env: COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.click-version }} CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.click-version }} COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }} CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }} - name: Store coverage files uses: actions/upload-artifact@v3 with: name: coverage47 unmodified linesmodified:docs/tutorial/options/callback-and-context.md+9 added-9 removed
6 unmodified lines7 For example, you could do some validation before the rest of the code is executed.8 9 === "Python 3.7+"10 11- ```Python hl_lines="5-8 11"11+ ```Python hl_lines="7-10 13"12 {!> ../docs_src/options/callback/tutorial001_an.py!}13 ```14 15 === "Python 3.7+ non-Annotated"16 17 !!! tip18 Prefer to use the `Annotated` version if possible.19 20- ```Python hl_lines="4-7 10"20+ ```Python hl_lines="6-9 12"21 {!> ../docs_src/options/callback/tutorial001.py!}22 ```23 24 Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.81 unmodified lines106 Let's say that when the callback is running, we want to show a message saying that it's validating the name:107 108 === "Python 3.7+"109 110- ```Python hl_lines="6"110+ ```Python hl_lines="8"111 {!> ../docs_src/options/callback/tutorial002_an.py!}112 ```113 114 === "Python 3.7+ non-Annotated"115 116 !!! tip117 Prefer to use the `Annotated` version if possible.118 119- ```Python hl_lines="5"119+ ```Python hl_lines="7"120 {!> ../docs_src/options/callback/tutorial002.py!}121 ```122 123 And 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 lines154 The "context" has some additional data about the current execution of your program:155 156 === "Python 3.7+"157 158- ```Python hl_lines="5-7"158+ ```Python hl_lines="7-9"159 {!> ../docs_src/options/callback/tutorial003_an.py!}160 ```161 162 === "Python 3.7+ non-Annotated"163 164 !!! tip165 Prefer to use the `Annotated` version if possible.166 167- ```Python hl_lines="4-6"167+ ```Python hl_lines="6-8"168 {!> ../docs_src/options/callback/tutorial003.py!}169 ```170 171 The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.172 173 But it will be `False` when calling the program normally. So you can continue the execution of your previous code.174 175-That's all is needed to fix completion 🚀175+That's all is needed to fix completion. 🚀176 177 Check it:178 179 <div class="termy">19 unmodified lines199 The 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.200 201 === "Python 3.7+"202 203- ```Python hl_lines="5 8"203+ ```Python hl_lines="7 10"204 {!> ../docs_src/options/callback/tutorial004_an.py!}205 ```206 207 === "Python 3.7+ non-Annotated"208 209 !!! tip210 Prefer to use the `Annotated` version if possible.211 212- ```Python hl_lines="4 7"212+ ```Python hl_lines="6 9"213 {!> ../docs_src/options/callback/tutorial004.py!}214 ```215 216 It's probably not very common, but you could do it if you need it.45 unmodified linesmodified:docs_src/options/callback/tutorial001_an.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 from typing_extensions import Annotated5 6 2 unmodified lines9 raise typer.BadParameter("Only Camila is allowed")10 return value11 12 11-def main(name: Annotated[str, typer.Option(callback=name_callback)]):13+def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):14 print(f"Hello {name}")15 16 17 if __name__ == "__main__":1 unmodified linemodified:docs_src/options/callback/tutorial001.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 5 6 def name_callback(value: str):1 unmodified line8 raise typer.BadParameter("Only Camila is allowed")9 return value10 11 10-def main(name: str = typer.Option(..., callback=name_callback)):12+def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):13 print(f"Hello {name}")14 15 16 if __name__ == "__main__":1 unmodified linemodified:docs_src/options/callback/tutorial002_an.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 from typing_extensions import Annotated5 6 3 unmodified lines10 raise typer.BadParameter("Only Camila is allowed")11 return value12 13 12-def main(name: Annotated[str, typer.Option(callback=name_callback)]):14+def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):15 print(f"Hello {name}")16 17 18 if __name__ == "__main__":1 unmodified linemodified:docs_src/options/callback/tutorial002.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 5 6 def name_callback(value: str):2 unmodified lines9 raise typer.BadParameter("Only Camila is allowed")10 return value11 12 11-def main(name: str = typer.Option(..., callback=name_callback)):13+def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):14 print(f"Hello {name}")15 16 17 if __name__ == "__main__":1 unmodified linemodified:docs_src/options/callback/tutorial003_an.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 from typing_extensions import Annotated5 6 5 unmodified lines12 raise typer.BadParameter("Only Camila is allowed")13 return value14 15 14-def main(name: Annotated[str, typer.Option(callback=name_callback)]):16+def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):17 print(f"Hello {name}")18 19 20 if __name__ == "__main__":1 unmodified linemodified:docs_src/options/callback/tutorial003.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 5 6 def name_callback(ctx: typer.Context, value: str):4 unmodified lines11 raise typer.BadParameter("Only Camila is allowed")12 return value13 14 13-def main(name: str = typer.Option(..., callback=name_callback)):15+def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):16 print(f"Hello {name}")17 18 19 if __name__ == "__main__":1 unmodified linemodified:docs_src/options/callback/tutorial004_an.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 from typing_extensions import Annotated5 6 5 unmodified lines12 raise typer.BadParameter("Only Camila is allowed")13 return value14 15 14-def main(name: Annotated[str, typer.Option(callback=name_callback)]):16+def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):17 print(f"Hello {name}")18 19 20 if __name__ == "__main__":1 unmodified linemodified:docs_src/options/callback/tutorial004.py+3 added-1 removed
1+from typing import Optional2+3 import typer4 5 6 def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):4 unmodified lines11 raise typer.BadParameter("Only Camila is allowed")12 return value13 14 13-def main(name: str = typer.Option(..., callback=name_callback)):15+def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):16 print(f"Hello {name}")17 18 19 if __name__ == "__main__":1 unmodified linemodified:tests/test_compat/test_option_get_help.py+1 added-2 removed
50 unmodified lines51 "_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.stdoutmodified:tests/test_completion/test_completion_install.py+1 added-5 removed
25 unmodified lines26 "_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- )31 32 33 def test_completion_install_bash():34 bash_completion_path: Path = Path.home() / ".bashrc"144 unmodified linesmodified:tests/test_completion/test_completion_show.py+18 added-5 removed
1 import os2 import subprocess3 import sys4+from unittest import mock5 6+import shellingham7+import typer8+from typer.testing import CliRunner9+10 from docs_src.commands.index import tutorial001 as mod11 12+runner = CliRunner()13+app = typer.Typer()14+app.command()(mod.main)15 16+17 def 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 lines25 "_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- )30 31 32 def test_completion_show_bash():33 result = subprocess.run(116 unmodified lines150 assert (151 "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"152 in result.stdout153 )154+155+156+def 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.stdoutmodified:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+1 added-5 removed
61 unmodified lines62 63 def 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- )67 68 69 def test_script():70 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_commands/test_help/test_tutorial001_an.py+4 added-20 removed
67 unmodified lines68 69 def 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.output74 75 76 def 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.output81 82 83 def 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.output88 89 90 def 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.output95 96 97 def test_init():13 unmodified linesmodified:tests/test_tutorial/test_commands/test_help/test_tutorial001.py+4 added-20 removed
67 unmodified lines68 69 def 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.output74 75 76 def 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.output81 82 83 def 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.output88 89 90 def 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.output95 96 97 def test_init():13 unmodified linesmodified:tests/test_tutorial/test_commands/test_options/test_tutorial001_an.py+5 added-25 removed
27 unmodified lines28 29 def 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.output34 35 36 def 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.output41 42 43 def 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.output48 49 50 def 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.output55 56 57 def 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.output62 63 64 def test_init():13 unmodified linesmodified:tests/test_tutorial/test_commands/test_options/test_tutorial001.py+5 added-25 removed
27 unmodified lines28 29 def 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.output34 35 36 def 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.output41 42 43 def 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.output48 49 50 def 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.output55 56 57 def 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.output62 63 64 def test_init():13 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002_an.py+1 added-6 removed
30 unmodified lines31 32 def 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.stdout36 37- assert (38- "Argument 'names' takes 3 values" in result.stdout39- or "argument names takes 3 values" in result.stdout40- )37 42-38 def test_valid_args():39 result = runner.invoke(app, ["Draco", "Hagrid", "Dobby"])40 assert result.exit_code == 041 assert "Hello Draco" in result.stdout12 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002.py+1 added-6 removed
28 unmodified lines29 30 def 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.stdout34 35- assert (36- "Argument 'names' takes 3 values" in result.stdout37- or "argument names takes 3 values" in result.stdout38- )35 40-36 def test_valid_args():37 result = runner.invoke(app, ["Draco", "Hagrid", "Dobby"])38 assert result.exit_code == 039 assert "Hello Draco" in result.stdout12 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001_an.py+1 added-6 removed
33 unmodified lines34 35 def 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.output39 40- assert (41- "Option '--user' requires 3 arguments" in result.output42- or "--user option requires 3 arguments" in result.output43- )40 45-41 def test_script():42 result = subprocess.run(43 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001.py+1 added-6 removed
33 unmodified lines34 35 def 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.output39 40- assert (41- "Option '--user' requires 3 arguments" in result.output42- or "--user option requires 3 arguments" in result.output43- )40 45-41 def test_script():42 result = subprocess.run(43 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_options/test_name/test_tutorial001_an.py+1 added-5 removed
27 unmodified lines28 29 def 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- )33 34 35 def test_script():36 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_options/test_name/test_tutorial001.py+1 added-5 removed
27 unmodified lines28 29 def 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- )33 34 35 def test_script():36 result = subprocess.run(6 unmodified linesmodified:tests/test_tutorial/test_options/test_prompt/test_tutorial003_an.py+1 added-6 removed
21 unmodified lines22 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 option27-28- 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.output28 29 30 def test_option():22 unmodified linesmodified:tests/test_tutorial/test_options/test_prompt/test_tutorial003.py+1 added-6 removed
21 unmodified lines22 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 option27-28- 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.output28 29 30 def test_option():22 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial008_an.py+1 added-2 removed
23 unmodified lines24 )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.stderr29 30 31 def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])13 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial008.py+1 added-2 removed
23 unmodified lines24 )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.stderr29 30 31 def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])13 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial009_an.py+1 added-2 removed
23 unmodified lines24 )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.stderr29 30 31 def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])13 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial009.py+1 added-2 removed
23 unmodified lines24 )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.stderr29 30 31 def test_1():32 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])13 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001_an.py+1 added-6 removed
32 unmodified lines33 34 def 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.output38 39- assert (40- "No such option: --no-force" in result.output41- or "no such option: --no-force" in result.output42- )39 44-40 def test_script():41 result = subprocess.run(42 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001.py+1 added-6 removed
32 unmodified lines33 34 def 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.output38 39- assert (40- "No such option: --no-force" in result.output41- or "no such option: --no-force" in result.output42- )39 44-40 def test_script():41 result = subprocess.run(42 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002_an.py+1 added-6 removed
51 unmodified lines52 53 def 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.output57 58- assert (59- "No such option: --no-accept" in result.output60- or "no such option: --no-accept" in result.output61- )58 63-59 def test_script():60 result = subprocess.run(61 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],62 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002.py+1 added-6 removed
51 unmodified lines52 53 def 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.output57 58- assert (59- "No such option: --no-accept" in result.output60- or "no such option: --no-accept" in result.output61- )58 63-59 def test_script():60 result = subprocess.run(61 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],62 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+1 added-5 removed
30 unmodified lines31 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 linesmodified:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial001.py+2 added-14 removed
27 unmodified lines28 29 def test_invalid_case():30 result = runner.invoke(app, ["--network", "CONV"])31 assert result.exit_code != 032- # TODO: when deprecating Click 7, remove second option33-34- 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.output36 37 38 def test_invalid_other():39 result = runner.invoke(app, ["--network", "capsule"])40 assert result.exit_code != 047- # TODO: when deprecating Click 7, remove second option48-49- 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 linesmodified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+1 added-6 removed
33 unmodified lines34 35 def 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.output39 40- 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- )40 45-41 def test_script():42 result = subprocess.run(43 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,4 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001_an.py+2 added-18 removed
43 unmodified lines44 45 def 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 )51 52 53 def 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.output57 64- 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- )58 70-59 def 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 option75-62 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 )66 67 68 def test_negative_score():15 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+2 added-18 removed
43 unmodified lines44 45 def 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 )51 52 53 def 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.output57 64- 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- )58 70-59 def 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 option75-62 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 )66 67 68 def test_negative_score():15 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002_an.py-4 removed
13 unmodified lines14 15 def test_invalid_id():16 result = runner.invoke(app, ["1002"])17 assert result.exit_code != 018- # TODO: when deprecating Click 7, remove second option19-18 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 )21 22 23 def test_clamped():15 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002.py-4 removed
13 unmodified lines14 15 def test_invalid_id():16 result = runner.invoke(app, ["1002"])17 assert result.exit_code != 018- # TODO: when deprecating Click 7, remove second option19-18 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 )21 22 23 def test_clamped():15 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py-4 removed
20 unmodified lines21 22 def test_invalid_uuid():23 result = runner.invoke(app, ["7479706572-72756c6573"])24 assert result.exit_code != 025- # TODO: when deprecating Click 7, remove second option26-25 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 )29 30 31 def test_script():7 unmodified linesmodified:tests/test_tutorial/test_using_click/test_tutorial003.py+1 added-2 removed
8 unmodified lines9 10 11 def 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.stdout14 15 16 def test_help():17 result = runner.invoke(mod.typer_click_object, ["--help"])24 unmodified linesmodified:tests/test_others.py+22 added-15 removed
8 unmodified lines9 import pytest10 import shellingham11 import typer12 import typer.completion13+from typer.core import _split_opt14 from typer.main import solve_typer_info_defaults, solve_typer_info_help15 from typer.models import ParameterInfo, TyperInfo16 from typer.testing import CliRunner17 137 unmodified lines155 "_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 lines184 "_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 lines225 print(f"arg4: {type(arg4)} {arg4}")226 print(f"arg5: {type(arg5)} {arg5}")227 228 result = runner.invoke(app, ["Hello", "2", "invalid"])236- # TODO: when deprecating Click 7, remove second option229 238- 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.stdout8 unmodified lines243 pass # pragma: nocover244 245 result = runner.invoke(app, ["main", "-h"])246 assert "Show this message and exit." in result.stdout247+248+249+def test_split_opt():250+ prefix, opt = _split_opt("--verbose")251+ assert prefix == "--"252+ assert opt == "verbose"253+254+ prefix, opt = _split_opt("//verbose")255+ assert prefix == "//"256+ assert opt == "verbose"257+258+ prefix, opt = _split_opt("-verbose")259+ assert prefix == "-"260+ assert opt == "verbose"261+262+ prefix, opt = _split_opt("verbose")263+ assert prefix == ""264+ assert opt == "verbose"deleted:typer/_compat_utils.py-5 removed
1-import click2-3-4-def _get_click_major() -> int:5- return int(click.__version__.split(".")[0])added:typer/_completion_classes.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)deleted:typer/_completion_click7.py-157 removed
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 = Truedeleted:typer/_completion_click8.py-192 removed
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)modified:typer/_completion_shared.py+1 added-5 removed
1 import os2 import re3 import subprocess4-import sys4 from enum import Enum5 from pathlib import Path6 from typing import Optional, Tuple7 4 unmodified lines12 except ImportError: # pragma: nocover13 shellingham = None14 15 17-from typing import Optional18-19-16 class Shells(str, Enum):17 bash = "bash"18 zsh = "zsh"19 fish = "fish"63 unmodified lines83 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 linesmodified:typer/completion.py+2 added-13 removed
2 unmodified lines3 from typing import Any, MutableMapping, Tuple4 5 import click6 7-from ._compat_utils import _get_click_major7+from ._completion_classes import completion_init8 from ._completion_shared import Shells, get_completion_script, install9 from .models import ParamMeta10 from .params import Option11 from .utils import get_params_from_function89 unmodified lines101 ) -> Any:102 pass # pragma no cover103 104 105-def completion_init() -> None:106- if _get_click_major() < 8:107- from ._completion_click7 import completion_init108-109- completion_init()110- else:111- from ._completion_click8 import completion_init112-113- completion_init()114-115-105 # 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+110 def 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 linesmodified:typer/core.py+58 added-119 removed
3 unmodified lines4 import sys5 from enum import Enum6 from gettext import gettext as _7 from typing import (8- TYPE_CHECKING,8 Any,9 Callable,10 Dict,11 List,9 unmodified lines21 import click22 import click.core23 import click.formatting24 import click.parser25+import click.shell_completion26 import click.types27 import click.utils28-from typer.completion import completion_init28 30-from ._compat_utils import _get_click_major31-29 if sys.version_info >= (3, 8):30 from typing import Literal31 else:32 from typing_extensions import Literal5 unmodified lines38 39 except ImportError: # pragma: nocover40 rich = None # type: ignore41 45-if TYPE_CHECKING: # pragma: no cover46- if _get_click_major() == 7:47- import click.shell_completion48-42 MarkupMode = Literal["markdown", "rich", None]43 44 52-# TODO: when deprecating Click 7, remove this53-def _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_opt46+def _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:]53 59- if results and isinstance(results[0], str):60- from click.shell_completion import CompletionItem54 62- results = [CompletionItem(c) for c in results]63-64- return cast(List["click.shell_completion.CompletionItem"], results)65-66- return self.type.shell_complete(ctx, self, incomplete)67-68-55 def _typer_param_setup_autocompletion_compat(56 self: click.Parameter,57 *,58 autocompletion: Optional[51 unmodified lines110 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 lines121 # (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_flag17 unmodified lines151 resilient = ctx.resilient_parsing152 ctx.resilient_parsing = True153 154 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 lines180 else:181 args = list(args)182 183 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_str185 209- prog_name = make_str(210- os.path.basename(sys.argv[0] if sys.argv else __file__)211- )212-186 # 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: ignore188 220- _bashcomplete(self, prog_name, complete_var)221-189 try:190 try:191 with self.make_context(prog_name, args, **extra) as ctx:192 rv = self.invoke(ctx)88 unmodified lines281 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- )285 286+ 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)300+301 def _get_default_string(302 self,303 *,304 ctx: click.Context,72 unmodified lines377 if self.nargs != 1:378 var += "..."379 return var380 420- 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)381 425-382 class TyperOption(click.core.Option):383 def __init__(384 self,385 *,32 unmodified lines418 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_panel451 452 def _get_default_string(453 self,14 unmodified lines468 ) -> Optional[Union[Any, Callable[[], Any]]]:469 return _extract_default_help_str(self, ctx=ctx)470 471 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 lines552 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"553 554 return ("; " if any_prefix_is_slash else " / ").join(rv), help555 612- 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)556 617-557 def _typer_format_options(558 self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter559 ) -> None:560 args = []179 unmodified linesmodified:typer/models.py+1 added-5 removed
12 unmodified lines13 Union,14 )15 16 import click17+import click.shell_completion18 18-from ._compat_utils import _get_click_major19-19 if TYPE_CHECKING: # pragma: no cover21- if _get_click_major() > 7:22- import click.shell_completion23-20 from .core import TyperCommand, TyperGroup21 from .main import Typer22 23 496 unmodified linesmodified:typer/rich_utils.py+10 added-14 removed
381 unmodified lines382 metavar.append(metavar_str)383 384 # 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- pass395 396 # Required asterisk397 required: Union[str, Text] = ""398 if param.required:217 unmodified lines616 markup_mode=markup_mode,617 console=console,618 )619 624- 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 linesmodified:pyproject.toml+1 added-1 removed
27 unmodified lines28 "Programming Language :: Python :: 3.11",29 "License :: OSI Approved :: MIT License"30 ]31 requires = [32- "click >= 7.1.1, <9.0.0",32+ "click >= 8.0.0",33 "typing-extensions >= 3.7.4.3",34 ]35 description-file = "README.md"36 requires-python = ">=3.7"59 unmodified lines