➖ Vendor Click and streamline Typer's functionality and code base (#1774)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sofie Van Landeghem · committed by GitHub · parent 2d7a5be · Browse files · 74 files·+10174 added−355 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-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
- Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Diff stats
74 files+10174 added−355 removed
- tests:+3222 added−47 removed
- other:+6952 added−308 removed
Provenance
- Commit
1829d73- Tree
9bca27a- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
2d7a5be
74 files changed+10174 added−355 removed
added:docs/tutorial/click.md+69 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# Vendored Click
/// note
This is historical information, if you are just learning Typer from scratch, you don't need to read it. ☕️
///
Typer used to depend on [Click](https://click.palletsprojects.com/), a popular tool for building CLIs in Python, as an external dependency.
Since version 0.26.0, Typer has vendored Click (included Click's source code internally, instead of installing it as a third party package) and has unified the code interactions between Typer and the embedded Click source code for easier maintainability in the future.
Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.
## Breaking Changes
Typer used to support extracting the internal Click app from a Typer app to use and modify it with any Click functionality. For example, to add Click-specific plug-ins.
The same way, it supported adding Click-specific types to override the default Typer ones.
Using Click directly was an edge case feature that was not commonly used, and it is no longer supported. If your app depended specifically on this, you will need to either migrate it to use plain Typer, or migrate it to use Click directly instead of Typer.
## Codebase Compatibility Improvements
Because Typer used to depend on Click, any new features or changes in newer Click versions could break compatibility in Typer.
The Click team has always been very helpful and supportive with Typer. But still, this dependency interaction would cause extra effort and burden for both the Typer team and the Click team.
Now that Typer continues evolving, starting from a fixed copy of Click's source code, any changes in Click's codebase will not affect Typer.
The Typer team will not need to make sure there are workarounds for changes in new versions of Click, and the Click team will not need to consider additional edge cases caused by Typer.
## Compatibility Improvements for Your Apps
The fact that Typer depended on Click caused an additional ongoing issue that could happen from time to time to user projects.
Many packages come with a CLI, some of them could use Click, some could use Typer.
Some of these packages could require a recent version of Click that Typer still didn't support, but as all these package dependencies would belong to the same project, there would be conflicts.
In these cases, the package that depended on the newer version of Click would require installing it, but the other package that used Typer would break. Or if there were version pins, some combinations of packages would not be installable together.
Across different versions of Click through time, there were many changes needed in Typer to make it all compatible with multiple versions of Click at the same time.
Now that Typer and Click are decoupled, a package could depend on a newer version of Click, while another package that uses Typer would continue working as normally, as that Typer version would bundle anything necessary from Click's source code to work.
## Future Improvements
Both the Click team and the Typer team have future improvements planned, not having to coordinate with each other for compatibility will simplify the work of both teams.
In some cases feature ideas could overlap, and could have caused incompatibilities. Now this won't be a problem as each team can focus on each project independently.
## Typer Changes
After vendoring Click, Typer will reduce, simplify and refactor parts of the vendored Click code that are not necessary for Typer, or that could be done in a different way to facilitate future improvements in Typer.
Then Typer will gradually introduce new features and improvements that have been planned for a while but were too difficult to implement before this.
## User Focus
These decisions are all carefully planned and based on real world use cases extracted from the official Typer developer survey, including the tradeoff between the potential breaking changes for some use cases and the planned future features and improvements that will be enabled.
## Thank You Click
Click has been the foundation building block of Typer and most CLI's in Python (through Typer or directly with Click).
We wouldn't be here without Click, and we are very grateful for all the work that the Click team has done.
Thank you Click! 🙇modified:docs/tutorial/install.md+1 added-1 removed
7 unmodified lines891011121213141516177 unmodified lines
```console$ pip install typer---> 100%Successfully installed typer click shellingham richSuccessfully installed typer shellingham rich```
</div>
By default, `typer` comes with `rich` and `shellingham`.modified:docs/tutorial/package.md+2 added-4 removed
58 unmodified lines59 // It creates a virtual environment for your project60 Using CPython 3.14.0 interpreter at: /location/of/python/61 Creating virtual environment at: .venv62 63-Resolved 10 packages in 21ms63+Resolved 9 packages in 21ms64 Built rick-portal-gun @ file:/home/rick-portal-gun65 Prepared 1 package in 19ms66-Installed 10 packages in 34ms67- + click==8.3.166+Installed 9 packages in 34ms67 + colorama==0.4.668 + markdown-it-py==4.0.069 + mdurl==0.1.270 + pygments==2.19.2495 unmodified lines566 Collecting rick-portal-gun567 Downloading rick_portal_gun-0.1.0-py3-none-any.whl.metadata (435 bytes)568 Requirement already satisfied: typer<0.13.0,>=0.12.3 in ./.local/lib/python3.10/site-packages (from rick-portal-gun==0.1.0) (0.12.3)569 Requirement already satisfied: typing-extensions>=3.7.4.3 in ./.local/lib/python3.10/site-packages (from typer<0.13.0,>=0.12.3->rick-portal-gun==0.1.0) (4.11.0)571-Requirement already satisfied: click>=8.0.0 in ./.local/lib/python3.10/site-packages (from typer<0.13.0,>=0.12.3->rick-portal-gun==0.1.0) (8.1.7)570 Requirement already satisfied: shellingham>=1.3.0 in ./.local/lib/python3.10/site-packages (from typer<0.13.0,>=0.12.3->rick-portal-gun==0.1.0) (1.5.4)571 Requirement already satisfied: rich>=10.11.0 in ./.local/lib/python3.10/site-packages (from typer<0.13.0,>=0.12.3->rick-portal-gun==0.1.0) (13.7.1)572 Requirement already satisfied: pygments<3.0.0,>=2.13.0 in ./.local/lib/python3.10/site-packages (from rich>=10.11.0->typer<0.13.0,>=0.12.3->rick-portal-gun==0.1.0) (2.17.2)573 Requirement already satisfied: markdown-it-py>=2.2.0 in ./.local/lib/python3.10/site-packages (from rich>=10.11.0->typer<0.13.0,>=0.12.3->rick-portal-gun==0.1.0) (3.0.0)97 unmodified linesmodified:docs/tutorial/printing.md+1 added-1 removed
194 unmodified lines195 And for the cases where you want to display data more beautifully, or more advanced content, you should use **Rich** instead.196 197 ### Why `typer.echo`198 199-`typer.echo()` (which is actually just `click.echo()`) applies some checks to try and convert binary data to strings, and other similar things.199+`typer.echo()` applies some checks to try and convert binary data to strings, and other similar things.200 201 But in most of the cases you wouldn't need it, as in modern Python strings (`str`) already support and use Unicode, and you would rarely deal with pure `bytes` that you want to print on the screen.202 203 If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.69 unmodified linesmodified:docs/alternatives.md+3 added-3 removed
68 unmodified lines6970717273737475757677777879808122 unmodified lines68 unmodified linesIt uses decorators on top of functions to modify the actual value of those functions, converting them to instances of a specific class. This is a clever trick, but code editors can't provide great support for autocompletion that way.
It was built with some great ideas and design using the features available in the language at the time (Python 2.x).
/// tip | **Typer** uses it for/// tip | **Typer** builds on top of Click functionality
Everything. 🚀It has <abbr title="included Click's source code internally, instead of installing it as a third party package">vendored</abbr> Click version 8.3.1 and adds a layer on top of it.
**Typer** mainly adds a layer on top of Click, making the code simpler and easier to use, with autocompletion everywhere, etc, but providing all the powerful features of Click underneath.Typer aims to make the code simpler and easier to use, with autocompletion everywhere, etc, while still providing many of the powerful features of Click underneath.
As someone pointed out: <em>["Nice to see it is built on Click but adds the type stuff. Me gusta!"](https://twitter.com/fishnets88/status/1210126833745838080)</em>
///22 unmodified linesmodified:docs/features.md-8 removed
61 unmodified lines62 * `--show-completion`: Show completion for the current shell, to copy it or customize the installation.63 64 ///65 66-/// tip67-68-**Typer**'s completion is implemented internally, it uses ideas and components from Click and ideas from `click-completion`, but it doesn't use `click-completion` and re-implements some of the relevant parts of Click.69-70-Then it extends those ideas with features and bug fixes. For example, **Typer** programs also support modern versions of PowerShell (e.g. in Windows 10) among all the other shells.71-72-///73-66 ## Tested67 68 * 100% <abbr title="The amount of code that is automatically tested">test coverage</abbr>.69 * 100% <abbr title="Python type annotations, with this your editor and external tools can give you better support">type annotated</abbr> code base.1 unmodified linemodified:docs/index.md+11 added-2 removed
358 unmodified lines359 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.360 361 ## Dependencies362 363-**Typer** stands on the shoulders of giants. It has three required dependencies:363+**Typer** requires only a few dependencies (most are tiny):364 365-* [Click](https://click.palletsprojects.com/): a popular tool for building CLIs in Python. Typer is based on it.365 * [`rich`](https://rich.readthedocs.io/en/stable/index.html): to show nicely formatted errors automatically.366 * [`shellingham`](https://github.com/sarugaku/shellingham): to automatically detect the current shell when installing completion.367+* [`annotated-doc`](https://github.com/fastapi/annotated-doc): to generate documentation from Python type annotations.368+* [`colorama`](https://github.com/tartley/colorama) (only on Windows): for producing colored terminal text on Windows.369 370+### Click code371+372+Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.373+374+Since version 0.26.0, Typer has vendored Click (included Click's source code internally, instead of installing it as a third party package) and has unified the code interactions between Typer and the embedded Click source code for easier maintainability in the future.375+376+Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.377+378 ### `typer-slim`379 380 There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.381 7 unmodified linesmodified:tests/assets/completion_argument.py+2 added-2 removed
1-import click1 import typer2+from typer import _click3 4 app = typer.Typer()5 6 7-def shell_complete(ctx: click.Context, param: click.Parameter, incomplete: str):7+def shell_complete(ctx: _click.Context, param: _click.Parameter, incomplete: str):8 typer.echo(f"ctx: {ctx.info_name}", err=True)9 typer.echo(f"arg is: {param.name}", err=True)10 typer.echo(f"incomplete is: {incomplete}", err=True)11 return ["Emma"]11 unmodified linesmodified:tests/test_cli/test_help.py+121 added
1 import subprocess2 import sys3 4+import typer5+from typer.testing import CliRunner6 7+runner = CliRunner()8+9+10 def test_script_help():11 result = subprocess.run(12 [13 sys.executable,26 unmodified lines40 capture_output=True,41 encoding="utf-8",42 )43 assert "Could not import as Python file" in result.stderr44+45+46+def test_short_help() -> None:47+ app = typer.Typer(48+ rich_markup_mode=None,49+ context_settings={"max_content_width": 50},50+ )51+52+ @app.command(help=" \n\t ")53+ def empty() -> None:54+ pass # pragma: no cover55+56+ @app.command(help="\b first sentence.")57+ def marker() -> None:58+ pass # pragma: no cover59+60+ # Forcing truncation61+ @app.command(help=f"{'x' * 30} {'y' * 5} z trailing")62+ def long() -> None:63+ pass # pragma: no cover64+65+ result = runner.invoke(app, ["--help"], terminal_width=50)66+ assert result.exit_code == 067+ assert "empty" in result.output68+ assert "marker" in result.output69+ assert "long" in result.output70+ assert "first sentence." in result.output71+ assert f"{'x' * 30}..." in result.output72+73+74+def test_help_wrapping() -> None:75+ app = typer.Typer(76+ rich_markup_mode=None,77+ context_settings={"max_content_width": 50},78+ )79+80+ @app.command(81+ help=(82+ "Wrapped paragraph has enough words to wrap in help output.\n"83+ "\n"84+ "\n"85+ "\b\n"86+ "RAW-LINE-ONE stays on one line even with many many many words.\n"87+ "RAW-LINE-TWO keeps original formatting.\n"88+ "\n"89+ "Final paragraph wraps normally as well."90+ )91+ )92+ def cmd() -> None:93+ pass # pragma: no cover94+95+ result = runner.invoke(app, ["cmd", "--help"], terminal_width=50)96+ assert result.exit_code == 097+ assert "Wrapped paragraph has enough words to wrap" in result.output98+ assert (99+ "RAW-LINE-ONE stays on one line even with many many many words."100+ in result.output101+ )102+ assert "RAW-LINE-TWO keeps original formatting." in result.output103+ assert "Final paragraph wraps normally as well." in result.output104+105+106+def test_help_wrapping_long_name() -> None:107+ app = typer.Typer(rich_markup_mode=None)108+109+ @app.command()110+ def cmd(value: str) -> None:111+ pass # pragma: no cover112+113+ result = runner.invoke(114+ app,115+ ["cmd", "--help"],116+ terminal_width=40,117+ prog_name="very-long-program-name-that-forces-wrap",118+ )119+ assert result.exit_code == 0120+121+ output_lines = result.output.splitlines()122+ usage_idx = output_lines.index("Usage: very-long-program-name-that-forces-wrap ")123+ args_line = output_lines[usage_idx + 1]124+ assert args_line.lstrip() == "[OPTIONS] VALUE"125+ assert args_line.startswith(" ")126+127+128+def test_format_long_help_option() -> None:129+ app = typer.Typer(rich_markup_mode=None)130+131+ @app.command()132+ def cmd(133+ very_long: str = typer.Option(134+ ...,135+ "--this-is-a-very-very-very-long-option-name",136+ help="Description is rendered in the next line for long option labels.",137+ ),138+ ) -> None:139+ pass # pragma: no cover140+141+ result = runner.invoke(app, ["cmd", "--help"], terminal_width=80)142+ assert result.exit_code == 0143+144+ output_lines = result.output.splitlines()145+ option_idx = next(146+ i147+ for i, line in enumerate(output_lines)148+ if "--this-is-a-very-very-very-long-option-name" in line149+ )150+ assert "Description is rendered" not in output_lines[option_idx]151+ first_desc_line = output_lines[option_idx + 1]152+ assert first_desc_line.lstrip().startswith("Description is rendered")153+ continuation_block = " ".join(154+ line.strip() for line in output_lines[option_idx + 1 :] if line.startswith(" ")155+ )156+ assert (157+ "Description is rendered in the next line for long option labels."158+ in continuation_block159+ )added:tests/test_cli/test_parser.py+67 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+runner = CliRunner()8+9+10+def test_double_dash() -> None:11+ result = subprocess.run(12+ [13+ sys.executable,14+ "-m",15+ "coverage",16+ "run",17+ "-m",18+ "typer",19+ "tests/assets/cli/sample.py",20+ "run",21+ "hello",22+ "--",23+ "--name",24+ "Camila",25+ ],26+ capture_output=True,27+ encoding="utf-8",28+ )29+ assert "Got unexpected extra argument" in result.stderr30+ assert "--name Camila" in result.stderr31+32+33+def test_unknown_short_option() -> None:34+ result = subprocess.run(35+ [36+ sys.executable,37+ "-m",38+ "coverage",39+ "run",40+ "-m",41+ "typer",42+ "tests/assets/cli/sample.py",43+ "run",44+ "hello",45+ "-x",46+ ],47+ capture_output=True,48+ encoding="utf-8",49+ )50+ assert "No such option: -x" in result.stderr51+52+53+def test_ignore_unknown_short_option() -> None:54+ app = typer.Typer(55+ context_settings={"ignore_unknown_options": True, "allow_extra_args": True}56+ )57+58+ @app.command()59+ def main(60+ ctx: typer.Context, all_: bool = typer.Option(False, "--all", "-a")61+ ) -> None:62+ assert all_63+ print(ctx.args)64+65+ result = runner.invoke(app, ["-azq"])66+ assert result.exit_code == 067+ assert "['-zq']" in result.outputadded:tests/test_cli/test_program_name.py+13 added
1+from typer import _click2+3+4+def test_detect_program_name_submodule_path() -> None:5+ class MainModule:6+ __package__ = "example"7+8+ program_name = _click.utils._detect_program_name(9+ path="/tmp/cli.py",10+ _main=MainModule(),11+ )12+13+ assert program_name == "python -m example.cli"added:tests/test_completion/choice_case_insensitive_example.py+19 added
1+from enum import Enum2+3+import typer4+5+app = typer.Typer()6+7+8+class User(str, Enum):9+ rick = "rick"10+ morty = "morty"11+12+13+@app.command()14+def main(name: User = typer.Option(User.rick, "--name", case_sensitive=False)):15+ print(name.value)16+17+18+if __name__ == "__main__":19+ app()added:tests/test_completion/choice_example.py+19 added
1+from enum import Enum2+3+import typer4+5+app = typer.Typer()6+7+8+class User(str, Enum):9+ rick = "rick"10+ morty = "morty"11+12+13+@app.command()14+def main(name: User = typer.Option(User.rick, "--name")):15+ print(name.value)16+17+18+if __name__ == "__main__":19+ app()added:tests/test_completion/completion_option_then_argument.py+23 added
1+import typer2+3+app = typer.Typer()4+5+6+def complete_name(ctx, args, incomplete):7+ return ["opt-choice"] # pragma: no cover8+9+10+def complete_target(ctx, args, incomplete):11+ return ["arg-choice"]12+13+14+@app.command()15+def main(16+ name: str = typer.Option(..., "--name", autocompletion=complete_name),17+ target: str = typer.Argument(..., autocompletion=complete_target),18+):19+ print(name, target) # pragma: no cover20+21+22+if __name__ == "__main__":23+ app()added:tests/test_completion/file_example.py+12 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def main(config: typer.FileText = typer.Option(...)):8+ print(config.read())9+10+11+if __name__ == "__main__":12+ app()added:tests/test_completion/test_completion_choice_no_case.py+32 added
1+import os2+import subprocess3+import sys4+5+from . import choice_case_insensitive_example as mod6+7+8+def test_script() -> None:9+ result = subprocess.run(10+ [sys.executable, "-m", "coverage", "run", mod.__file__, "--name", "rick"],11+ capture_output=True,12+ encoding="utf-8",13+ )14+ assert result.returncode == 015+ assert "rick" in result.stdout16+17+18+def test_completion_choice_bash_case_insensitive() -> None:19+ result = subprocess.run(20+ [sys.executable, "-m", "coverage", "run", mod.__file__, " "],21+ capture_output=True,22+ encoding="utf-8",23+ env={24+ **os.environ,25+ "_CHOICE_CASE_INSENSITIVE_EXAMPLE.PY_COMPLETE": "complete_bash",26+ "COMP_WORDS": "choice_case_insensitive_example.py --name MO",27+ "COMP_CWORD": "2",28+ },29+ )30+ assert result.returncode == 031+ assert "morty" in result.stdout32+ assert "rick" not in result.stdoutadded:tests/test_completion/test_completion_choice.py+32 added
1+import os2+import subprocess3+import sys4+5+from . import choice_example as mod6+7+8+def test_script() -> None:9+ result = subprocess.run(10+ [sys.executable, "-m", "coverage", "run", mod.__file__, "--name", "rick"],11+ capture_output=True,12+ encoding="utf-8",13+ )14+ assert result.returncode == 015+ assert "rick" in result.stdout16+17+18+def test_completion_choice_bash() -> None:19+ result = subprocess.run(20+ [sys.executable, "-m", "coverage", "run", mod.__file__, " "],21+ capture_output=True,22+ encoding="utf-8",23+ env={24+ **os.environ,25+ "_CHOICE_EXAMPLE.PY_COMPLETE": "complete_bash",26+ "COMP_WORDS": "choice_example.py --name mo",27+ "COMP_CWORD": "2",28+ },29+ )30+ assert result.returncode == 031+ assert "morty" in result.stdout32+ assert "rick" not in result.stdoutadded:tests/test_completion/test_completion_file.py+39 added
1+import os2+import subprocess3+import sys4+5+from . import file_example as mod6+7+8+def test_script() -> None:9+ result = subprocess.run(10+ [11+ sys.executable,12+ "-m",13+ "coverage",14+ "run",15+ mod.__file__,16+ "--config",17+ mod.__file__,18+ ],19+ capture_output=True,20+ encoding="utf-8",21+ )22+ assert result.returncode == 023+ assert "def main(config: typer.FileText = typer.Option(...)):" in result.stdout24+25+26+def test_completion_file_bash() -> None:27+ result = subprocess.run(28+ [sys.executable, "-m", "coverage", "run", mod.__file__, " "],29+ capture_output=True,30+ encoding="utf-8",31+ env={32+ **os.environ,33+ "_FILE_EXAMPLE.PY_COMPLETE": "complete_bash",34+ "COMP_WORDS": "file_example.py --config file_ex",35+ "COMP_CWORD": "2",36+ },37+ )38+ assert result.returncode == 039+ assert "file_ex" in result.stdoutmodified:tests/test_completion/test_completion_option_colon.py+33 added
175 unmodified lines176 assert "latest alpine image" not in result.stdout177 assert "nvidia/cuda:10.0-devel-ubuntu18.04" not in result.stdout178 179 180+def test_completion_powershell_option_equals_value() -> None:181+ result = subprocess.run(182+ [sys.executable, "-m", "coverage", "run", mod.__file__, " "],183+ capture_output=True,184+ encoding="utf-8",185+ env={186+ **os.environ,187+ "_COLON_EXAMPLE.PY_COMPLETE": "complete_powershell",188+ "_TYPER_COMPLETE_ARGS": "colon_example.py --name=alpine",189+ "_TYPER_COMPLETE_WORD_TO_COMPLETE": "--name=alpine",190+ },191+ )192+ assert "alpine:hello" in result.stdout193+ assert "alpine:latest" in result.stdout194+ assert "nvidia/cuda:10.0-devel-ubuntu18.04" not in result.stdout195+196+197+def test_completion_powershell_option_equals_only() -> None:198+ result = subprocess.run(199+ [sys.executable, "-m", "coverage", "run", mod.__file__, " "],200+ capture_output=True,201+ encoding="utf-8",202+ env={203+ **os.environ,204+ "_COLON_EXAMPLE.PY_COMPLETE": "complete_powershell",205+ "_TYPER_COMPLETE_ARGS": "colon_example.py --name=",206+ "_TYPER_COMPLETE_WORD_TO_COMPLETE": "=",207+ },208+ )209+ assert result.returncode == 0210+ assert result.stdout.strip() == ""211+212+213 def test_completion_colon_pwsh_all():214 result = subprocess.run(215 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],216 capture_output=True,108 unmodified linesmodified:tests/test_completion/test_completion.py+27 added
1 unmodified line2 import subprocess3 import sys4 from pathlib import Path5 6+from typer._click.shell_completion import CompletionItem7+8 from docs_src.typer_app import tutorial001_py310 as mod9 10 from ..utils import needs_bash, needs_linux, requires_completion_permission11+from . import completion_option_then_argument as mod_option_arg12 13 14 @needs_bash15 @needs_linux150 unmodified lines166 assert (167 "Register-ArgumentCompleter -Native -CommandName tutorial001_py310.py -ScriptBlock $scriptblock"168 in result.stdout169 )170+171+172+def test_completion_option_argument() -> None:173+ file_name = Path(mod_option_arg.__file__).name174+ result = subprocess.run(175+ [sys.executable, "-m", "coverage", "run", mod_option_arg.__file__, " "],176+ capture_output=True,177+ encoding="utf-8",178+ env={179+ **os.environ,180+ f"_{file_name.upper()}_COMPLETE": "complete_bash",181+ "COMP_WORDS": f"{file_name} --name chosen ",182+ "COMP_CWORD": "3",183+ },184+ )185+ assert "arg-choice" in result.stdout186+ assert "opt-choice" not in result.stdout187+188+189+def test_completion_item_getattr() -> None:190+ item = CompletionItem("demo", source="envvar")191+192+ assert item.source == "envvar"193+ assert item.missing is Nonemodified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001.py+7 added
2 unmodified lines3 import sys4 from types import ModuleType5 6 import pytest7+import typer8 from typer.testing import CliRunner9 10 runner = CliRunner()11 10 unmodified lines22 mod = importlib.import_module(module_name)23 return mod24 25 26+def test_type_repr(mod: ModuleType):27+ command = typer.main.get_command(mod.app)28+ force_param = next(param for param in command.params if param.name == "force")29+ assert repr(force_param.type) == "BOOL"30+31+32 def test_help(mod: ModuleType):33 result = runner.invoke(mod.app, ["--help"])34 assert result.exit_code == 035 assert "--force" in result.output28 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+17 added
1 import subprocess2 import sys3+from datetime import datetime4 5+import typer6 from typer.testing import CliRunner7 8 from docs_src.parameter_types.datetime import tutorial001_py310 as mod9 10 runner = CliRunner()11 app = mod.app12 13 14+def test_type_repr():15+ command = typer.main.get_command(app)16+ birth_param = next(param for param in command.params if param.name == "birth")17+ assert repr(birth_param.type) == "DateTime"18+19+20 def test_help():21 result = runner.invoke(app, ["--help"])22 assert result.exit_code == 023 assert "[%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output5 unmodified lines29 assert "Interesting day to be born: 1956-01-31 10:00:00" in result.output30 assert "Birth hour: 10" in result.output31 32 33+def test_main_datetime_object():34+ result = runner.invoke(35+ app, [], default_map={"birth": datetime(1956, 1, 31, 10, 0, 0)}36+ )37+ assert result.exit_code == 038+ assert "Interesting day to be born: 1956-01-31 10:00:00" in result.output39+ assert "Birth hour: 10" in result.output40+41+42 def test_invalid():43 result = runner.invoke(app, ["july-19-1989"])44 assert result.exit_code != 045 assert (16 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+11 added
1 import subprocess2 import sys3 4+import typer5 from typer.testing import CliRunner6 7 from docs_src.parameter_types.index import tutorial001_py310 as mod8 9 runner = CliRunner()10 app = mod.app11 12 13+def test_type_repr():14+ command = typer.main.get_command(app)15+ age_param = next(param for param in command.params if param.name == "age")16+ height_meters_param = next(17+ param for param in command.params if param.name == "height_meters"18+ )19+ assert repr(age_param.type) == "INT"20+ assert repr(height_meters_param.type) == "FLOAT"21+22+23 def test_help():24 result = runner.invoke(app, ["--help"])25 assert result.exit_code == 026 assert "--age" in result.output30 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+13 added
22 unmodified lines23 mod = importlib.import_module(module_name)24 return mod25 26 27+def test_type_repr(mod: ModuleType):28+ command = typer.main.get_command(mod.app)29+30+ id_param = next(param for param in command.params if param.name == "id")31+ assert repr(id_param.type) == "<IntRange 0<=x<=1000>"32+33+ age_param = next(param for param in command.params if param.name == "age")34+ assert repr(age_param.type) == "<IntRange x>=18>"35+36+ score_param = next(param for param in command.params if param.name == "score")37+ assert repr(score_param.type) == "<FloatRange x<=100>"38+39+40 def test_help(mod: ModuleType):41 result = runner.invoke(mod.app, ["--help"])42 assert result.exit_code == 043 assert "--age" in result.output61 unmodified linesmodified:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py+16 added
1 import subprocess2 import sys3+import uuid4 5+import typer6 from typer.testing import CliRunner7 8 from docs_src.parameter_types.uuid import tutorial001_py310 as mod9 10 runner = CliRunner()11 app = mod.app12 13 14+def test_type_repr():15+ command = typer.main.get_command(app)16+ user_id_param = next(param for param in command.params if param.name == "user_id")17+ assert repr(user_id_param.type) == "UUID"18+19+20 def test_main():21 result = runner.invoke(app, ["d48edaa6-871a-4082-a196-4daab372d4a1"])22 assert result.exit_code == 023 assert "USER_ID is d48edaa6-871a-4082-a196-4daab372d4a1" in result.output24 assert "UUID version is: 4" in result.output25 26 27+def test_main_with_uuid_object():28+ user_id = uuid.UUID("d48edaa6-871a-4082-a196-4daab372d4a1")29+ result = runner.invoke(app, [], default_map={"user_id": user_id})30+ assert result.exit_code == 031+ assert "USER_ID is d48edaa6-871a-4082-a196-4daab372d4a1" in result.output32+ assert "UUID version is: 4" in result.output33+34+35 def test_invalid_uuid():36 result = runner.invoke(app, ["7479706572-72756c6573"])37 assert result.exit_code != 038 assert (12 unmodified linesadded:tests/atomic_write_example.py+63 added
1+import time2+3+import typer4+5+app = typer.Typer()6+7+8+@app.command()9+def write_atomic(10+ config: typer.FileText = typer.Option(..., mode="w", atomic=True),11+ pause: float = typer.Option(0.3),12+) -> None:13+ config.write("atomic-content-1\n")14+ config.flush()15+ typer.echo("halfway")16+ time.sleep(pause)17+ config.write("atomic-content-2\n")18+ config.flush()19+ typer.echo("written atomically")20+21+22+@app.command()23+def write_atomic_binary(24+ config: typer.FileBinaryWrite = typer.Option(..., atomic=True, lazy=False),25+) -> None:26+ config.write(b"\x00\x01binary-atomic\n")27+ typer.echo("written binary atomically")28+29+30+@app.command()31+def api_atomic(32+ config: typer.FileText = typer.Option(..., mode="w", atomic=True, lazy=False),33+) -> None:34+ typer.echo(f"name={config.name}")35+ typer.echo(f"repr={repr(config)}")36+ with config as entered:37+ typer.echo(f"entered={entered is config}")38+ entered.write("atomic-api-done\n")39+40+41+@app.command()42+def invalid_atomic_append(43+ config: typer.FileText = typer.Option(..., mode="a", atomic=True, lazy=False),44+) -> None:45+ typer.echo(config.name) # pragma: no cover46+47+48+@app.command()49+def invalid_atomic_exclusive(50+ config: typer.FileText = typer.Option(..., mode="x", atomic=True, lazy=False),51+) -> None:52+ typer.echo(config.name) # pragma: no cover53+54+55+@app.command()56+def invalid_atomic_read(57+ config: typer.FileText = typer.Option(..., mode="r", atomic=True, lazy=False),58+) -> None:59+ typer.echo(config.name) # pragma: no cover60+61+62+if __name__ == "__main__":63+ app()modified:tests/test_annotated.py+12 added
1 import sys2 from pathlib import Path3 from typing import Annotated4 5+import pytest6 import typer7 from typer.testing import CliRunner8 9 runner = CliRunner()85 unmodified lines95 assert isinstance(my_path, CustomPath)96 97 result = runner.invoke(app, "/some/quirky/path/implementation")98 assert result.exit_code == 099+100+101+def test_annotated_option_invalid():102+ app = typer.Typer()103+104+ @app.command()105+ def cmd(value: Annotated[str, typer.Option(..., "foo-bar")]):106+ print(value) # pragma: no cover107+108+ with pytest.raises(ValueError, match="Invalid start character for option"):109+ runner.invoke(app, ["--help"], catch_exceptions=False)added:tests/test_atomic_file.py+122 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import pytest6+7+from . import atomic_write_example as mod8+9+10+def test_atomic_write(tmp_path: Path) -> None:11+ original_content = "existing-content\n"12+ output_file = tmp_path / "atomic-write-target.txt"13+ output_file.write_text(original_content, encoding="utf-8")14+15+ process = subprocess.Popen(16+ [17+ sys.executable,18+ "-m",19+ "coverage",20+ "run",21+ mod.__file__,22+ "write-atomic",23+ f"--config={output_file}",24+ ],25+ stdout=subprocess.PIPE,26+ stderr=subprocess.PIPE,27+ text=True,28+ )29+ assert process.stdout is not None30+31+ # Halfway of writing the file, check that the original content is still there32+ halfway_line = process.stdout.readline().strip()33+ assert halfway_line == "halfway"34+ assert output_file.read_text(encoding="utf-8") == original_content35+36+ # Only at the end, the full new content is visible37+ stdout, stderr = process.communicate(timeout=5)38+ assert process.returncode == 0, stderr39+ assert "written atomically" in stdout40+ assert (41+ output_file.read_text(encoding="utf-8")42+ == "atomic-content-1\natomic-content-2\n"43+ )44+45+46+def test_atomic_binary_write(tmp_path: Path) -> None:47+ output_file = tmp_path / "atomic-binary.bin"48+49+ result = subprocess.run(50+ [51+ sys.executable,52+ "-m",53+ "coverage",54+ "run",55+ mod.__file__,56+ "write-atomic-binary",57+ f"--config={output_file}",58+ ],59+ capture_output=True,60+ encoding="utf-8",61+ )62+63+ assert result.returncode == 0, result.stderr64+ assert "written binary atomically" in result.stdout65+ assert output_file.read_bytes() == b"\x00\x01binary-atomic\n"66+67+68+def test_atomic_api(tmp_path: Path) -> None:69+ output_file = tmp_path / "atomic-api.txt"70+71+ result = subprocess.run(72+ [73+ sys.executable,74+ "-m",75+ "coverage",76+ "run",77+ mod.__file__,78+ "api-atomic",79+ f"--config={output_file}",80+ ],81+ capture_output=True,82+ encoding="utf-8",83+ )84+85+ assert result.returncode == 0, result.stderr86+ assert f"name={output_file}" in result.stdout87+ assert "repr=<_io.TextIOWrapper" in result.stdout88+ assert "entered=True" in result.stdout89+ assert output_file.read_text(encoding="utf-8") == "atomic-api-done\n"90+91+92+@pytest.mark.parametrize(93+ ("command_name", "expected_message"),94+ [95+ ("invalid-atomic-append", "Appending to an existing file is not supported"),96+ ("invalid-atomic-exclusive", "Use the `overwrite`-parameter instead."),97+ ("invalid-atomic-read", "Atomic writes only make sense with `w`-mode."),98+ ],99+)100+def test_atomic_mode_invalid_options(101+ tmp_path: Path, command_name: str, expected_message: str102+) -> None:103+ output_file = tmp_path / "atomic-invalid-mode.txt"104+ output_file.write_text("existing-content\n", encoding="utf-8")105+106+ result = subprocess.run(107+ [108+ sys.executable,109+ "-m",110+ "coverage",111+ "run",112+ mod.__file__,113+ command_name,114+ f"--config={output_file}",115+ ],116+ capture_output=True,117+ encoding="utf-8",118+ )119+120+ assert result.returncode != 0121+ combined_output = f"{result.stdout}\n{result.stderr}"122+ assert expected_message in combined_outputadded:tests/test_core.py+379 added
1+from typing import Annotated2+3+import pytest4+import typer5+import typer._completion_shared6+import typer.completion7+from typer import _click8+from typer.core import TyperArgument, TyperCommand, TyperGroup, TyperOption, _split_opt9+from typer.testing import CliRunner10+11+runner = CliRunner()12+13+14+def test_human_readable_name() -> None:15+ app = typer.Typer()16+17+ @app.command()18+ def main(19+ my_arg_1: Annotated[str, typer.Argument()],20+ my_arg_2: Annotated[str, typer.Argument(metavar="META_ARG")],21+ my_opt: Annotated[str, typer.Option()],22+ ):23+ pass # pragma: no cover24+25+ command = typer.main.get_command(app)26+ params = {param.name: param for param in command.params}27+28+ assert params["my_arg_1"].human_readable_name == "MY_ARG_1"29+ assert params["my_arg_2"].human_readable_name == "META_ARG"30+ assert params["my_opt"].human_readable_name == "my_opt"31+32+33+def test_parameter_metavar() -> None:34+ app = typer.Typer(rich_markup_mode=None)35+36+ @app.command()37+ def cmd(name: Annotated[str, typer.Option(metavar="CUSTOM")]) -> None:38+ pass # pragma: no cover39+40+ result = runner.invoke(app, ["--help"])41+ assert result.exit_code == 042+ assert "--name CUSTOM" in result.output43+44+45+def test_parameter_nargs_gt_1() -> None:46+ param = TyperArgument(param_decls=["value"], type=str, nargs=2)47+ ctx = _click.Context(TyperCommand(name="cmd"))48+49+ assert param.type_cast_value(ctx, ("one", "two")) == ("one", "two")50+51+ with pytest.raises(52+ _click.exceptions.BadParameter, match="Takes 2 values but 1 given."53+ ):54+ param.type_cast_value(ctx, ("one",))55+56+57+def test_parameter_constructor() -> None:58+ # no param_decl and expose_value is False: sets name to None59+ arg = TyperArgument(param_decls=[], expose_value=False)60+ assert arg.name is None61+ assert arg.opts == []62+ assert arg.secondary_opts == []63+64+ # no param_decl and expose_value is True: raises65+ with pytest.raises(TypeError, match="does not have a name."):66+ TyperArgument(param_decls=[], expose_value=True)67+68+ # len(param_decl) > 1: raises69+ with pytest.raises(TypeError, match="take exactly one parameter declaration"):70+ TyperArgument(param_decls=["first", "second"])71+72+ # duplicated identifier in option declarations: raises73+ with pytest.raises(TypeError, match="Name 'name' defined twice"):74+ TyperOption(param_decls=["name", "name"], required=False)75+76+ # same true/false flag in boolean option declaration: raises77+ with pytest.raises(ValueError, match="cannot use the same flag for true/false"):78+ TyperOption(param_decls=["flag", "--flag/--flag"], required=False, is_flag=True)79+80+ # inferred name is not a valid identifier: sets name to None81+ unnamed_option = TyperOption(param_decls=["--123"], required=False)82+ assert unnamed_option.name is None83+84+ # no param_decl and prompt=True: raises85+ with pytest.raises(TypeError, match="'name' is required with 'prompt=True'."):86+ TyperOption(param_decls=[], expose_value=False, prompt=True, required=False)87+88+ # count works89+ option = TyperOption(90+ param_decls=["verbose", "--verbose", "-v"],91+ type=None,92+ default=0,93+ required=False,94+ count=True,95+ )96+ assert isinstance(option.type, _click.types.IntRange)97+ assert option.type.min == 098+99+100+def test_option_error_hint() -> None:101+ option = TyperOption(102+ param_decls=["name", "--name"],103+ required=False,104+ show_envvar=True,105+ envvar="APP_NAME",106+ )107+ hint = option.get_error_hint(_click.Context(TyperCommand(name="cmd")))108+ assert "(env var: 'APP_NAME')" in hint109+110+111+def test_group_init() -> None:112+ group_no_commands = TyperGroup(name="root", commands=None)113+ assert group_no_commands.commands == {}114+115+ named = TyperCommand(name="named")116+ unnamed = TyperCommand(name=None)117+ group_command_sequence = TyperGroup(name="root", commands=[named, unnamed])118+ assert group_command_sequence.commands == {"named": named}119+120+121+@pytest.mark.parametrize("with_result_callback", [False, True])122+def test_group_result_callback(with_result_callback: bool) -> None:123+ called = {"child": False, "result_callback": False}124+125+ def child_callback() -> None:126+ called["child"] = True127+ return None128+129+ def result_callback(value, **kwargs): # type: ignore[no-untyped-def]130+ called["result_callback"] = True131+ return value132+133+ child = TyperCommand(name="child", callback=child_callback)134+ group = TyperGroup(135+ name="root",136+ commands={"child": child},137+ result_callback=result_callback if with_result_callback else None,138+ )139+ ctx = group.make_context("root", ["child"])140+141+ result = group.invoke(ctx)142+143+ assert result is None144+ assert called["child"] is True145+ assert called["result_callback"] is with_result_callback146+ assert ctx.invoked_subcommand == "child"147+148+149+def test_group_add_command() -> None:150+ group = TyperGroup(name="root")151+ unnamed_command = TyperCommand(name=None)152+153+ with pytest.raises(TypeError, match="Command has no name."):154+ group.add_command(unnamed_command)155+156+157+def test_group_click_resolve_command() -> None:158+ child = TyperCommand(name="child")159+ group = TyperGroup(name="root", commands={"child": child})160+ ctx = group.make_context("root", ["CHILD"], token_normalize_func=str.lower)161+162+ cmd_name, cmd, remaining = group._click_resolve_command(ctx, ["CHILD"])163+164+ assert cmd_name == "child"165+ assert cmd is child166+ assert remaining == []167+168+169+@pytest.mark.parametrize(170+ ("envvar", "auto_prefix", "set_env", "expected"),171+ [172+ ("APP_NAME", None, True, "my-precious"),173+ (None, "APP", True, "my-precious"),174+ (None, None, False, None),175+ ],176+)177+def test_option_resolve_envvar(178+ monkeypatch: pytest.MonkeyPatch,179+ envvar: str | None,180+ auto_prefix: str | None,181+ set_env: bool,182+ expected: str | None,183+) -> None:184+ option = TyperOption(185+ param_decls=["name", "--name"],186+ required=False,187+ envvar=envvar,188+ )189+ if set_env:190+ monkeypatch.setenv("APP_NAME", "my-precious")191+192+ ctx = _click.Context(TyperCommand(name="cmd"), auto_envvar_prefix=auto_prefix)193+ assert option.resolve_envvar_value(ctx) == expected194+195+196+def test_option_resolve_envvar_list(197+ monkeypatch: pytest.MonkeyPatch,198+) -> None:199+ option = TyperOption(200+ param_decls=["name", "--name"],201+ required=False,202+ envvar=["APP_NAME_1", "APP_NAME_2"],203+ )204+ monkeypatch.delenv("APP_NAME_1", raising=False)205+ monkeypatch.delenv("APP_NAME_2", raising=False)206+ ctx = _click.Context(TyperCommand(name="cmd"))207+208+ assert option.resolve_envvar_value(ctx) is None209+210+211+def test_context_auto_envvar() -> None:212+ app = typer.Typer(context_settings={"auto_envvar_prefix": "APP"})213+ sub_app = typer.Typer()214+215+ @sub_app.command()216+ def clone(ctx: typer.Context) -> None:217+ print(ctx.auto_envvar_prefix)218+219+ app.add_typer(sub_app, name="beth")220+221+ result = runner.invoke(app, ["beth", "clone"])222+ assert result.exit_code == 0223+ assert "APP_BETH_CLONE" in result.stdout224+225+226+def test_context_with_resource() -> None:227+ events: list[str] = []228+229+ class DemoResource:230+ def __enter__(self) -> str:231+ events.append("enter")232+ return "pickle-rick"233+234+ def __exit__(self, *args: object) -> None:235+ events.append("exit")236+237+ app = typer.Typer()238+239+ @app.command()240+ def cmd(ctx: typer.Context) -> None:241+ value = ctx.with_resource(DemoResource())242+ assert value == "pickle-rick"243+ assert events == ["enter"]244+ print("I'm a pickle")245+246+ result = runner.invoke(app)247+248+ assert result.exit_code == 0249+ assert "I'm a pickle" in result.stdout250+ assert events == ["enter", "exit"]251+252+253+def test_context_find_root() -> None:254+ app = typer.Typer()255+ sub_app = typer.Typer()256+257+ @sub_app.command()258+ def child(ctx: typer.Context) -> None:259+ root = ctx.find_root()260+ assert root.parent is None261+ assert root is ctx.parent.parent262+ print("ok")263+264+ app.add_typer(sub_app, name="sub")265+266+ result = runner.invoke(app, ["sub", "child"])267+ assert result.exit_code == 0268+ assert "ok" in result.stdout269+270+271+def test_context_find_object() -> None:272+ class Marker:273+ pass274+275+ marker = Marker()276+ app = typer.Typer()277+278+ @app.callback()279+ def callback(ctx: typer.Context) -> None:280+ ctx.obj = marker281+282+ @app.command()283+ def child(ctx: typer.Context) -> None:284+ assert ctx.find_object(Marker) is marker285+ assert ctx.find_object(str) is None286+ print("ok")287+288+ result = runner.invoke(app, ["child"])289+ assert result.exit_code == 0290+ assert "ok" in result.stdout291+292+293+def test_context_lookup_default_callable() -> None:294+ app = typer.Typer()295+296+ @app.command()297+ def child(ctx: typer.Context) -> None:298+ ctx.default_map = {"planet": lambda: "Earth"}299+ assert ctx.lookup_default("planet") == "Earth"300+ value = ctx.lookup_default("planet", call=False)301+ assert callable(value)302+ print("ok")303+304+ result = runner.invoke(app)305+ assert result.exit_code == 0306+ assert "ok" in result.stdout307+308+309+def test_context_abort() -> None:310+ app = typer.Typer()311+312+ @app.command()313+ def cmd(ctx: typer.Context) -> None:314+ ctx.abort()315+316+ result = runner.invoke(app, standalone_mode=False)317+ assert result.exit_code == 1318+ assert isinstance(result.exception, _click.core.Abort)319+320+321+def test_command_help_disabled() -> None:322+ app = typer.Typer()323+324+ @app.command(add_help_option=False)325+ def cmd() -> None:326+ pass # pragma: no cover327+328+ result = runner.invoke(app, ["--help"], standalone_mode=False)329+ assert result.exit_code == 1330+ assert isinstance(result.exception, _click.exceptions.NoSuchOption)331+ assert result.exception.option_name == "--help"332+333+334+def test_command_help_deprecated() -> None:335+ app = typer.Typer(rich_markup_mode=None, epilog="Built with love")336+337+ @app.command(short_help="Shorty", help="Regular help text.", deprecated=True)338+ def one() -> None:339+ pass # pragma: no cover340+341+ @app.command()342+ def two() -> None:343+ pass # pragma: no cover344+345+ result = runner.invoke(app, ["one", "--help"])346+ assert result.exit_code == 0347+ assert "Regular help text. (DEPRECATED)" in result.output348+349+ result = runner.invoke(app, ["--help"])350+ assert result.exit_code == 0351+ assert "Built with love" in result.output352+ assert "oneShorty(DEPRECATED)" in result.output.replace(" ", "")353+354+355+@pytest.mark.parametrize(356+ ("value", "expected_prefix", "expected_opt"),357+ [358+ ("--verbose", "--", "verbose"),359+ ("//verbose", "//", "verbose"),360+ ("-verbose", "-", "verbose"),361+ ("verbose", "", "verbose"),362+ ],363+)364+def test_split_opt(value: str, expected_prefix: str, expected_opt: str) -> None:365+ prefix, opt = _split_opt(value)366+ assert prefix == expected_prefix367+ assert opt == expected_opt368+369+370+def test_nargs_default_map():371+ app = typer.Typer()372+373+ @app.command()374+ def main(names: list[str] = typer.Option(None)):375+ print(names) # pragma: no cover376+377+ result = runner.invoke(app, [], default_map={"names": "not-a-list"})378+ assert result.exit_code == 2379+ assert "Invalid value" in result.outputmodified:tests/test_launch.py+84 added-8 removed
1+import io2 import subprocess3 from unittest.mock import patch4 5 import pytest6 import typer7 7-from tests.utils import needs_windows8+from tests.utils import needs_linux, needs_macos, needs_windows9 10 url = "http://example.com"11 12 38 unmodified lines51 52 mock_webbrowser_open.assert_called_once_with(url)53 54 54-def test_calls_original_launch_when_not_passing_urls():55- with patch("typer.main.click.launch", return_value=0) as launch_mock:56- typer.launch("not a url")55+@pytest.fixture56+def allow_dev_null(monkeypatch):57+ real_open = open58 58- launch_mock.assert_called_once_with("not a url", wait=False, locate=False)59+ def fake_open(path, *args, **kwargs):60+ if path == "/dev/null":61+ return io.StringIO()62+ return real_open(path, *args, **kwargs) # pragma: no cover63 64+ monkeypatch.setattr("builtins.open", fake_open)65 66+67+@needs_macos68+def test_open_url_macos(monkeypatch, allow_dev_null):69+ recorded: list[list[str]] = []70+71+ class Proc:72+ def wait(self) -> int:73+ return 4274+75+ def fake_popen(args, **kwargs):76+ recorded.append(list(args))77+ return Proc()78+79+ monkeypatch.setattr(subprocess, "Popen", fake_popen)80+81+ assert typer.launch("/path/to/file", wait=True, locate=True) == 4282+ assert recorded[0][:3] == ["open", "-W", "-R"]83+ assert recorded[0][-1] == "/path/to/file"84+85+86 @needs_windows87+def test_launch_files_windows(monkeypatch):88+ calls: list[list[str]] = []89+90+ def fake_call(args):91+ calls.append(list(args))92+ return 093+94+ monkeypatch.setattr(subprocess, "call", fake_call)95+96+ assert typer.launch("C:/Tools/readme.txt", wait=True, locate=False) == 097+ assert typer.launch("file:///C:/tmp/a.txt", wait=False, locate=True) == 098+ assert calls.pop(0) == ["start", "/WAIT", "", "C:/Tools/readme.txt"]99+ assert calls.pop(0) == ["explorer", "/select,/C:/tmp/a.txt"]100+101+ monkeypatch.setattr(subprocess, "call", lambda a: (_ for _ in ()).throw(OSError()))102+ assert typer.launch("D:/no/such/file.txt", wait=False, locate=False) == 127103+104+105+@needs_linux106+def test_open_url_linux_wait(monkeypatch):107+ class Proc:108+ def __init__(self, code: int = 0) -> None:109+ self._code = code110+111+ def wait(self) -> int:112+ return self._code113+114+ monkeypatch.setattr(subprocess, "Popen", lambda *a, **k: Proc(7))115+116+ assert typer.launch("/file", wait=True, locate=False) == 7117+118+119+@needs_linux120+def test_open_url_linux_locate(monkeypatch):121+ recorded: list[list[str]] = []122+123+ class Proc:124+ def wait(self) -> int:125+ return 0 # pragma: no cover126+127+ def fake_popen(args, **kwargs):128+ recorded.append(list(args))129+ return Proc()130+131+ monkeypatch.setattr(subprocess, "Popen", fake_popen)132+133+ assert typer.launch("/tmp/sub/file.txt", wait=False, locate=True) == 0134+ assert recorded[-1] == ["xdg-open", "/tmp/sub"]135+136+137+@needs_windows138 def test_launch_file():139 with (64- patch("click._termui_impl.sys.platform", "win32"),65- patch("click._termui_impl.WIN", True),66- patch("click._termui_impl.CYGWIN", False),140+ patch("typer._click._termui_impl.sys.platform", "win32"),141+ patch("typer._click._termui_impl.WIN", True),142+ patch("typer._click._termui_impl.CYGWIN", False),143 patch("subprocess.call", return_value=0) as call_mock,144 ):145 result = typer.launch("C:/tmp/file.txt", locate=True)146 2 unmodified linesmodified:tests/test_others.py+150 added-28 removed
4 unmodified lines5 from pathlib import Path6 from typing import Annotated7 from unittest import mock8 9-import click9 import pytest10 import typer11 import typer._completion_shared12 import typer.completion14-from typer.core import _split_opt13+from typer import _click14 from typer.main import solve_typer_info_defaults, solve_typer_info_help15 from typer.models import ParameterInfo, TyperInfo16 from typer.testing import CliRunner17 17 unmodified lines35 def test_too_many_parsers():36 def custom_parser(value: str) -> int:37 return int(value) # pragma: no cover38 40- class CustomClickParser(click.ParamType):39+ class CustomClickParser(_click.types.ParamType):40 name = "custom_parser"41 42 def convert(43 self,44 value: str,46- param: click.Parameter | None,47- ctx: click.Context | None,45+ param: _click.Parameter | None,46+ ctx: _click.Context | None,47 ) -> typing.Any:48 return int(value) # pragma: no cover49 50 expected_error = (8 unmodified lines59 def test_valid_parser_permutations():60 def custom_parser(value: str) -> int:61 return int(value) # pragma: no cover62 64- class CustomClickParser(click.ParamType):63+ class CustomClickParser(_click.types.ParamType):64 name = "custom_parser"65 66 def convert(67 self,68 value: str,70- param: click.Parameter | None,71- ctx: click.Context | None,69+ param: _click.Parameter | None,70+ ctx: _click.Context | None,71 ) -> typing.Any:72 return int(value) # pragma: no cover73 74 ParameterInfo()27 unmodified lines102 @app.command()103 def main(name: str = typer.Option(..., callback=name_callback)):104 pass # pragma: no cover105 107- with pytest.raises(click.ClickException) as exc_info:106+ with pytest.raises(_click.ClickException) as exc_info:107 runner.invoke(app, ["--name", "Camila"])108 assert (109 exc_info.value.message == "Too many CLI parameter callback function parameters"110 )14 unmodified lines125 assert "info name is: main" in result.stdout126 assert "value is: Camila" in result.stdout127 128 129+@pytest.mark.parametrize(130+ ("param_hint", "option_decls", "expected_message"),131+ [132+ ("--name", (), "Invalid value for --name"),133+ (None, ("--name", "-n"), "Invalid value for '--name' / '-n'"),134+ ],135+)136+def test_bad_parameter_callback(137+ param_hint: str | None, option_decls: tuple[str, ...], expected_message: str138+) -> None:139+ app = typer.Typer()140+141+ def my_bad(value: str) -> str:142+ kwargs = {"param_hint": param_hint} if param_hint is not None else {}143+ raise typer.BadParameter("custom validation failed", **kwargs)144+145+ @app.command()146+ def main(name: str = typer.Option(..., *option_decls, callback=my_bad)) -> None:147+ typer.echo(name) # pragma: no cover148+149+ result = runner.invoke(app, ["--name", "Camila"])150+ assert result.exit_code == 2151+ assert expected_message in result.stderr152+ assert "custom validation failed" in result.stderr153+154+155+def test_bad_parameter_main() -> None:156+ app = typer.Typer()157+158+ @app.command()159+ def main() -> None:160+ raise typer.BadParameter("custom validation failed")161+162+ result = runner.invoke(app, [])163+ assert result.exit_code == 2164+ assert "Invalid value: custom validation failed" in result.stderr165+166+167+@pytest.mark.parametrize(168+ ("kw", "msg"),169+ [170+ (171+ {"param_hint": ["--name", "-n"], "param_type": "parameter"},172+ "Missing parameter '--name' / '-n'.",173+ ),174+ ({"param_type": "value"}, "Missing value."),175+ ],176+)177+def test_missing_parameter_msg(kw: dict[str, object], msg: str) -> None:178+ app = typer.Typer(rich_markup_mode=None)179+180+ @app.command()181+ def main() -> None:182+ raise typer._click.exceptions.MissingParameter(**kw)183+184+ result = runner.invoke(app, [])185+ assert result.exit_code == 2186+ assert msg in result.stderr187+188+189+def test_missing_parameter_callback_msg() -> None:190+ def my_cb(ctx: typer.Context, param: typer.CallbackParam, value: str) -> str:191+ raise typer._click.exceptions.MissingParameter(192+ message="My bad", ctx=ctx, param=param, param_type="parameter"193+ )194+195+ app = typer.Typer(rich_markup_mode=None)196+197+ @app.command()198+ def main(199+ mode: Annotated[200+ typing.Literal["alpha", "beta"],201+ typer.Option(..., "--mode", callback=my_cb),202+ ],203+ ) -> None:204+ typer.echo(mode) # pragma: no cover205+206+ result = runner.invoke(app, ["--mode", "alpha"])207+ assert result.exit_code == 2208+ assert "Missing parameter '--mode'." in result.stderr209+ assert "My bad. Choose from:" in result.stderr210+ assert "alpha" in result.stderr211+ assert "beta" in result.stderr212+ result_msg = runner.invoke(app, ["--mode", "alpha"], standalone_mode=False)213+ assert isinstance(result_msg.exception, typer._click.exceptions.MissingParameter)214+ assert str(result_msg.exception) == "My bad"215+216+217+def test_missing_parameter_str() -> None:218+ def my_cb(ctx: typer.Context, param: typer.CallbackParam, value: str) -> str:219+ raise typer._click.exceptions.MissingParameter(ctx=ctx, param=param)220+221+ app = typer.Typer()222+223+ @app.command()224+ def main(mode: str = typer.Option(..., "--mode", callback=my_cb)) -> None:225+ typer.echo(mode) # pragma: no cover226+227+ result2 = runner.invoke(app, ["--mode", "alpha"], standalone_mode=False)228+ assert isinstance(result2.exception, typer._click.exceptions.MissingParameter)229+ assert str(result2.exception) == "Missing parameter: mode"230+231+232+def test_click_exception_show_default_file() -> None:233+ app = typer.Typer(rich_markup_mode=None)234+235+ @app.command()236+ def main() -> None:237+ raise typer._click.ClickException("custom click failure")238+239+ result = runner.invoke(app, [])240+ assert result.exit_code == 1241+ assert "custom click" in result.stderr242+ assert "failure" in result.stderr243+244+245+def test_no_args_is_help_show() -> None:246+ app = typer.Typer(rich_markup_mode=None)247+248+ @app.callback(invoke_without_command=True, no_args_is_help=True)249+ def main() -> None:250+ return None # pragma: no cover251+252+ result = runner.invoke(app, [])253+ assert result.exit_code == 2254+ assert "Usage:" in result.stderr255+ assert "Show this message and exit." in result.stderr256+257+258 def test_callback_3_untyped_parameters():259 app = typer.Typer()260 261 def name_callback(ctx, param, value):34 unmodified lines296 result = runner.invoke(app, [])297 assert "Hello World" in result.stdout298 299 300+def test_multiple_bool_flags() -> None:301+ app = typer.Typer()302+303+ @app.command()304+ def main(choices: list[bool] = typer.Option([], "--accept/--reject")) -> None:305+ print(choices)306+307+ result = runner.invoke(app, ["--accept", "--reject", "--accept"])308+ assert result.exit_code == 0309+ assert "[True, False, True]" in result.stdout310+311+312 def test_empty_list_default_generator():313 def empty_list() -> list[str]:314 return []315 89 unmodified lines405 @app.command()406 def main(name: str = typer.Option(..., autocompletion=name_callback)):407 pass # pragma: no cover408 269- with pytest.raises(click.ClickException) as exc_info:409+ with pytest.raises(_click.ClickException) as exc_info:410 runner.invoke(app, ["--name", "Camila"])411 assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"412 413 28 unmodified lines442 result = runner.invoke(app, ["main", "-h"])443 assert "Show this message and exit." in result.stdout444 445 306-def test_split_opt():307- prefix, opt = _split_opt("--verbose")308- assert prefix == "--"309- assert opt == "verbose"310-311- prefix, opt = _split_opt("//verbose")312- assert prefix == "//"313- assert opt == "verbose"314-315- prefix, opt = _split_opt("-verbose")316- assert prefix == "-"317- assert opt == "verbose"318-319- prefix, opt = _split_opt("verbose")320- assert prefix == ""321- assert opt == "verbose"322-323-446 def test_options_metadata_typer_default():447 app = typer.Typer(options_metavar="[options]")448 449 @app.command()12 unmodified linesadded:tests/test_progress_bar.py+397 added
1+"""2+Tests for the Progress bar functionality.3+Created after vendoring Click to ensure test coverage is back up to 100%.4+"""5+6+import io7+import shutil8+9+import pytest10+import typer11+from typer import progressbar12+from typer._click import _termui_impl13+from typer.testing import CliRunner14+15+runner = CliRunner()16+17+18+def _fake_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:19+ clock = [0.0]20+ monkeypatch.setattr(_termui_impl.time, "time", lambda: clock[0])21+ return clock22+23+24+def _pbar(**kw):25+ return progressbar(file=kw.pop("file", io.StringIO()), **kw)26+27+28+@pytest.mark.parametrize(29+ ("iterable", "length", "hidden", "label", "expected_count"),30+ [31+ (["a", "b"], None, False, "Processing", 2),32+ (None, 3, False, "Counting", 3),33+ (["x", "y"], None, True, "Hidden", 2),34+ ],35+)36+def test_progressbar(iterable, length, hidden, label, expected_count):37+ app = typer.Typer()38+39+ @app.command()40+ def main():41+ bar_out = io.StringIO()42+ count = 043+ with progressbar(44+ iterable, length=length, hidden=hidden, label=label, file=bar_out45+ ) as bar:46+ for _ in bar:47+ count += 148+ typer.echo(f"count={count}")49+ typer.echo(f"bar={bar_out.getvalue()!r}")50+51+ result = runner.invoke(app, [])52+ assert result.exit_code == 0, result.output53+ assert f"count={expected_count}" in result.stdout54+ assert (label in result.stdout) == (not hidden)55+56+57+@pytest.mark.parametrize(58+ ("label", "pbar_kw", "must_contain", "must_not_contain"),59+ [60+ pytest.param(61+ "TTY",62+ {63+ "show_pos": True,64+ "show_percent": True,65+ "item_show_func": lambda item: f"item={item}",66+ },67+ ("TTY", "1/1", "100%", "item=x"),68+ (),69+ ),70+ pytest.param(71+ "HeurPct",72+ {},73+ ("HeurPct", "100%"),74+ ("1/1",),75+ ),76+ pytest.param(77+ "HeurPos",78+ {"show_pos": True},79+ ("HeurPos", "1/1"),80+ ("100%",),81+ ),82+ ],83+)84+def test_progressbar_tty(85+ monkeypatch, label: str, pbar_kw: dict, must_contain, must_not_contain86+):87+ monkeypatch.setattr(_termui_impl, "isatty", lambda f: True)88+ _fake_clock(monkeypatch)89+90+ app = typer.Typer()91+92+ @app.command()93+ def main():94+ bar_out = io.StringIO()95+ with progressbar(96+ ["x"],97+ label=label,98+ file=bar_out,99+ bar_template="%(label)s %(info)s",100+ width=1,101+ **pbar_kw,102+ ) as bar:103+ for _ in bar:104+ pass105+ typer.echo(bar_out.getvalue())106+107+ result = runner.invoke(app, [])108+ assert result.exit_code == 0, result.output109+ for part in must_contain:110+ assert part in result.stdout111+ for part in must_not_contain:112+ assert part not in result.stdout113+114+115+def test_progressbar_tty_show_eta(monkeypatch):116+ monkeypatch.setattr(_termui_impl, "isatty", lambda f: True)117+ clock = _fake_clock(monkeypatch)118+ clock[0] = 1_000.0119+120+ app = typer.Typer()121+122+ @app.command()123+ def main():124+ bar_out = io.StringIO()125+ with progressbar(126+ ["a", "b"],127+ label="ETA",128+ file=bar_out,129+ show_pos=True,130+ show_percent=False,131+ show_eta=True,132+ bar_template="%(label)s %(info)s",133+ width=1,134+ ) as bar:135+ for i, _ in enumerate(bar):136+ if i == 0:137+ clock[0] = 1_001.0138+ typer.echo(bar_out.getvalue())139+140+ result = runner.invoke(app, [])141+ assert result.exit_code == 0, result.output142+ for part in ("ETA", "1/2", "00:00:01"):143+ assert part in result.stdout144+145+146+def test_progressbar_autowidth(monkeypatch):147+ monkeypatch.setattr(_termui_impl, "isatty", lambda f: True)148+ call = [0]149+ real_get_terminal_size = shutil.get_terminal_size150+151+ def fake_get_terminal_size(*args, **kwargs):152+ # Pytest (and others) call get_terminal_size(fallback=...); only stub no-arg calls153+ if args or kwargs:154+ return real_get_terminal_size(*args, **kwargs)155+ col = 120 if call[0] == 0 else 40156+ call[0] += 1157+ return type("TS", (), {"columns": col, "lines": 24})()158+159+ monkeypatch.setattr(shutil, "get_terminal_size", fake_get_terminal_size)160+161+ state: dict[str, object] = {}162+163+ app = typer.Typer()164+165+ @app.command()166+ def main():167+ out = io.StringIO()168+ with progressbar(["a", "b"], width=0, label="AW", file=out) as bar:169+ state["autowidth"] = bar.autowidth170+ for _ in bar:171+ pass172+ state["call_count"] = call[0]173+ state["out"] = out.getvalue()174+ typer.echo("done")175+176+ result = runner.invoke(app, [])177+ assert result.exit_code == 0, result.output178+ assert state["autowidth"] is True179+ assert state["call_count"] >= 2180+ out = str(state["out"])181+ assert "\r" in out and "AW" in out182+ assert "0%" in out and "50%" in out and "100%" in out183+184+185+def test_progress_bar_iter():186+ not_entered = _pbar(iterable=[1, 2], length=2)187+ with pytest.raises(RuntimeError, match="with block"):188+ iter(not_entered)189+190+ entered = _pbar(iterable=[10, 20], length=2)191+ with entered:192+ iterator = iter(entered)193+ assert next(iterator) == 10194+ assert next(entered) == 20195+ with pytest.raises(StopIteration):196+ next(iterator)197+198+199+def test_progress_bar_time(monkeypatch):200+ clock = _fake_clock(monkeypatch)201+ state: dict[str, object] = {}202+ clock[0] = 1_000.0203+204+ app = typer.Typer()205+206+ @app.command()207+ def main():208+ bar = _pbar(iterable=None, length=10)209+ state["tpi0"] = bar.time_per_iteration210+ clock[0] = 1_000.5211+ bar.make_step(1)212+ state["avg_after_one"] = list(bar.avg)213+ state["tpi_after_one"] = bar.time_per_iteration214+ clock[0] = 1_001.0215+ bar.make_step(1)216+ state["pos2"] = bar.pos217+ state["avg2"] = list(bar.avg)218+ state["tpi2"] = bar.time_per_iteration219+ clock[0] = 1_002.0220+ bar.make_step(1)221+ state["avg3"] = list(bar.avg)222+ state["tpi3"] = bar.time_per_iteration223+ typer.echo("ok")224+225+ result = runner.invoke(app, [])226+ assert result.exit_code == 0, result.output227+ assert state["tpi0"] == 0.0228+ assert state["avg_after_one"] == [] and state["tpi_after_one"] == 0.0229+ assert state["pos2"] == 2230+ assert state["avg2"] == [(1_001.0 - 1_000.0) / 2.0]231+ assert state["tpi2"] == pytest.approx(0.5)232+ assert state["avg3"] == [0.5, (1_002.0 - 1_000.0) / 3.0]233+ assert state["tpi3"] == pytest.approx(sum(state["avg3"]) / 2.0) # type: ignore[arg-type]234+235+236+def test_progress_bar_time_zero_steps(monkeypatch):237+ clock = _fake_clock(monkeypatch)238+ state: dict[str, object] = {}239+ clock[0] = 2_000.0240+241+ app = typer.Typer()242+243+ @app.command()244+ def main():245+ bar = _pbar(iterable=None, length=3)246+ clock[0] = 2_001.0247+ bar.make_step(0)248+ state["pos"] = bar.pos249+ state["avg"] = list(bar.avg)250+ state["tpi"] = bar.time_per_iteration251+ typer.echo("ok")252+253+ result = runner.invoke(app, [])254+ assert result.exit_code == 0, result.output255+ assert state["pos"] == 0256+ assert state["avg"] == [1.0]257+ assert state["tpi"] == pytest.approx(1.0)258+259+260+def test_progress_bar_eta(monkeypatch):261+ state: dict[str, object] = {}262+263+ app = typer.Typer()264+265+ @app.command()266+ def main():267+ state["eta0"] = _pbar(iterable=[1, 2], length=None).eta268+269+ done = _pbar(iterable=None, length=5)270+ done.pos, done.finished = 2, True271+ state["eta_done"] = done.eta272+273+ fresh = _pbar(iterable=None, length=5)274+ state["eta_known_fresh"] = fresh.eta_known275+ state["fmt_eta_fresh"] = fresh.format_eta()276+277+ clock = _fake_clock(monkeypatch)278+ clock[0] = 5_000.0279+ bar = _pbar(iterable=None, length=10)280+ clock[0] = 5_001.0281+ bar.make_step(3)282+ state["pos3"] = bar.pos283+ state["eta_after"] = bar.eta284+ state["tpi"] = bar.time_per_iteration285+286+ cases_out = []287+ for t0, t1, length, n_steps, _expected_fmt, expected_eta_int in (288+ (9_000.0, 9_001.0, 10, 1, "00:00:09", None),289+ (1_000.0, 100_000.0, 2, 1, "1d 03:30:00", 99_000),290+ ):291+ clock2 = _fake_clock(monkeypatch)292+ clock2[0] = t0293+ b = _pbar(iterable=None, length=length)294+ clock2[0] = t1295+ b.make_step(n_steps)296+ cases_out.append(297+ (298+ b.eta_known,299+ b.format_eta(),300+ int(b.eta) if expected_eta_int is not None else None,301+ )302+ )303+304+ state["cases"] = cases_out305+306+ clock3 = _fake_clock(monkeypatch)307+ clock3[0] = 3_000.0308+ b2 = _pbar(iterable=None, length=2)309+ clock3[0] = 3_001.0310+ b2.make_step(1)311+ state["fmt_before_finish"] = b2.format_eta()312+ b2.finish()313+ state["fmt_after_finish"] = b2.format_eta()314+ typer.echo("ok")315+316+ result = runner.invoke(app, [])317+ assert result.exit_code == 0, result.output318+ assert state["eta0"] == 0.0319+ assert state["eta_done"] == 0.0320+ assert not state["eta_known_fresh"] and state["fmt_eta_fresh"] == ""321+ assert state["pos3"] == 3322+ assert state["eta_after"] == pytest.approx(state["tpi"] * (10 - 3)) # type: ignore[operator]323+324+ (ek1, fmt1, ei1), (ek2, fmt2, ei2) = state["cases"] # type: ignore[misc]325+ assert ek1 and fmt1 == "00:00:09" and ei1 is None326+ assert ek2 and fmt2 == "1d 03:30:00" and ei2 == 99_000327+328+ assert state["fmt_before_finish"] != ""329+ assert state["fmt_after_finish"] == ""330+331+332+@pytest.mark.parametrize(333+ ("width", "fill_char", "empty_char", "expected_bar", "finished", "sample_timing"),334+ [335+ pytest.param(4, "X", "-", "XXXX", True, False, id="finished"),336+ pytest.param(4, "#", "-", "----", False, False, id="no_timing_yet"),337+ pytest.param(5, "*", ".", None, False, True, id="indeterminate"),338+ ],339+)340+def test_progress_bar_unknown_length(341+ monkeypatch,342+ width: int,343+ fill_char: str,344+ empty_char: str,345+ expected_bar: str | None,346+ finished: bool,347+ sample_timing: bool,348+):349+ clock: list[float] | None = _fake_clock(monkeypatch) if sample_timing else None350+ if clock is not None:351+ clock[0] = 100.0352+353+ state: dict[str, object] = {}354+355+ class _IterableWithoutLength:356+ def __iter__(self):357+ return iter((1, 2, 3))358+359+ app = typer.Typer()360+361+ @app.command()362+ def main():363+ bar = _pbar(364+ iterable=_IterableWithoutLength(),365+ length=None,366+ width=width,367+ fill_char=fill_char,368+ empty_char=empty_char,369+ )370+ assert bar.length is None371+372+ if sample_timing:373+ assert clock is not None374+ clock[0] = 101.0375+ bar.make_step(1)376+ assert bar.time_per_iteration > 0377+ rendered = bar.format_bar()378+ assert len(rendered) == width379+ assert rendered.count(fill_char) == 1380+ assert rendered.count(empty_char) == width - 1381+ state["branch"] = "sample_timing"382+ elif finished:383+ bar.finished = True384+ state["bar"] = bar.format_bar()385+ state["branch"] = "finished"386+ else:387+ assert bar.time_per_iteration == 0.0388+ state["bar"] = bar.format_bar()389+ state["branch"] = "no_timing"390+ typer.echo("ok")391+392+ result = runner.invoke(app, [])393+ assert result.exit_code == 0, result.output394+ if sample_timing:395+ assert state["branch"] == "sample_timing"396+ else:397+ assert state["bar"] == expected_baradded:tests/test_termui.py+458 added
1+"""2+Tests for the termui, echo, and CliRunner isolation functionality.3+Created after vendoring Click to ensure test coverage is back up to 100%.4+"""5+6+import io7+import os8+from contextlib import contextmanager9+from typing import Literal10+11+import pytest12+import typer13+from typer._click import _termui_impl, termui14+from typer.testing import CliRunner15+16+from tests.utils import needs_windows, skip_if_windows17+18+19+def test_raw_terminal(monkeypatch):20+ runner = CliRunner()21+ app = typer.Typer()22+ state = {"entered": 0, "exited": 0}23+24+ @contextmanager25+ def fake_raw_terminal():26+ state["entered"] += 127+ try:28+ yield 4229+ finally:30+ state["exited"] += 131+32+ monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw_terminal)33+34+ @app.command()35+ def main():36+ with termui.raw_terminal() as fd:37+ typer.echo(f"fd={fd}")38+39+ result = runner.invoke(app, [])40+ assert result.exit_code == 0, result.output41+ assert "fd=42" in result.stdout42+ assert state["entered"] == 143+ assert state["exited"] == 144+45+46+def test_getchar(monkeypatch):47+ # Cached path: call the existing _getchar directly.48+ cached_state = {"echo": None}49+50+ def cached_getchar(echo: bool) -> str:51+ cached_state["echo"] = echo52+ return "x"53+54+ monkeypatch.setattr(termui, "_getchar", cached_getchar)55+ assert termui.getchar(echo=True) == "x"56+ assert cached_state["echo"] is True57+58+ # Lazy-load path: _getchar is None, so import/cache _termui_impl.getchar.59+ lazy_state = {"calls": 0}60+61+ def lazy_getchar(echo: bool) -> str:62+ lazy_state["calls"] += 163+ return "y" if not echo else "z"64+65+ monkeypatch.setattr(termui, "_getchar", None)66+ monkeypatch.setattr(_termui_impl, "getchar", lazy_getchar)67+68+ assert termui.getchar(echo=False) == "y"69+ assert termui._getchar is lazy_getchar70+ assert termui.getchar(echo=True) == "z"71+ assert lazy_state["calls"] == 272+73+74+def test_clirunner_getchar(monkeypatch) -> None:75+ runner = CliRunner()76+ app = typer.Typer()77+78+ @app.command()79+ def main() -> None:80+ first = termui.getchar(echo=False)81+ second = termui.getchar(echo=True)82+ typer.echo(f"\nfirst={first};second={second}")83+84+ monkeypatch.setattr(termui, "_getchar", None)85+ result = runner.invoke(app, [], input="ab")86+ assert result.exit_code == 0, result.output87+ assert result.stdout.splitlines() == ["b", "first=a;second=b"]88+89+90+def test_clirunner_env_none(monkeypatch) -> None:91+ runner = CliRunner()92+ app = typer.Typer()93+ env_key = "TYPER_TEST_ENV_REMOVE"94+ monkeypatch.setenv(env_key, "present")95+96+ @app.command()97+ def main() -> None:98+ typer.echo(f"inside={os.environ.get(env_key)}")99+100+ result = runner.invoke(app, [], env={env_key: None})101+ assert result.exit_code == 0, result.output102+ assert "inside=None" in result.stdout103+ assert os.environ.get(env_key) == "present"104+105+106+@pytest.mark.parametrize(107+ ("runner_exc", "invoke_exc"),108+ [109+ (False, None),110+ (True, False),111+ ],112+)113+def test_clirunner_invoke_catch_exceptions(114+ runner_exc: bool, invoke_exc: bool | None115+) -> None:116+ runner = CliRunner(catch_exceptions=runner_exc)117+ app = typer.Typer()118+119+ @app.command()120+ def main() -> None:121+ raise RuntimeError("boom")122+123+ with pytest.raises(RuntimeError, match="boom"):124+ runner.invoke(app, [], catch_exceptions=invoke_exc)125+126+127+@pytest.mark.parametrize(128+ ("exit_value", "expected_exit_code", "expected_stdout"),129+ [130+ (None, 0, ""),131+ ("bad-exit", 1, "bad-exit\n"),132+ ],133+)134+def test_clirunner_invoke_system_exit_branches(135+ exit_value: object,136+ expected_exit_code: int,137+ expected_stdout: str,138+) -> None:139+ runner = CliRunner()140+ app = typer.Typer()141+142+ @app.command()143+ def main() -> None:144+ raise SystemExit(exit_value)145+146+ result = runner.invoke(app, [])147+ assert result.exit_code == expected_exit_code148+ assert result.stdout == expected_stdout149+ if expected_exit_code:150+ assert isinstance(result.exception, SystemExit)151+ else:152+ assert result.exception is None153+154+155+@needs_windows156+def test_termui_impl_windows_raw_terminal():157+ with _termui_impl.raw_terminal() as fd:158+ assert fd == -1159+ with termui.raw_terminal() as fd:160+ assert fd == -1161+162+163+@needs_windows164+def test_termui_impl_windows_getchar(monkeypatch):165+ monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "a")166+ monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: "b")167+ assert _termui_impl.getchar(echo=False) == "a"168+ assert _termui_impl.getchar(echo=True) == "b"169+170+ seq_null = iter(["\x00", "K"])171+ monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_null))172+ assert _termui_impl.getchar(echo=False) == "\x00K"173+174+ seq_e0 = iter(["\xe0", "H"])175+ monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_e0))176+ assert _termui_impl.getchar(echo=False) == "\xe0H"177+178+ seq_echo = iter(["\x00", "M"])179+ monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: next(seq_echo))180+ assert _termui_impl.getchar(echo=True) == "\x00M"181+182+ seq_e0_echo = iter(["\xe0", "Z"])183+ monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: next(seq_e0_echo))184+ assert _termui_impl.getchar(echo=True) == "\xe0Z"185+186+ monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x03")187+ with pytest.raises(KeyboardInterrupt):188+ _termui_impl.getchar(echo=False)189+190+ monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x1a")191+ with pytest.raises(EOFError):192+ _termui_impl.getchar(echo=False)193+194+195+@skip_if_windows196+@pytest.mark.parametrize("use_stdin_tty", [True, False])197+def test_termui_impl_posix_raw_terminal(monkeypatch, use_stdin_tty: bool):198+ state: dict[str, object] = {}199+ flushed: list[None] = []200+ fake_tty = None201+202+ if use_stdin_tty:203+ expected_fd = 14204+ old_termios = "old_settings"205+ monkeypatch.setattr(206+ _termui_impl, "isatty", lambda s: s is _termui_impl.sys.stdin207+ )208+ monkeypatch.setattr(_termui_impl.sys.stdin, "fileno", lambda: expected_fd)209+ else:210+ expected_fd = 27211+ old_termios = "old"212+ monkeypatch.setattr(213+ _termui_impl,214+ "isatty",215+ lambda s: s is not _termui_impl.sys.stdin,216+ )217+218+ class FakeTTY:219+ def __init__(self) -> None:220+ self.closed = False221+222+ def fileno(self) -> int:223+ return expected_fd224+225+ def close(self) -> None:226+ self.closed = True227+228+ fake_tty = FakeTTY()229+ real_open = open230+231+ def fake_open(path, *args, **kwargs):232+ if path == "/dev/tty":233+ return fake_tty234+ return real_open(path, *args, **kwargs) # pragma: no cover235+236+ monkeypatch.setattr("builtins.open", fake_open)237+238+ def tcgetattr(fd: int) -> str:239+ state["tcgetattr_fd"] = fd240+ return old_termios241+242+ def setraw(fd: int) -> None:243+ state["setraw_fd"] = fd244+245+ def tcsetattr(fd: int, when: int, old: str) -> None:246+ state["tcsetattr"] = (fd, when, old)247+248+ monkeypatch.setattr(_termui_impl.termios, "tcgetattr", tcgetattr)249+ monkeypatch.setattr(_termui_impl.tty, "setraw", setraw)250+ monkeypatch.setattr(_termui_impl.termios, "tcsetattr", tcsetattr)251+ monkeypatch.setattr(252+ _termui_impl.sys.stdout, "flush", lambda *a, **k: flushed.append(None)253+ )254+255+ with _termui_impl.raw_terminal() as fd:256+ assert fd == expected_fd257+258+ assert state["tcgetattr_fd"] == expected_fd259+ assert state["setraw_fd"] == expected_fd260+ assert state["tcsetattr"] == (261+ expected_fd,262+ _termui_impl.termios.TCSADRAIN,263+ old_termios,264+ )265+ assert flushed == [None]266+ if fake_tty is not None:267+ assert fake_tty.closed is True268+269+270+@skip_if_windows271+def test_termui_impl_posix_getchar(monkeypatch):272+ @contextmanager273+ def fake_raw():274+ yield 7275+276+ monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw)277+ monkeypatch.setattr(_termui_impl.os, "read", lambda fd, n: b"q")278+ monkeypatch.setattr(_termui_impl, "get_best_encoding", lambda stdin: "utf-8")279+ monkeypatch.setattr(_termui_impl, "isatty", lambda f: f is _termui_impl.sys.stdout)280+ written: list[str] = []281+ monkeypatch.setattr(_termui_impl.sys.stdout, "write", lambda s: written.append(s))282+283+ assert _termui_impl.getchar(echo=True) == "q"284+ assert written == ["q"]285+286+287+@skip_if_windows288+def test_termui_impl_posix_getchar_eof(monkeypatch):289+ @contextmanager290+ def fake_raw():291+ yield 5292+293+ monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw)294+ monkeypatch.setattr(_termui_impl.os, "read", lambda fd, n: b"\x04")295+ monkeypatch.setattr(_termui_impl, "get_best_encoding", lambda stdin: "utf-8")296+ monkeypatch.setattr(_termui_impl, "isatty", lambda f: False)297+298+ with pytest.raises(EOFError):299+ _termui_impl.getchar(echo=False)300+301+302+def test_prompt():303+ runner = CliRunner()304+ app = typer.Typer()305+ fake_file = io.StringIO("data")306+ fake_file.name = "demo.txt"307+308+ @app.command()309+ def main(310+ accept: bool = typer.Option(True, prompt=True),311+ name: str = typer.Option(..., prompt=True),312+ flavor: Literal["a", "b"] = typer.Option(..., prompt=True),313+ city: str = typer.Option("London", prompt=True),314+ config: str = typer.Option(fake_file, prompt=True),315+ password: str = typer.Option(316+ ...,317+ prompt=True,318+ hide_input=True,319+ confirmation_prompt=True,320+ ),321+ ):322+ typer.echo(323+ f"accept={accept};name={name};flavor={flavor};city={city};config={config};pass_len={len(password)}"324+ )325+326+ result = runner.invoke(app, [], input="\nAda\na\n\ncustom.ini\nsecret\nsecret\n")327+ assert result.exit_code == 0, result.output328+ assert (329+ "accept=True;name=Ada;flavor=a;city=London;config=custom.ini;pass_len=6"330+ in result.stdout331+ )332+ assert "(a, b): " in result.stdout333+ assert "[demo.txt]: " in result.stdout334+335+336+def test_hidden_prompt_func(monkeypatch):337+ monkeypatch.setattr("getpass.getpass", lambda prompt: "secret")338+ assert termui.hidden_prompt_func("Password: ") == "secret"339+340+341+def test_echo_stdout_missing(monkeypatch: pytest.MonkeyPatch) -> None:342+ monkeypatch.setattr("sys.stdout", None)343+ typer.echo("ignored")344+345+346+def test_echo_stringifies() -> None:347+ stream = io.StringIO()348+ typer.echo(123, file=stream, nl=False)349+ assert stream.getvalue() == "123"350+351+352+def test_echo_bytes() -> None:353+ buffer = io.BytesIO()354+ stream = io.TextIOWrapper(buffer, encoding="utf-8")355+ typer.echo(b"abc", file=stream, nl=True)356+ assert buffer.getvalue() == b"abc\n"357+358+359+def test_echo_empty_output() -> None:360+ class FlushTrackingTextStream(io.StringIO):361+ def __init__(self) -> None:362+ super().__init__()363+ self.flush_count = 0364+365+ def flush(self) -> None:366+ self.flush_count += 1367+ super().flush()368+369+ def write(self, s: str) -> int:370+ raise AssertionError("Empty output") # pragma: no cover371+372+ stream = FlushTrackingTextStream()373+ typer.echo("", file=stream, nl=False)374+ assert stream.flush_count == 1375+376+377+@needs_windows378+def test_echo_windows_color_none(379+ monkeypatch: pytest.MonkeyPatch,380+) -> None:381+ class TtyStream(io.StringIO):382+ def isatty(self) -> bool:383+ return True384+385+ stream = TtyStream()386+ monkeypatch.setattr("typer._click.utils.auto_wrap_for_ansi", None)387+ typer.echo("\x1b[31mred\x1b[0m", file=stream, nl=False, color=None)388+ assert stream.getvalue() == "red"389+390+391+@pytest.mark.parametrize(392+ ("flag", "true_code", "false_code"),393+ [394+ ("bold", "\x1b[1m", "\x1b[22m"),395+ ("dim", "\x1b[2m", "\x1b[22m"),396+ ("underline", "\x1b[4m", "\x1b[24m"),397+ ("overline", "\x1b[53m", "\x1b[55m"),398+ ("italic", "\x1b[3m", "\x1b[23m"),399+ ("blink", "\x1b[5m", "\x1b[25m"),400+ ("reverse", "\x1b[7m", "\x1b[27m"),401+ ("strikethrough", "\x1b[9m", "\x1b[29m"),402+ ],403+)404+def test_style(flag, true_code, false_code):405+ runner = CliRunner()406+ app = typer.Typer()407+408+ @app.command()409+ def main():410+ # testing an int and a str on purpose411+ typer.echo("TRUE=" + typer.style("42", **{flag: True}), color=True)412+ typer.echo("FALSE=" + typer.style(666, **{flag: False}), color=True)413+414+ result = runner.invoke(app, [])415+ assert result.exit_code == 0, result.output416+ lines = [line for line in result.stdout.splitlines() if line]417+ true_line = next(line for line in lines if line.startswith("TRUE="))418+ false_line = next(line for line in lines if line.startswith("FALSE="))419+ assert "42" in true_line420+ assert "666" in false_line421+422+ assert true_code in true_line423+ assert true_code not in false_line424+ assert false_code in false_line425+ assert false_code not in true_line426+427+428+def test_style_color():429+ fg_int = typer.style("x", fg=123)430+ assert "\x1b[38;5;123m" in fg_int431+432+ bg_list = typer.style("x", bg=[1, 2, 3])433+ assert "\x1b[48;2;1;2;3m" in bg_list434+435+ with pytest.raises(TypeError, match="Unknown color"):436+ typer.style("x", fg="not-a-color")437+438+ with pytest.raises(TypeError, match="Unknown color"):439+ typer.style("x", bg="not-a-color")440+441+442+def test_termui_launch(monkeypatch):443+ captured = {}444+445+ def fake_open_url(url, wait=False, locate=False):446+ captured["url"] = url447+ captured["wait"] = wait448+ captured["locate"] = locate449+ return 7450+451+ monkeypatch.setattr(_termui_impl, "open_url", fake_open_url)452+ rv = termui.launch("https://example.com", wait=True, locate=True)453+ assert rv == 7454+ assert captured == {455+ "url": "https://example.com",456+ "wait": True,457+ "locate": True,458+ }modified:tests/test_type_conversion.py+234 added-4 removed
1+import os2 from enum import Enum3 from pathlib import Path4 from typing import Any5 5-import click6 import pytest7 import typer8+from typer import _click, models9 from typer.testing import CliRunner10 11+from tests.utils import needs_linux, needs_windows12+13 runner = CliRunner()14 15 16 def test_optional():118 unmodified lines135 result = runner.invoke(app, ["one", "two"])136 assert result.exit_code == 0137 138 139+def test_tuple_wrong_arity():140+ app = typer.Typer()141+142+ @app.command()143+ def tuple_arity(value: tuple[str, str] = typer.Option(...)):144+ print(value) # pragma: no cover145+146+ result = runner.invoke(app, [], default_map={"value": ("only-one",)})147+ assert result.exit_code == 2148+ assert "2 values are required, but 1 given." in result.output149+150+151 def test_custom_parse():152 app = typer.Typer()153 154 @app.command()5 unmodified lines160 result = runner.invoke(app, ["0x56"])161 assert result.exit_code == 0162 163 164+def test_custom_parse_value_error():165+ app = typer.Typer()166+167+ @app.command()168+ def custom_parser(169+ hex_value: int = typer.Argument(None, parser=lambda x: int(x, 0)),170+ ):171+ print(hex_value) # pragma: no cover172+173+ result = runner.invoke(app, ["not-a-hex"])174+ assert result.exit_code == 2175+ assert "Invalid value" in result.output176+177+178 def test_custom_click_type():150- class BaseNumberParamType(click.ParamType):179+ class BaseNumberParamType(_click.types.ParamType):180 name = "base_integer"181 182 def convert(183 self,184 value: Any,156- param: click.Parameter | None,157- ctx: click.Context | None,185+ param: _click.Parameter | None,186+ ctx: _click.Context | None,187 ) -> Any:188 return int(value, 0)189 190 app = typer.Typer()5 unmodified lines196 assert hex_value == 0x56197 198 result = runner.invoke(app, ["0x56"])199 assert result.exit_code == 0200+201+202+def test_int_range_open_bound_clamp():203+ app = typer.Typer()204+205+ @app.command()206+ def custom_click_type(207+ value: int = typer.Argument(208+ ...,209+ click_type=_click.types.IntRange(min=1, min_open=True, clamp=True),210+ ),211+ ):212+ print(value)213+214+ result = runner.invoke(app, ["1"])215+ assert result.exit_code == 0216+ assert "2" in result.output217+218+219+def test_bool_convert_invalid():220+ app = typer.Typer()221+222+ @app.command()223+ def main(value: bool):224+ print(value) # pragma: no cover225+226+ result = runner.invoke(app, ["maybe"])227+ assert result.exit_code == 2228+ assert "is not a valid boolean" in result.output229+ assert "yes" in result.output230+ assert "false" in result.output231+232+233+@pytest.mark.parametrize(234+ ("arg_enc", "system_enc", "raw_value", "expected_output"),235+ [236+ pytest.param("latin-1", "utf-8", b"\xff", "ÿ"),237+ pytest.param("ascii", "latin-1", b"\xff", "ÿ"),238+ pytest.param("ascii", "utf-16", b"\xff", "�"),239+ pytest.param("ascii", "ascii", b"\xff", "�"),240+ ],241+)242+def test_string_param_type_converts_bytes(243+ monkeypatch: pytest.MonkeyPatch,244+ arg_enc: str,245+ system_enc: str,246+ raw_value: bytes,247+ expected_output: str,248+):249+ app = typer.Typer()250+251+ @app.command()252+ def show(name: str = typer.Option(...)):253+ print(name)254+255+ command = typer.main.get_command(app)256+ name_param = next(param for param in command.params if param.name == "name")257+ assert repr(name_param.type) == "STRING"258+259+ monkeypatch.setattr(_click.types, "_get_argv_encoding", lambda: arg_enc)260+ monkeypatch.setattr(_click.types.sys, "getfilesystemencoding", lambda: system_enc)261+262+ result = runner.invoke(app, [], default_map={"name": raw_value})263+ assert result.exit_code == 0264+ assert expected_output in result.output265+266+267+@pytest.mark.parametrize("path_type", [str, bytes, Path])268+def test_path_coerced(path_type) -> None:269+ # Ensure coerce_path_result works correctly270+ app = typer.Typer()271+272+ @app.command()273+ def show(path: Any = typer.Option(..., path_type=path_type)):274+ print(path)275+276+ result = runner.invoke(app, ["--path", "dir/my_awesome_file.txt"])277+ assert result.exit_code == 0278+ assert "my_awesome_file" in result.output279+280+281+@pytest.mark.parametrize(282+ ("create_file", "option_kwargs", "deny_mode", "expected_error"),283+ [284+ (True, {"file_okay": False, "dir_okay": True}, None, "is a file"),285+ (False, {"file_okay": True, "dir_okay": False}, None, "is a directory"),286+ (True, {"readable": True}, os.R_OK, "is not readable"),287+ (True, {"readable": False, "writable": True}, os.W_OK, "is not writable"),288+ ],289+)290+def test_path_convert_failures(291+ monkeypatch: pytest.MonkeyPatch,292+ tmp_path: Path,293+ create_file: bool,294+ option_kwargs: dict[str, bool],295+ deny_mode: int | None,296+ expected_error: str,297+) -> None:298+ app = typer.Typer()299+300+ @app.command()301+ def show(path: Path = typer.Option(..., **option_kwargs)):302+ print(path) # pragma: no cover303+304+ if deny_mode is not None:305+ original_access = os.access306+307+ def fake_access(path: str, mode: int) -> bool:308+ if mode == deny_mode:309+ return False310+ return original_access(path, mode) # pragma: no cover311+312+ monkeypatch.setattr(models.os, "access", fake_access)313+314+ path = tmp_path / "some_path"315+ if create_file:316+ path.write_text("hello")317+ else:318+ path.mkdir()319+ result = runner.invoke(app, ["--path", str(path)])320+321+ assert result.exit_code != 0322+ assert expected_error in result.output323+324+325+def test_convert_type():326+ from typer._click.types import convert_type327+328+ # str329+ assert convert_type(str) is _click.types.STRING330+ assert convert_type(None) is _click.types.STRING331+ assert convert_type(None, default=["a"]) is _click.types.STRING332+333+ # tuples334+ tuple_type = convert_type((str, int))335+ assert isinstance(tuple_type, _click.types.Tuple)336+ assert [type(item) for item in tuple_type.types] == [337+ type(_click.types.STRING),338+ type(_click.types.INT),339+ ]340+341+ guessed_tuple = convert_type(None, default=[(1, "x")])342+ assert isinstance(guessed_tuple, _click.types.Tuple)343+ assert [type(item) for item in guessed_tuple.types] == [344+ type(_click.types.INT),345+ type(_click.types.STRING),346+ ]347+348+ # numbers349+ assert convert_type(int) is _click.types.INT350+ assert convert_type(float) is _click.types.FLOAT351+ assert convert_type(bool) is _click.types.BOOL352+353+ param_type = _click.types.IntRange(min=0, max=10)354+ assert convert_type(param_type) is param_type355+356+ guessed_int = convert_type(None, default=42)357+ assert guessed_int is _click.types.INT358+359+ # custom type360+ class CustomType:361+ pass362+363+ guessed_unknown = convert_type(None, default=CustomType())364+ assert guessed_unknown is _click.types.STRING365+366+ func_type = convert_type(CustomType)367+ assert isinstance(func_type, _click.types.FuncParamType)368+ assert func_type.name == "CustomType"369+370+371+@pytest.mark.parametrize(372+ ("platform_case", "stdin_encoding", "filesystem_encoding"),373+ [374+ pytest.param("windows", None, "utf-8", marks=needs_windows),375+ pytest.param("linux", "latin-1", "utf-8", marks=needs_linux),376+ pytest.param("linux", None, "latin-1", marks=needs_linux),377+ ],378+)379+def test_argv_encoding(380+ monkeypatch: pytest.MonkeyPatch,381+ platform_case: str,382+ stdin_encoding: str | None,383+ filesystem_encoding: str,384+) -> None:385+ sys = _click._compat.sys386+ if platform_case == "windows":387+ import locale388+389+ monkeypatch.setattr(locale, "getpreferredencoding", lambda: "latin-1")390+ else:391+392+ class FakeStdin:393+ def __init__(self, encoding: str | None) -> None:394+ self.encoding = encoding395+396+ monkeypatch.setattr(sys, "stdin", FakeStdin(stdin_encoding))397+ monkeypatch.setattr(sys, "getfilesystemencoding", lambda: filesystem_encoding)398+399+ converted = _click.types.STRING.convert(b"\xff", None, None)400+ assert converted == "ÿ"added:tests/test_types_file.py+395 added
1+import subprocess2+import sys3+from io import BytesIO, StringIO, TextIOWrapper4+from pathlib import Path5+6+import pytest7+import typer8+from typer._click._compat import get_best_encoding, should_strip_ansi9+from typer._click.testing import make_input_stream10+from typer._click.utils import PacifyFlushWrapper11+from typer.testing import CliRunner12+13+from tests.utils import needs_linux, needs_windows14+15+app = typer.Typer()16+17+18+@app.command()19+def read_text(file_in: typer.FileText = typer.Option(..., lazy=True)):20+ data = file_in.read()21+ typer.echo(f"text-len={len(data)}")22+23+24+@app.command()25+def write_text(file_out: typer.FileTextWrite = typer.Option(..., lazy=None)):26+ file_out.write("This is a single line\n")27+ typer.echo("1 line written")28+29+30+@app.command()31+def write_lazy(file_out: typer.FileTextWrite = typer.Option(..., lazy=True)):32+ file_out.write("This is a single lazy line\n")33+ typer.echo("1 line written")34+35+36+@app.command()37+def probe_lazy_file_behaviors(38+ file_in: typer.FileText = typer.Option(..., lazy=True),39+ file_out: typer.FileTextWrite = typer.Option(..., lazy=True),40+):41+ typer.echo(f"repr-before={repr(file_out)}")42+ file_out.write("repr-opened\n")43+ typer.echo(f"repr-after={repr(file_out)}")44+ with file_in as stream:45+ typer.echo(f"context-len={len(stream.read())}")46+ stream.seek(0)47+ first_line = next(iter(stream), "")48+ typer.echo(f"first-line={first_line.rstrip()}")49+50+51+@app.command()52+def write_binary(file_out: typer.FileBinaryWrite = typer.Option(...)):53+ file_out.write(b"binary-written\n")54+55+56+@app.command()57+def write_binary_stderr():58+ stream = typer.get_binary_stream("stderr")59+ stream.write(b"binary-stderr\n")60+ stream.flush()61+62+63+@app.command()64+def read_binary(file_in: typer.FileBinaryRead = typer.Option(...)):65+ data = file_in.read()66+ typer.echo(f"binary-len={len(data)}")67+68+69+runner = CliRunner()70+71+72+def test_text_stdin_dash() -> None:73+ result = runner.invoke(app, ["read-text", "--file-in=-"], input="hello\n")74+ assert result.exit_code == 075+ assert "text-len=6" in result.output76+77+78+def test_lazy_file(tmp_path: Path) -> None:79+ # dash: written to stdout80+ result = runner.invoke(app, ["write-text", "--file-out=-"])81+ assert result.exit_code == 082+ assert "This is a single line" in result.output83+ assert "1 line written" in result.output84+85+ # lazy + file86+ file_path = tmp_path / "example.txt"87+ result = runner.invoke(app, ["write-lazy", f"--file-out={file_path}"])88+ assert result.exit_code == 089+ assert "This is a single lazy line" not in result.output90+ assert "1 line written" in result.output91+ assert file_path.exists()92+ assert file_path.read_text() == "This is a single lazy line\n"93+94+ # lazy probe: unopened/opened repr, context manager, and iteration.95+ result = runner.invoke(96+ app,97+ [98+ "probe-lazy-file-behaviors",99+ f"--file-in={file_path}",100+ f"--file-out={tmp_path / 'repr-opened.txt'}",101+ ],102+ )103+ assert result.exit_code == 0104+ assert "repr-before=<unopened file" in result.output105+ assert "repr-after=<unopened file" not in result.output106+ assert "repr-opened.txt" in result.output107+ assert "context-len=27" in result.output108+ assert "first-line=This is a single lazy line" in result.output109+110+ # lazy + dash: written to stdout (lazy setting is pretty much ignored)111+ result = runner.invoke(app, ["write-lazy", "--file-out=-"])112+ assert result.exit_code == 0113+ assert "This is a single lazy line" in result.output114+ assert "1 line written" in result.output115+116+117+def test_filelike_conversion() -> None:118+ stream = StringIO()119+ result = runner.invoke(120+ app, ["write-text"], default_map={"write-text": {"file_out": stream}}121+ )122+ assert result.exit_code == 0123+ assert "1 line written" in result.output124+ assert stream.getvalue() == "This is a single line\n"125+126+127+def test_input_stream() -> None:128+ binary_stream = BytesIO(b"hello")129+ converted = make_input_stream(binary_stream, charset="utf-8")130+ assert converted is binary_stream131+132+ text_stream = TextIOWrapper(BytesIO(b"hello"), encoding="utf-8")133+ converted = make_input_stream(text_stream, charset="utf-8")134+ assert converted is text_stream.buffer135+136+137+def test_binary_dash() -> None:138+ result = runner.invoke(app, ["write-binary", "--file-out=-"])139+ assert result.exit_code == 0140+ assert result.stdout_bytes == b"binary-written\n"141+142+ result = runner.invoke(143+ app, ["read-binary", "--file-in=-"], input=b"\x00\x01\x02abc"144+ )145+ assert result.exit_code == 0146+ assert "binary-len=6" in result.output147+148+149+def test_binary_stderr() -> None:150+ result = subprocess.run(151+ [152+ sys.executable,153+ "-c",154+ "from tests.test_types_file import app; app()",155+ "write-binary-stderr",156+ ],157+ capture_output=True,158+ )159+ assert result.returncode == 0160+ assert result.stderr == b"binary-stderr\n"161+162+163+@pytest.mark.parametrize(164+ ("errors_arg", "expected_errors"),165+ [166+ (None, "replace"),167+ ("strict", "strict"),168+ ],169+)170+def test_get_text_stream_errors(171+ monkeypatch,172+ errors_arg: str | None,173+ expected_errors: str,174+) -> None:175+ class BinaryStdout(BytesIO):176+ pass177+178+ binary_stdout = BinaryStdout()179+ monkeypatch.setattr(sys, "stdout", binary_stdout)180+181+ text_stream = typer.get_text_stream("stdout", encoding=None, errors=errors_arg)182+ text_stream.write("stream-text")183+ text_stream.flush()184+185+ assert text_stream.errors == expected_errors186+ assert text_stream.writable() is True187+ assert binary_stdout.getvalue() == b"stream-text"188+189+190+def test_get_best_encoding() -> None:191+ """Test that ASCII is being transformed into UTF-8"""192+193+ class AsciiStream:194+ encoding = "ascii"195+196+ class Utf8Stream:197+ encoding = "utf-8"198+199+ class UnknownStream:200+ encoding = "unknown"201+202+ assert get_best_encoding(AsciiStream()) == "utf-8"203+ assert get_best_encoding(Utf8Stream()) == "utf-8"204+ assert get_best_encoding(UnknownStream()) == "unknown"205+206+207+def test_pacify_flush_wrapper() -> None:208+ class Wrapped:209+ def __init__(self) -> None:210+ self.name = "wrapped-stream"211+212+ def flush(self) -> None:213+ return None # pragma: no cover214+215+ wrapped = PacifyFlushWrapper(Wrapped())216+ assert wrapped.name == "wrapped-stream"217+218+219+def test_text_stream_isatty(monkeypatch) -> None:220+ class BinaryStdout(BytesIO):221+ def isatty(self) -> bool:222+ return True223+224+ binary_stdout = BinaryStdout()225+ monkeypatch.setattr(sys, "stdout", binary_stdout)226+ text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors=None)227+ assert text_stream.isatty() is True228+229+230+def test_text_stream_buffer_read1(monkeypatch) -> None:231+ class BinaryStdinNoRead1:232+ def __init__(self, data: bytes) -> None:233+ self._data = data234+ self._pos = 0235+236+ def read(self, size: int = -1) -> bytes:237+ if size < 0:238+ size = len(self._data) - self._pos # pragma: no cover239+ chunk = self._data[self._pos : self._pos + size]240+ self._pos += len(chunk)241+ return chunk242+243+ binary_stdin = BinaryStdinNoRead1(b"hello")244+ monkeypatch.setattr(sys, "stdin", binary_stdin)245+ text_stream = typer.get_text_stream("stdin", encoding="utf-8", errors=None)246+ assert text_stream._stream.read1(4) == b"hell"247+248+249+def test_binary_stream(monkeypatch) -> None:250+ binary_stdin = BytesIO(b"hello")251+ binary_stdout = BytesIO()252+ monkeypatch.setattr(sys, "stdin", binary_stdin)253+ monkeypatch.setattr(sys, "stdout", binary_stdout)254+255+ assert typer.get_binary_stream("stdin") is binary_stdin256+ assert typer.get_binary_stream("stdout") is binary_stdout257+258+259+def test_binary_stream_raises(monkeypatch) -> None:260+ class TextOnlyStdin:261+ def read(self, n: int = -1) -> str:262+ return "hello"263+264+ monkeypatch.setattr(sys, "stdin", TextOnlyStdin())265+ with pytest.raises(RuntimeError, match="Was not able to determine binary stream"):266+ typer.get_binary_stream("stdin")267+268+269+def test_stream_unknown() -> None:270+ with pytest.raises(TypeError, match="Unknown standard stream 'Plumbus'"):271+ typer.get_binary_stream("Plumbus") # type: ignore[arg-type]272+273+ with pytest.raises(TypeError, match="Unknown standard stream 'Fleeb'"):274+ typer.get_text_stream("Fleeb") # type: ignore[arg-type]275+276+277+def test_format_filename() -> None:278+ filename = b"folder/subdir/demo.txt"279+ assert typer.format_filename(filename, shorten=True) == "demo.txt"280+281+282+def test_file_error(monkeypatch, tmp_path: Path) -> None:283+ file_path = tmp_path / "cannot-open.txt"284+285+ def fake_open(path, *args, **kwargs):286+ if Path(path) == file_path:287+ raise OSError()288+289+ monkeypatch.setattr("builtins.open", fake_open)290+ result = runner.invoke(app, ["write-text", f"--file-out={file_path}"])291+ assert result.exit_code == 1292+ assert "Could not open file" in result.output293+ assert "cannot-open.txt" in result.output294+ assert "unknown error" in result.output295+296+297+@needs_windows298+def test_app_dir_windows_fallback(299+ monkeypatch: pytest.MonkeyPatch,300+) -> None:301+ monkeypatch.delenv("APPDATA", raising=False)302+ monkeypatch.setattr("os.path.expanduser", lambda _path: r"C:\Users\Tester")303+304+ assert typer.get_app_dir("My App", roaming=True) == r"C:\Users\Tester\My App"305+306+307+@needs_linux308+def test_app_dir_force_posix(monkeypatch: pytest.MonkeyPatch) -> None:309+ monkeypatch.setattr("os.path.expanduser", lambda _path: "/home/tester/.my-app")310+311+ assert typer.get_app_dir("My App", force_posix=True) == "/home/tester/.my-app"312+313+314+def test_text_stream_binary_buffer(monkeypatch) -> None:315+ class TextStdinWithBinaryBuffer:316+ def __init__(self, data: bytes) -> None:317+ self.buffer = BytesIO(data)318+ self.encoding = "latin-1"319+320+ def read(self, n: int = -1) -> str:321+ raise OSError("text stream is not readable directly")322+323+ class TextStdoutWithBinaryBuffer:324+ def __init__(self) -> None:325+ self.buffer = BytesIO()326+ self.encoding = "latin-1"327+328+ def write(self, s: str) -> int:329+ raise OSError("text stream is not writable directly")330+331+ stdin = TextStdinWithBinaryBuffer(b"hello")332+ stdout = TextStdoutWithBinaryBuffer()333+334+ monkeypatch.setattr(sys, "stdin", stdin)335+ monkeypatch.setattr(sys, "stdout", stdout)336+337+ text_stdin = typer.get_text_stream("stdin", encoding="utf-8", errors=None)338+ text_stdout = typer.get_text_stream("stdout", encoding="utf-8", errors=None)339+340+ assert text_stdin.read() == "hello"341+ text_stdout.write("ok")342+ text_stdout.flush()343+ assert stdout.buffer.getvalue() == b"ok"344+345+346+def test_text_stream_binary_stream(monkeypatch) -> None:347+ binary_stdout = BytesIO()348+ monkeypatch.setattr(sys, "stdout", binary_stdout)349+ text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors=None)350+ text_stream.write("ok")351+ text_stream.flush()352+ assert binary_stdout.getvalue() == b"ok"353+354+355+def test_text_stream_stdout_no_binary(356+ monkeypatch,357+) -> None:358+ class TextStdoutNoBinaryFallback:359+ encoding = "utf-8"360+ errors = "strict"361+362+ def write(self, s: str) -> int:363+ if isinstance(s, bytes):364+ raise TypeError("bytes not supported")365+ return len(s)366+367+ stdout = TextStdoutNoBinaryFallback()368+ monkeypatch.setattr(sys, "stdout", stdout)369+ text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors="replace")370+ assert text_stream is stdout371+372+373+def test_jupyter_wrapped_stream(monkeypatch) -> None:374+ class JupyterLikeStdout(BytesIO):375+ __module__ = "ipykernel.iostream"376+377+ def isatty(self) -> bool:378+ return False379+380+ binary_stdout = JupyterLikeStdout()381+ monkeypatch.setattr(sys, "stdout", binary_stdout)382+ text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors=None)383+ assert should_strip_ansi(text_stream, color=None) is False384+385+386+def test_should_strip_ansi(monkeypatch) -> None:387+ class NonTtyStdin(BytesIO):388+ def isatty(self) -> bool:389+ return False390+391+ stdin = NonTtyStdin()392+ monkeypatch.setattr(sys, "stdin", stdin)393+ assert should_strip_ansi(stream=None, color=None) is True394+ assert should_strip_ansi(stream=None, color=True) is False395+ assert should_strip_ansi(stream=None, color=False) is Truemodified:tests/test_types.py+92 added-5 removed
1 from enum import Enum2 3+import pytest4 import typer5+from typer import _click6 from typer.testing import CliRunner7 8 app = typer.Typer(context_settings={"token_normalize_func": str.lower})9 3 unmodified lines13 morty = "Morty"14 15 16 @app.command()15-def hello(name: User = User.rick) -> None:17+def hello_option(name: User = User.rick) -> None:18 print(f"Hello {name.value}!")19 20 21+@app.command()22+def hello_argument(name: User) -> None:23+ print(f"Hello {name.value}!")24+25+26+@app.command()27+def hello_no_choices(28+ name: User = typer.Option(..., "--name", show_choices=False),29+):30+ print(f"Hello {name.value}!")31+32+33+@app.command()34+def hello_all(names: list[str] = typer.Argument(["World"], envvar="NAMES")) -> None:35+ for name in names:36+ print(f"Hello {name}!")37+38+39+@app.command()40+def split_variadic_and_pair(items: list[str], pair: tuple[str, str]) -> None:41+ print(f"items={items}")42+ print(f"pair={pair}")43+44+45 runner = CliRunner()46 47 48 def test_enum_choice() -> None:23- # This test is only for coverage of the new custom TyperChoice class24- result = runner.invoke(app, ["--name", "morty"], catch_exceptions=False)49+ result = runner.invoke(50+ app, ["hello-option", "--name", "morty"], catch_exceptions=False51+ )52 assert result.exit_code == 053 assert "Hello Morty!" in result.output54 28- result = runner.invoke(app, ["--name", "Rick"])55+ result = runner.invoke(app, ["hello-option", "--name", "Rick"])56 assert result.exit_code == 057 assert "Hello Rick!" in result.output58 32- result = runner.invoke(app, ["--name", "RICK"])59+ result = runner.invoke(app, ["hello-option", "--name", "RICK"])60 assert result.exit_code == 061 assert "Hello Rick!" in result.output62+63+ result = runner.invoke(app, ["hello-no-choices", "--name", "RICK"])64+ assert result.exit_code == 065+ assert "Hello Rick!" in result.output66+67+ result = runner.invoke(app, ["hello-argument", "RICK"])68+ assert result.exit_code == 069+ assert "Hello Rick!" in result.output70+71+72+def test_enum_choice_repr() -> None:73+ root_command = typer.main.get_command(app)74+ command = root_command.commands["hello-option"]75+ name_param = next(param for param in command.params if param.name == "name")76+ assert repr(name_param.type).startswith("Choice([")77+78+79+def test_enum_choice_help() -> None:80+ result = runner.invoke(app, ["hello-argument", "--help"])81+ assert result.exit_code == 082+ assert "{rick|morty}" in result.output83+84+ result = runner.invoke(app, ["hello-option", "--help"])85+ assert result.exit_code == 086+ assert "[rick|morty]" in result.output87+88+ result = runner.invoke(app, ["hello-no-choices", "--help"])89+ assert result.exit_code == 090+ assert "--name" in result.output91+ assert "rick|morty" not in result.output92+93+94+def test_enum_choice_missing_message() -> None:95+ result = runner.invoke(app, ["hello-argument"])96+ assert result.exit_code != 097+ assert "Missing argument" in result.output98+ assert "Choose from:" in result.output99+ assert "rick" in result.output100+ assert "morty" in result.output101+102+103+def test_split_envvar_value(monkeypatch) -> None:104+ # This will use split_envvar_value to produce two strings from the envvar105+ monkeypatch.setenv("NAMES", "Rick Morty")106+ result = runner.invoke(app, ["hello-all"])107+ assert result.exit_code == 0108+ assert "Hello Rick!" in result.output109+ assert "Hello Morty!" in result.output110+111+112+def test_list_pair() -> None:113+ result = runner.invoke(app, ["split-variadic-and-pair", "a", "b", "c", "x", "y"])114+ assert result.exit_code == 0115+ assert "items=['a', 'b', 'c']" in result.output116+ assert "pair=('x', 'y')" in result.output117+118+119+def test_float_range_open_bounds_with_clamp_not_allowed():120+ with pytest.raises(TypeError, match="Clamping is not supported for open bounds."):121+ _click.types.FloatRange(min=0.0, min_open=True, clamp=True)added:tests/test_win_console.py+326 added
1+"""2+Tests for the Windows console functionality.3+Created after vendoring Click to ensure test coverage is back up to 100%.4+"""5+6+import ctypes7+import io8+import sys9+10+import pytest11+import typer12+from typer.testing import CliRunner13+14+from .utils import needs_windows15+16+pytestmark = needs_windows17+18+19+if sys.platform == "win32":20+ from typer._click import _compat, _winconsole21+22+23+def _identity_buffer(obj, writable=False): # noqa: ARG00124+ return obj25+26+27+def _route_console_stream(target_name, wrapper, state=None):28+ def patched_windows_stream(stream, encoding, errors): # noqa: ARG00129+ current_target = getattr(sys, target_name)30+ if stream is current_target:31+ if state is not None and target_name == "stderr":32+ state["stderr_wrap_calls"] += 133+ buffer = getattr(stream, "buffer", None)34+ return wrapper(buffer) if buffer else None35+ return None36+37+ return patched_windows_stream38+39+40+def _capture_write_console(state):41+ def fake_write_console(handle, buffer, units_to_write, units_written_ptr, reserved): # noqa: ARG00142+ state["write_calls"] += 143+ bytes_to_write = units_to_write * 244+ state["written"].extend(buffer[:bytes_to_write])45+ units_written_ptr._obj.value = units_to_write46+ return 147+48+ return fake_write_console49+50+51+def test_winconsole_stdin(monkeypatch):52+ runner = CliRunner()53+ app = typer.Typer()54+55+ @app.command()56+ def read_name(config: typer.FileText = typer.Option(...)) -> None:57+ name = config.readline().strip()58+ typer.echo(f"Hello {name}")59+60+ utf16_data = bytearray("Rick\r\n".encode("utf-16-le"))61+ state = {"pos": 0, "read_calls": 0}62+63+ def fake_read_console(handle, buffer, units_to_read, units_read_ptr, reserved): # noqa: ARG00164+ state["read_calls"] += 165+ max_bytes = units_to_read * 266+ chunk = utf16_data[state["pos"] : state["pos"] + max_bytes]67+ if chunk:68+ buffer[0 : len(chunk)] = chunk69+ state["pos"] += len(chunk)70+ units_read_ptr._obj.value = len(chunk) // 271+ return 172+73+ return 1 # pragma: no cover74+75+ monkeypatch.setattr(_winconsole, "get_buffer", _identity_buffer)76+ monkeypatch.setattr(_winconsole, "ReadConsoleW", fake_read_console)77+ monkeypatch.setattr(_winconsole, "GetLastError", lambda: 0)78+ monkeypatch.setattr(79+ _compat,80+ "_get_windows_console_stream",81+ _route_console_stream("stdin", _winconsole._get_text_stdin),82+ )83+84+ result = runner.invoke(app, ["--config", "-"])85+ assert result.exit_code == 0, result.output86+ assert "Hello Rick" in result.stdout87+ assert state["read_calls"] > 088+89+90+def test_winconsole_stdout(monkeypatch):91+ runner = CliRunner()92+ app = typer.Typer()93+ state = {"write_calls": 0, "written": bytearray()}94+95+ @app.command()96+ def write_message(out: typer.FileTextWrite = typer.Option(...)) -> None:97+ out.write("Hello Summer\n")98+99+ monkeypatch.setattr(_winconsole, "get_buffer", _identity_buffer)100+ monkeypatch.setattr(_winconsole, "WriteConsoleW", _capture_write_console(state))101+ monkeypatch.setattr(_winconsole, "GetLastError", lambda: 0)102+ monkeypatch.setattr(103+ _compat,104+ "_get_windows_console_stream",105+ _route_console_stream("stdout", _winconsole._get_text_stdout),106+ )107+108+ result = runner.invoke(app, ["--out", "-"])109+ assert result.exit_code == 0, result.output110+ assert state["write_calls"] > 0111+ assert _winconsole._WindowsConsoleWriter(1).isatty() is True112+ decoded = state["written"].decode("utf-16-le", errors="ignore")113+ assert "Hello Summer\r\n" in decoded114+115+116+def test_winconsole_stderr(monkeypatch):117+ runner = CliRunner()118+ app = typer.Typer()119+ state = {"write_calls": 0, "written": bytearray(), "stderr_wrap_calls": 0}120+121+ @app.command()122+ def main() -> None:123+ typer.echo("Ran out of adventure time!", err=True)124+125+ monkeypatch.setattr(_winconsole, "get_buffer", _identity_buffer)126+ monkeypatch.setattr(_winconsole, "WriteConsoleW", _capture_write_console(state))127+ monkeypatch.setattr(_winconsole, "GetLastError", lambda: 0)128+ monkeypatch.setattr(129+ _compat,130+ "_get_windows_console_stream",131+ _route_console_stream("stderr", _winconsole._get_text_stderr, state),132+ )133+134+ result = runner.invoke(app)135+ assert result.exit_code == 0, result.output136+ assert state["stderr_wrap_calls"] > 0137+ assert state["write_calls"] > 0138+ decoded = state["written"].decode("utf-16-le", errors="ignore")139+ assert "Ran out of adventure time!\r\n" in decoded140+141+142+@pytest.mark.parametrize(143+ ("writable", "source", "expected_flags"),144+ [145+ (True, bytearray(b"python"), 1), # PyBUF_WRITABLE146+ (False, b"python", 0), # PyBUF_SIMPLE147+ ],148+)149+def test_get_buffer(monkeypatch, writable, source, expected_flags):150+ state = {"flags": None, "released": 0}151+ if writable:152+ backing = (_winconsole.c_char * len(source)).from_buffer(source)153+ else:154+ backing = (_winconsole.c_char * len(source)).from_buffer_copy(source)155+ backing_ptr = _winconsole.c_void_p(ctypes.addressof(backing))156+157+ def fake_object_get_buffer(obj, buf_ref, flags): # noqa: ARG001158+ state["flags"] = flags159+ buf = buf_ref._obj160+ buf.buf = backing_ptr161+ buf.len = len(source)162+163+ def fake_buffer_release(buf_ref): # noqa: ARG001164+ state["released"] += 1165+166+ monkeypatch.setattr(_winconsole, "PyObject_GetBuffer", fake_object_get_buffer)167+ monkeypatch.setattr(_winconsole, "PyBuffer_Release", fake_buffer_release)168+169+ probe = source if writable else b"x"170+ out = _winconsole.get_buffer(probe, writable=writable)171+ if writable:172+ # mutate the first byte of "python" to obtain another beloved programming language173+ out[0] = b"c"174+ assert source == bytearray(b"cython")175+ else:176+ assert bytes(out[: len(source)]) == source177+ assert state["flags"] == expected_flags178+ assert state["released"] == 1179+180+181+def test_isatty():182+ assert _winconsole._WindowsConsoleRawIOBase(None).isatty() is True183+ assert _winconsole._WindowsConsoleReader(0).isatty() is True184+ assert _winconsole._WindowsConsoleReader(1).isatty() is True185+186+187+def test_console_stream():188+ class NamedBytesIO(io.BytesIO):189+ name = "fake-buffer"190+191+ def isatty(self):192+ return False193+194+ stream = _winconsole.ConsoleStream(195+ io.TextIOWrapper(io.BytesIO(), encoding="utf-8"), NamedBytesIO()196+ )197+ assert stream.isatty() is False198+ assert stream.name == "fake-buffer"199+ assert "fake-buffer" in repr(stream)200+ assert "utf-8" in repr(stream)201+202+ # test writelines203+ stream.writelines(["hello", " ", "world"])204+ stream._text_stream.flush()205+ assert stream._text_stream.buffer.getvalue().decode("utf-8") == "hello world"206+207+ # Cover bytes write path.208+ assert stream.write(b"!") == 1209+ assert stream.buffer.getvalue().endswith(b"!")210+211+212+@pytest.mark.parametrize(213+ ("error", "msg"),214+ [215+ (0, "ERROR_SUCCESS"), # ERROR_SUCCESS216+ (8, "ERROR_NOT_ENOUGH_MEMORY"), # ERROR_NOT_ENOUGH_MEMORY217+ (342, "Windows error 342"),218+ ],219+)220+def test_error_message(error, msg):221+ writer = _winconsole._WindowsConsoleWriter222+ assert writer._get_error_message(error) == msg223+224+225+def test_is_console():226+ assert _winconsole._is_console(object()) is False227+228+229+def test_get_windows_console_stream_factory_and_buffer_paths(monkeypatch):230+ monkeypatch.setattr(_winconsole, "_is_console", lambda f: True)231+ monkeypatch.setattr(_winconsole, "get_buffer", object())232+233+ class FakeStream:234+ def __init__(self, fd, buffer=None):235+ self._fd = fd236+ self.buffer = buffer237+238+ def fileno(self):239+ return self._fd240+241+ wrapped = {"called": False, "buffer": None}242+243+ def fake_factory(buffer):244+ wrapped["called"] = True245+ wrapped["buffer"] = buffer246+ return "wrapped", buffer247+248+ monkeypatch.setattr(_winconsole, "_stream_factories", {7: fake_factory})249+250+ # Known console stream preconditions pass, but no stream factory for this fd.251+ get_stream = _winconsole._get_windows_console_stream252+ assert get_stream(FakeStream(99, object()), "utf-16-le", "strict") is None253+254+ # Factory exists, but stream has no usable .buffer.255+ assert get_stream(FakeStream(7, None), "utf-16-le", "strict") is None256+257+ # Factory exists and buffer is present, so wrapper result is returned.258+ raw_buffer = object()259+ out = get_stream(FakeStream(7, raw_buffer), "utf-16-le", "strict")260+ assert out == ("wrapped", raw_buffer)261+ assert wrapped["called"] is True262+ assert wrapped["buffer"] is raw_buffer263+264+265+def test_windows_console_reader(monkeypatch):266+ reader = _winconsole._WindowsConsoleReader(42)267+268+ # Empty input buffer returns early269+ assert reader.readinto(bytearray()) == 0270+271+ # Require an even number of bytes272+ with pytest.raises(ValueError):273+ reader.readinto(bytearray(3))274+275+ def writable_buffer(obj, writable=False): # noqa: ARG001276+ return (ctypes.c_char * len(obj)).from_buffer(obj)277+278+ monkeypatch.setattr(_winconsole, "get_buffer", writable_buffer)279+280+ def patch_console(read_console, error):281+ monkeypatch.setattr(_winconsole, "ReadConsoleW", read_console)282+ monkeypatch.setattr(_winconsole, "GetLastError", lambda: error)283+284+ def make_read(payload=b"", rv=1, units_read=None):285+ def read_console(handle, buffer, units_to_read, units_read_ptr, reserved): # noqa: ARG001286+ bytes_to_copy = min(len(payload), units_to_read * 2)287+ if bytes_to_copy:288+ buffer[0:bytes_to_copy] = payload[:bytes_to_copy]289+ read_units = units_read if units_read is not None else bytes_to_copy // 2290+ units_read_ptr._obj.value = read_units291+ return rv292+293+ return read_console294+295+ # Normal successful read returns the number of bytes read296+ patch_console(make_read(payload=b"A\x00B\x00"), _winconsole.ERROR_SUCCESS)297+ assert reader.readinto(bytearray(4)) == 4298+299+ # CTRL+Z (EOF) should be translated into an empty read300+ patch_console(301+ make_read(payload=_winconsole.EOF + b"\x00", units_read=1),302+ _winconsole.ERROR_SUCCESS,303+ )304+ assert reader.readinto(bytearray(2)) == 0305+306+ # An aborted read should sleep briefly while waiting for KeyboardInterrupt307+ sleep_state = {"calls": 0}308+309+ def fake_sleep(seconds):310+ sleep_state["calls"] += 1311+ assert seconds == 0.1312+313+ monkeypatch.setattr(314+ _winconsole, "time", type("FakeTime", (), {"sleep": fake_sleep})315+ )316+ patch_console(317+ make_read(payload=b"Z\x00", units_read=1),318+ _winconsole.ERROR_OPERATION_ABORTED,319+ )320+ assert reader.readinto(bytearray(2)) == 2321+ assert sleep_state["calls"] == 1322+323+ # Failed reads propagate a Windows error324+ patch_console(make_read(rv=0), _winconsole.ERROR_NOT_ENOUGH_MEMORY)325+ with pytest.raises(OSError, match="Windows error"):326+ reader.readinto(bytearray(2))modified:tests/utils.py+7 added
7 unmodified lines8 9 needs_linux = pytest.mark.skipif(10 not sys.platform.startswith("linux"), reason="Test requires Linux"11 )12+needs_macos = pytest.mark.skipif(13+ not sys.platform.startswith("darwin"), reason="Test requires macOS"14+)15 needs_windows = pytest.mark.skipif(16 not sys.platform.startswith("win"), reason="Test requires Windows"17 )18+skip_if_windows = pytest.mark.skipif(19+ sys.platform == "win32",20+ reason="Test should not be run on Windows",21+)22 23 needs_rich = pytest.mark.skipif(not HAS_RICH, reason="Test requires Rich")24 25 shell = _get_shell_name()27 unmodified linesadded:typer/_click/__init__.py+11 added
1+"""2+Code taken and adapted from Click: https://github.com/pallets/click/releases/tag/8.3.13+"""4+5+from .core import Command as Command6+from .core import Context as Context7+from .core import Parameter as Parameter8+from .exceptions import ClickException as ClickException9+from .formatting import HelpFormatter as HelpFormatter10+from .termui import launch as launch11+from .utils import echo as echoadded:typer/_click/_compat.py+569 added
1+import codecs2+import io3+import os4+import re5+import sys6+from collections.abc import Callable, Mapping, MutableMapping7+from types import TracebackType8+from typing import (9+ IO,10+ Any,11+ BinaryIO,12+ TextIO,13+ cast,14+)15+from weakref import WeakKeyDictionary16+17+CYGWIN = sys.platform.startswith("cygwin")18+WIN = sys.platform.startswith("win")19+auto_wrap_for_ansi: Callable[[TextIO], TextIO] | None = None20+_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")21+22+23+def _make_text_stream(24+ stream: BinaryIO,25+ encoding: str | None,26+ errors: str,27+) -> TextIO:28+ if encoding is None:29+ encoding = get_best_encoding(stream)30+ return _NonClosingTextIOWrapper(31+ stream,32+ encoding,33+ errors,34+ line_buffering=True,35+ )36+37+38+def is_ascii_encoding(encoding: str) -> bool:39+ """Checks if a given encoding is ascii."""40+ try:41+ return codecs.lookup(encoding).name == "ascii"42+ except LookupError:43+ return False44+45+46+def get_best_encoding(stream: IO[Any]) -> str:47+ """Returns the default stream encoding if not found."""48+ rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()49+ if is_ascii_encoding(rv):50+ return "utf-8"51+ return rv52+53+54+class _NonClosingTextIOWrapper(io.TextIOWrapper):55+ def __init__(56+ self,57+ stream: BinaryIO,58+ encoding: str | None,59+ errors: str | None,60+ **extra: Any,61+ ) -> None:62+ self._stream = stream = cast(BinaryIO, _FixupStream(stream))63+ super().__init__(stream, encoding, errors, **extra)64+65+ def __del__(self) -> None:66+ try:67+ self.detach()68+ except Exception: # pragma: no cover69+ pass70+71+ def isatty(self) -> bool:72+ # https://bitbucket.org/pypy/pypy/issue/180373+ return self._stream.isatty()74+75+76+class _FixupStream:77+ """The new io interface needs more from streams than streams78+ traditionally implement. As such, this fix-up code is necessary in79+ some circumstances.80+ """81+82+ def __init__(83+ self,84+ stream: BinaryIO,85+ ):86+ self._stream = stream87+88+ def __getattr__(self, name: str) -> Any:89+ return getattr(self._stream, name)90+91+ def read1(self, size: int) -> bytes:92+ f = getattr(self._stream, "read1", None)93+94+ if f is not None:95+ return cast(bytes, f(size))96+97+ return self._stream.read(size)98+99+ def readable(self) -> bool:100+ return True101+102+ def writable(self) -> bool:103+ return True104+105+ def seekable(self) -> bool:106+ x = getattr(self._stream, "seekable", None)107+ if x is not None:108+ return cast(bool, x())109+ return False110+111+112+def _is_binary_reader(stream: IO[Any], default: bool = False) -> bool:113+ try:114+ return isinstance(stream.read(0), bytes)115+ except Exception: # pragma: no cover116+ return default117+ # This happens in some cases where the stream was already118+ # closed. In this case, we assume the default.119+120+121+def _is_binary_writer(stream: IO[Any], default: bool = False) -> bool:122+ try:123+ stream.write(b"")124+ except Exception: # pragma: no cover125+ try:126+ stream.write("")127+ return False128+ except Exception:129+ pass130+ return default131+ return True132+133+134+def _find_binary_reader(stream: IO[Any]) -> BinaryIO | None:135+ # We need to figure out if the given stream is already binary.136+ # This can happen because the official docs recommend detaching137+ # the streams to get binary streams. Some code might do this, so138+ # we need to deal with this case explicitly.139+ if _is_binary_reader(stream, False):140+ return cast(BinaryIO, stream)141+142+ buf = getattr(stream, "buffer", None)143+144+ # Same situation here; this time we assume that the buffer is145+ # actually binary in case it's closed.146+ if buf is not None and _is_binary_reader(buf, True):147+ return cast(BinaryIO, buf)148+149+ return None150+151+152+def _find_binary_writer(stream: IO[Any]) -> BinaryIO | None:153+ # We need to figure out if the given stream is already binary.154+ # This can happen because the official docs recommend detaching155+ # the streams to get binary streams. Some code might do this, so156+ # we need to deal with this case explicitly.157+ if _is_binary_writer(stream, False):158+ return cast(BinaryIO, stream)159+160+ buf = getattr(stream, "buffer", None)161+162+ # Same situation here; this time we assume that the buffer is163+ # actually binary in case it's closed.164+ if buf is not None and _is_binary_writer(buf, True):165+ return cast(BinaryIO, buf)166+167+ return None168+169+170+def _stream_is_misconfigured(stream: TextIO) -> bool:171+ """A stream is misconfigured if its encoding is ASCII."""172+ # If the stream does not have an encoding set, we assume it's set173+ # to ASCII. This appears to happen in certain unittest174+ # environments. It's not quite clear what the correct behavior is175+ # but this at least will force Click to recover somehow.176+ return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")177+178+179+def _is_compat_stream_attr(stream: TextIO, attr: str, value: str | None) -> bool:180+ """A stream attribute is compatible if it is equal to the181+ desired value or the desired value is unset and the attribute182+ has a value.183+ """184+ stream_value = getattr(stream, attr, None)185+ return stream_value == value or (value is None and stream_value is not None)186+187+188+def _is_compatible_text_stream(189+ stream: TextIO, encoding: str | None, errors: str | None190+) -> bool:191+ """Check if a stream's encoding and errors attributes are192+ compatible with the desired values.193+ """194+ return _is_compat_stream_attr(195+ stream, "encoding", encoding196+ ) and _is_compat_stream_attr(stream, "errors", errors)197+198+199+def _force_correct_text_stream(200+ text_stream: IO[Any],201+ encoding: str | None,202+ errors: str | None,203+ is_binary: Callable[[IO[Any], bool], bool],204+ find_binary: Callable[[IO[Any]], BinaryIO | None],205+) -> TextIO:206+ if is_binary(text_stream, False):207+ binary_reader = cast(BinaryIO, text_stream)208+ else:209+ text_stream = cast(TextIO, text_stream)210+ # If the stream looks compatible, and won't default to a211+ # misconfigured ascii encoding, return it as-is.212+ if _is_compatible_text_stream(text_stream, encoding, errors) and not (213+ encoding is None and _stream_is_misconfigured(text_stream)214+ ):215+ return text_stream216+217+ # Otherwise, get the underlying binary reader.218+ possible_binary_reader = find_binary(text_stream)219+220+ # If that's not possible, silently use the original reader221+ # and get mojibake instead of exceptions.222+ if possible_binary_reader is None:223+ return text_stream224+225+ binary_reader = possible_binary_reader226+227+ # Default errors to replace instead of strict in order to get228+ # something that works.229+ if errors is None:230+ errors = "replace"231+232+ # Wrap the binary stream in a text stream with the correct233+ # encoding parameters.234+ return _make_text_stream(235+ binary_reader,236+ encoding,237+ errors,238+ )239+240+241+def _force_correct_text_reader(242+ text_reader: IO[Any],243+ encoding: str | None,244+ errors: str | None,245+) -> TextIO:246+ return _force_correct_text_stream(247+ text_reader,248+ encoding,249+ errors,250+ _is_binary_reader,251+ _find_binary_reader,252+ )253+254+255+def _force_correct_text_writer(256+ text_writer: IO[Any],257+ encoding: str | None,258+ errors: str | None,259+) -> TextIO:260+ return _force_correct_text_stream(261+ text_writer,262+ encoding,263+ errors,264+ _is_binary_writer,265+ _find_binary_writer,266+ )267+268+269+def get_binary_stdin() -> BinaryIO:270+ reader = _find_binary_reader(sys.stdin)271+ if reader is None: # pragma: no cover272+ raise RuntimeError("Was not able to determine binary stream for sys.stdin.")273+ return reader274+275+276+def get_binary_stdout() -> BinaryIO:277+ writer = _find_binary_writer(sys.stdout)278+ if writer is None: # pragma: no cover279+ raise RuntimeError("Was not able to determine binary stream for sys.stdout.")280+ return writer281+282+283+def get_binary_stderr() -> BinaryIO:284+ writer = _find_binary_writer(sys.stderr)285+ if writer is None: # pragma: no cover286+ raise RuntimeError("Was not able to determine binary stream for sys.stderr.")287+ return writer288+289+290+def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> TextIO:291+ rv = _get_windows_console_stream(sys.stdin, encoding, errors)292+ if rv is not None:293+ return rv294+ return _force_correct_text_reader(sys.stdin, encoding, errors)295+296+297+def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> TextIO:298+ rv = _get_windows_console_stream(sys.stdout, encoding, errors)299+ if rv is not None:300+ return rv301+ return _force_correct_text_writer(sys.stdout, encoding, errors)302+303+304+def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> TextIO:305+ rv = _get_windows_console_stream(sys.stderr, encoding, errors)306+ if rv is not None:307+ return rv308+ return _force_correct_text_writer(sys.stderr, encoding, errors)309+310+311+def _wrap_io_open(312+ file: str | os.PathLike[str] | int,313+ mode: str,314+ encoding: str | None,315+ errors: str | None,316+) -> IO[Any]:317+ """Handles not passing ``encoding`` and ``errors`` in binary mode."""318+ if "b" in mode:319+ return open(file, mode)320+321+ return open(file, mode, encoding=encoding, errors=errors)322+323+324+def open_stream(325+ filename: str | os.PathLike[str],326+ mode: str = "r",327+ encoding: str | None = None,328+ errors: str | None = "strict",329+ atomic: bool = False,330+) -> tuple[IO[Any], bool]:331+ binary = "b" in mode332+ filename = os.fspath(filename)333+334+ # Standard streams first, ignoring the atomic flag.335+ if os.fsdecode(filename) == "-":336+ if any(m in mode for m in ["w", "a", "x"]):337+ if binary:338+ return get_binary_stdout(), False339+ return get_text_stdout(encoding=encoding, errors=errors), False340+ if binary:341+ return get_binary_stdin(), False342+ return get_text_stdin(encoding=encoding, errors=errors), False343+344+ # Non-atomic writes directly go out through the regular open functions.345+ if not atomic:346+ return _wrap_io_open(filename, mode, encoding, errors), True347+348+ # Some usability stuff for atomic writes349+ if "a" in mode:350+ raise ValueError(351+ "Appending to an existing file is not supported, because that"352+ " would involve an expensive `copy`-operation to a temporary"353+ " file. Open the file in normal `w`-mode and copy explicitly"354+ " if that's what you're after."355+ )356+ if "x" in mode:357+ raise ValueError("Use the `overwrite`-parameter instead.")358+ if "w" not in mode:359+ raise ValueError("Atomic writes only make sense with `w`-mode.")360+361+ # Atomic writes are more complicated. They work by opening a file362+ # as a proxy in the same folder and then using the fdopen363+ # functionality to wrap it in a Python file. Then we wrap it in an364+ # atomic file that moves the file over on close.365+ import errno366+ import random367+368+ try:369+ perm: int | None = os.stat(filename).st_mode370+ except OSError: # pragma: no cover371+ perm = None372+373+ flags = os.O_RDWR | os.O_CREAT | os.O_EXCL374+375+ if binary:376+ flags |= getattr(os, "O_BINARY", 0)377+378+ while True:379+ tmp_filename = os.path.join(380+ os.path.dirname(filename),381+ f".__atomic-write{random.randrange(1 << 32):08x}",382+ )383+ try:384+ fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)385+ break386+ except OSError as e: # pragma: no cover387+ if e.errno == errno.EEXIST or (388+ os.name == "nt"389+ and e.errno == errno.EACCES390+ and os.path.isdir(e.filename)391+ and os.access(e.filename, os.W_OK)392+ ):393+ continue394+ raise395+396+ if perm is not None:397+ os.chmod(tmp_filename, perm) # in case perm includes bits in umask398+399+ f = _wrap_io_open(fd, mode, encoding, errors)400+ af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))401+ return cast(IO[Any], af), True402+403+404+class _AtomicFile:405+ def __init__(self, f: IO[Any], tmp_filename: str, real_filename: str) -> None:406+ self._f = f407+ self._tmp_filename = tmp_filename408+ self._real_filename = real_filename409+ self.closed = False410+411+ @property412+ def name(self) -> str:413+ return self._real_filename414+415+ def close(self, delete: bool = False) -> None:416+ if self.closed:417+ return # pragma: no cover418+ self._f.close()419+ os.replace(self._tmp_filename, self._real_filename)420+ self.closed = True421+422+ def __getattr__(self, name: str) -> Any:423+ return getattr(self._f, name)424+425+ def __enter__(self) -> "_AtomicFile":426+ return self427+428+ def __exit__(429+ self,430+ exc_type: type[BaseException] | None,431+ exc_value: BaseException | None,432+ tb: TracebackType | None,433+ ) -> None:434+ self.close(delete=exc_type is not None)435+436+ def __repr__(self) -> str:437+ return repr(self._f)438+439+440+def strip_ansi(value: str) -> str:441+ return _ansi_re.sub("", value)442+443+444+def _is_jupyter_kernel_output(stream: IO[Any]) -> bool:445+ while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):446+ stream = stream._stream447+448+ return stream.__class__.__module__.startswith("ipykernel.")449+450+451+def should_strip_ansi(stream: IO[Any] | None = None, color: bool | None = None) -> bool:452+ if color is None:453+ if stream is None:454+ stream = sys.stdin455+ return not isatty(stream) and not _is_jupyter_kernel_output(stream)456+ return not color457+458+459+# On Windows, wrap the output streams with colorama to support ANSI460+# color codes.461+# NOTE: double check is needed so mypy does not analyze this on Linux462+if sys.platform.startswith("win") and WIN:463+ from ._winconsole import _get_windows_console_stream464+465+ def _get_argv_encoding() -> str:466+ import locale467+468+ return locale.getpreferredencoding()469+470+ _ansi_stream_wrappers: MutableMapping[TextIO, TextIO] = WeakKeyDictionary()471+472+ def auto_wrap_for_ansi(stream: TextIO, color: bool | None = None) -> TextIO:473+ """Support ANSI color and style codes on Windows by wrapping a474+ stream with colorama.475+ """476+ try:477+ cached = _ansi_stream_wrappers.get(stream)478+ except Exception: # pragma: no cover479+ cached = None480+481+ if cached is not None:482+ return cached483+484+ import colorama485+486+ strip = should_strip_ansi(stream, color)487+ ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)488+ rv = cast(TextIO, ansi_wrapper.stream)489+ _write = rv.write490+491+ def _safe_write(s: str) -> int:492+ try:493+ return _write(s)494+ except BaseException: # pragma: no cover495+ ansi_wrapper.reset_all()496+ raise497+498+ rv.write = _safe_write # type: ignore[method-assign] # ty: ignore[invalid-assignment]499+500+ try:501+ _ansi_stream_wrappers[stream] = rv502+ except Exception: # pragma: no cover503+ pass504+505+ return rv506+507+else:508+509+ def _get_argv_encoding() -> str:510+ return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()511+512+ def _get_windows_console_stream(513+ f: TextIO, encoding: str | None, errors: str | None514+ ) -> TextIO | None:515+ return None516+517+518+def term_len(x: str) -> int:519+ return len(strip_ansi(x))520+521+522+def isatty(stream: IO[Any]) -> bool:523+ try:524+ return stream.isatty()525+ except Exception: # pragma: no cover526+ return False527+528+529+def _make_cached_stream_func(530+ src_func: Callable[[], TextIO],531+ wrapper_func: Callable[[], TextIO],532+) -> Callable[[], TextIO]:533+ cache: MutableMapping[TextIO, TextIO] = WeakKeyDictionary()534+535+ def func() -> TextIO:536+ stream = src_func()537+538+ try:539+ rv = cache.get(stream)540+ except Exception: # pragma: no cover541+ rv = None542+ if rv is not None:543+ return rv544+ rv = wrapper_func()545+ try:546+ cache[stream] = rv547+ except Exception: # pragma: no cover548+ pass549+ return rv550+551+ return func552+553+554+_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)555+_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)556+_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)557+558+559+binary_streams: Mapping[str, Callable[[], BinaryIO]] = {560+ "stdin": get_binary_stdin,561+ "stdout": get_binary_stdout,562+ "stderr": get_binary_stderr,563+}564+565+text_streams: Mapping[str, Callable[[str | None, str | None], TextIO]] = {566+ "stdin": get_text_stdin,567+ "stdout": get_text_stdout,568+ "stderr": get_text_stderr,569+}added:typer/_click/_termui_impl.py+522 added
1+"""2+To keep the import times down, some infrequently used termui functionality3+is placed here and only imported as needed.4+"""5+6+import contextlib7+import math8+import os9+import sys10+import time11+from collections.abc import Callable, Iterable, Iterator12+from io import StringIO13+from types import TracebackType14+from typing import Generic, TextIO, TypeVar, cast15+16+from ._compat import (17+ CYGWIN,18+ WIN,19+ _default_text_stdout,20+ get_best_encoding,21+ isatty,22+ term_len,23+)24+from .utils import echo25+26+V = TypeVar("V")27+28+if os.name == "nt":29+ BEFORE_BAR = "\r"30+ AFTER_BAR = "\n"31+else:32+ BEFORE_BAR = "\r\033[?25l"33+ AFTER_BAR = "\033[?25h\n"34+35+36+class ProgressBar(Generic[V]):37+ def __init__(38+ self,39+ iterable: Iterable[V] | None,40+ length: int | None = None,41+ fill_char: str = "#",42+ empty_char: str = " ",43+ bar_template: str = "%(bar)s",44+ info_sep: str = " ",45+ hidden: bool = False,46+ show_eta: bool = True,47+ show_percent: bool | None = None,48+ show_pos: bool = False,49+ item_show_func: Callable[[V | None], str | None] | None = None,50+ label: str | None = None,51+ file: TextIO | None = None,52+ color: bool | None = None,53+ update_min_steps: int = 1,54+ width: int = 30,55+ ) -> None:56+ self.fill_char = fill_char57+ self.empty_char = empty_char58+ self.bar_template = bar_template59+ self.info_sep = info_sep60+ self.hidden = hidden61+ self.show_eta = show_eta62+ self.show_percent = show_percent63+ self.show_pos = show_pos64+ self.item_show_func = item_show_func65+ self.label: str = label or ""66+67+ if file is None:68+ file = _default_text_stdout()69+70+ # There are no standard streams attached to write to. For example,71+ # pythonw on Windows.72+ if file is None: # pragma: no cover73+ file = StringIO()74+75+ self.file = file76+ self.color = color77+ self.update_min_steps = update_min_steps78+ self._completed_intervals = 079+ self.width: int = width80+ self.autowidth: bool = width == 081+82+ if length is None:83+ from operator import length_hint84+85+ length = length_hint(iterable, -1)86+87+ if length == -1: # pragma: no cover88+ length = None89+ if iterable is None:90+ if length is None: # pragma: no cover91+ raise TypeError("iterable or length is required")92+ iterable = cast("Iterable[V]", range(length))93+ self.iter: Iterable[V] = iter(iterable)94+ self.length = length95+ self.pos: int = 096+ self.avg: list[float] = []97+ self.last_eta: float98+ self.start: float99+ self.start = self.last_eta = time.time()100+ self.eta_known: bool = False101+ self.finished: bool = False102+ self.max_width: int | None = None103+ self.entered: bool = False104+ self.current_item: V | None = None105+ self._is_atty = isatty(self.file)106+ self._last_line: str | None = None107+108+ def __enter__(self) -> "ProgressBar[V]":109+ self.entered = True110+ self.render_progress()111+ return self112+113+ def __exit__(114+ self,115+ exc_type: type[BaseException] | None,116+ exc_value: BaseException | None,117+ tb: TracebackType | None,118+ ) -> None:119+ self.render_finish()120+121+ def __iter__(self) -> Iterator[V]:122+ if not self.entered:123+ raise RuntimeError("You need to use progress bars in a with block.")124+ self.render_progress()125+ return self.generator()126+127+ def __next__(self) -> V:128+ # Iteration is defined in terms of a generator function,129+ # returned by iter(self); use that to define next(). This works130+ # because `self.iter` is an iterable consumed by that generator,131+ # so it is re-entry safe. Calling `next(self.generator())`132+ # twice works and does "what you want".133+ return next(iter(self))134+135+ def render_finish(self) -> None:136+ if self.hidden or not self._is_atty:137+ return138+ self.file.write(AFTER_BAR)139+ self.file.flush()140+141+ @property142+ def pct(self) -> float:143+ if self.finished:144+ return 1.0145+ return min(self.pos / (float(self.length or 1) or 1), 1.0)146+147+ @property148+ def time_per_iteration(self) -> float:149+ if not self.avg:150+ return 0.0151+ return sum(self.avg) / float(len(self.avg))152+153+ @property154+ def eta(self) -> float:155+ if self.length is not None and not self.finished:156+ return self.time_per_iteration * (self.length - self.pos)157+ return 0.0158+159+ def format_eta(self) -> str:160+ if self.eta_known:161+ t = int(self.eta)162+ seconds = t % 60163+ t //= 60164+ minutes = t % 60165+ t //= 60166+ hours = t % 24167+ t //= 24168+ if t > 0:169+ return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"170+ else:171+ return f"{hours:02}:{minutes:02}:{seconds:02}"172+ return ""173+174+ def format_pos(self) -> str:175+ pos = str(self.pos)176+ if self.length is not None:177+ pos += f"/{self.length}"178+ return pos179+180+ def format_pct(self) -> str:181+ return f"{int(self.pct * 100): 4}%"[1:]182+183+ def format_bar(self) -> str:184+ if self.length is not None:185+ bar_length = int(self.pct * self.width)186+ bar = self.fill_char * bar_length187+ bar += self.empty_char * (self.width - bar_length)188+ elif self.finished:189+ bar = self.fill_char * self.width190+ else:191+ chars = list(self.empty_char * (self.width or 1))192+ if self.time_per_iteration != 0:193+ chars[194+ int(195+ (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)196+ * self.width197+ )198+ ] = self.fill_char199+ bar = "".join(chars)200+ return bar201+202+ def format_progress_line(self) -> str:203+ show_percent = self.show_percent204+205+ info_bits = []206+ if self.length is not None and show_percent is None:207+ show_percent = not self.show_pos208+209+ if self.show_pos:210+ info_bits.append(self.format_pos())211+ if show_percent:212+ info_bits.append(self.format_pct())213+ if self.show_eta and self.eta_known and not self.finished:214+ info_bits.append(self.format_eta())215+ if self.item_show_func is not None:216+ item_info = self.item_show_func(self.current_item)217+ if item_info is not None:218+ info_bits.append(item_info)219+220+ return (221+ self.bar_template222+ % {223+ "label": self.label,224+ "bar": self.format_bar(),225+ "info": self.info_sep.join(info_bits),226+ }227+ ).rstrip()228+229+ def render_progress(self) -> None:230+ if self.hidden:231+ return232+233+ if not self._is_atty:234+ # Only output the label once if the output is not a TTY.235+ if self._last_line != self.label:236+ self._last_line = self.label237+ echo(self.label, file=self.file, color=self.color)238+ return239+240+ buf = []241+ # Update width in case the terminal has been resized242+ if self.autowidth:243+ import shutil244+245+ old_width = self.width246+ self.width = 0247+ clutter_length = term_len(self.format_progress_line())248+ new_width = max(0, shutil.get_terminal_size().columns - clutter_length)249+ if new_width < old_width and self.max_width is not None:250+ buf.append(BEFORE_BAR)251+ buf.append(" " * self.max_width)252+ self.max_width = new_width253+ self.width = new_width254+255+ clear_width = self.width256+ if self.max_width is not None:257+ clear_width = self.max_width258+259+ buf.append(BEFORE_BAR)260+ line = self.format_progress_line()261+ line_len = term_len(line)262+ if self.max_width is None or self.max_width < line_len:263+ self.max_width = line_len264+265+ buf.append(line)266+ buf.append(" " * (clear_width - line_len))267+ line = "".join(buf)268+ # Render the line only if it changed.269+270+ if line != self._last_line:271+ self._last_line = line272+ echo(line, file=self.file, color=self.color, nl=False)273+ self.file.flush()274+275+ def make_step(self, n_steps: int) -> None:276+ self.pos += n_steps277+ if self.length is not None and self.pos >= self.length:278+ self.finished = True279+280+ if (time.time() - self.last_eta) < 1.0:281+ return282+283+ self.last_eta = time.time()284+285+ # self.avg is a rolling list of length <= 7 of steps where steps are286+ # defined as time elapsed divided by the total progress through287+ # self.length.288+ if self.pos:289+ step = (time.time() - self.start) / self.pos290+ else:291+ step = time.time() - self.start292+293+ self.avg = self.avg[-6:] + [step]294+295+ self.eta_known = self.length is not None296+297+ def update(self, n_steps: int) -> None:298+ """Update the progress bar by advancing a specified number of steps."""299+ self._completed_intervals += n_steps300+301+ if self._completed_intervals >= self.update_min_steps:302+ self.make_step(self._completed_intervals)303+ self.render_progress()304+ self._completed_intervals = 0305+306+ def finish(self) -> None:307+ self.eta_known = False308+ self.current_item = None309+ self.finished = True310+311+ def generator(self) -> Iterator[V]:312+ """Return a generator which yields the items added to the bar313+ during construction, and updates the progress bar *after* the314+ yielded block returns.315+ """316+ # WARNING: the iterator interface for `ProgressBar` relies on317+ # this and only works because this is a simple generator which318+ # doesn't create or manage additional state. If this function319+ # changes, the impact should be evaluated both against320+ # `iter(bar)` and `next(bar)`. `next()` in particular may call321+ # `self.generator()` repeatedly, and this must remain safe in322+ # order for that interface to work.323+ if not self.entered: # pragma: no cover324+ raise RuntimeError("You need to use progress bars in a with block.")325+326+ if not self._is_atty:327+ yield from self.iter328+ else:329+ for rv in self.iter:330+ self.current_item = rv331+332+ # This allows show_item_func to be updated before the333+ # item is processed. Only trigger at the beginning of334+ # the update interval.335+ if self._completed_intervals == 0:336+ self.render_progress()337+338+ yield rv339+ self.update(1)340+341+ self.finish()342+ self.render_progress()343+344+345+def open_url(url: str, wait: bool = False, locate: bool = False) -> int:346+ import subprocess347+348+ def _unquote_file(url: str) -> str:349+ from urllib.parse import unquote350+351+ if url.startswith("file://"):352+ url = unquote(url[7:])353+354+ return url355+356+ if sys.platform == "darwin":357+ args = ["open"]358+ if wait:359+ args.append("-W")360+ if locate:361+ args.append("-R")362+ args.append(_unquote_file(url))363+ null = open("/dev/null", "w")364+ try:365+ return subprocess.Popen(args, stderr=null).wait()366+ finally:367+ null.close()368+ elif WIN:369+ if locate:370+ url = _unquote_file(url)371+ args = ["explorer", f"/select,{url}"]372+ else:373+ args = ["start"]374+ if wait:375+ args.append("/WAIT")376+ args.append("")377+ args.append(url)378+ try:379+ return subprocess.call(args)380+ except OSError:381+ # Command not found382+ return 127383+ elif CYGWIN: # pragma: no cover384+ if locate:385+ url = _unquote_file(url)386+ args = ["cygstart", os.path.dirname(url)]387+ else:388+ args = ["cygstart"]389+ if wait:390+ args.append("-w")391+ args.append(url)392+ try:393+ return subprocess.call(args)394+ except OSError:395+ # Command not found396+ return 127397+398+ try:399+ if locate:400+ url = os.path.dirname(_unquote_file(url)) or "."401+ else:402+ url = _unquote_file(url)403+ c = subprocess.Popen(["xdg-open", url])404+ if wait:405+ return c.wait()406+ return 0407+ except OSError: # pragma: no cover408+ # TODO: remove this part, doesn't get hit by Typer code paths?409+ if url.startswith(("http://", "https://")) and not locate and not wait:410+ import webbrowser411+412+ webbrowser.open(url)413+ return 0414+ return 1415+416+417+def _translate_ch_to_exc(ch: str) -> None:418+ if ch == "\x03":419+ raise KeyboardInterrupt()420+421+ if ch == "\x04" and not WIN: # Unix-like, Ctrl+D422+ raise EOFError()423+424+ if ch == "\x1a" and WIN: # Windows, Ctrl+Z425+ raise EOFError()426+427+ return None428+429+430+if sys.platform == "win32":431+ import msvcrt432+433+ @contextlib.contextmanager434+ def raw_terminal() -> Iterator[int]:435+ yield -1436+437+ def getchar(echo: bool) -> str:438+ # The function `getch` will return a bytes object corresponding to439+ # the pressed character. Since Windows 10 build 1803, it will also440+ # return \x00 when called a second time after pressing a regular key.441+ #442+ # `getwch` does not share this probably-bugged behavior. Moreover, it443+ # returns a Unicode object by default, which is what we want.444+ #445+ # Either of these functions will return \x00 or \xe0 to indicate446+ # a special key, and you need to call the same function again to get447+ # the "rest" of the code. The fun part is that \u00e0 is448+ # "latin small letter a with grave", so if you type that on a French449+ # keyboard, you _also_ get a \xe0.450+ # E.g., consider the Up arrow. This returns \xe0 and then \x48. The451+ # resulting Unicode string reads as "a with grave" + "capital H".452+ # This is indistinguishable from when the user actually types453+ # "a with grave" and then "capital H".454+ #455+ # When \xe0 is returned, we assume it's part of a special-key sequence456+ # and call `getwch` again, but that means that when the user types457+ # the \u00e0 character, `getchar` doesn't return until a second458+ # character is typed.459+ # The alternative is returning immediately, but that would mess up460+ # cross-platform handling of arrow keys and others that start with461+ # \xe0. Another option is using `getch`, but then we can't reliably462+ # read non-ASCII characters, because return values of `getch` are463+ # limited to the current 8-bit codepage.464+ #465+ # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`466+ # is doing the right thing in more situations than with `getch`.467+468+ if echo:469+ func = cast(Callable[[], str], msvcrt.getwche)470+ else:471+ func = cast(Callable[[], str], msvcrt.getwch)472+473+ rv = func()474+475+ if rv in ("\x00", "\xe0"):476+ # \x00 and \xe0 are control characters that indicate special key,477+ # see above.478+ rv += func()479+480+ _translate_ch_to_exc(rv)481+ return rv482+483+else:484+ import termios485+ import tty486+487+ @contextlib.contextmanager488+ def raw_terminal() -> Iterator[int]:489+ f: TextIO | None490+ fd: int491+492+ if not isatty(sys.stdin):493+ f = open("/dev/tty")494+ fd = f.fileno()495+ else:496+ fd = sys.stdin.fileno()497+ f = None498+499+ try:500+ old_settings = termios.tcgetattr(fd)501+502+ try:503+ tty.setraw(fd)504+ yield fd505+ finally:506+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)507+ sys.stdout.flush()508+509+ if f is not None:510+ f.close()511+ except termios.error: # pragma: no cover512+ pass513+514+ def getchar(echo: bool) -> str:515+ with raw_terminal() as fd:516+ ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")517+518+ if echo and isatty(sys.stdout): # pragma: no cover519+ sys.stdout.write(ch)520+521+ _translate_ch_to_exc(ch)522+ return chadded:typer/_click/_textwrap.py+46 added
1+import textwrap2+from collections.abc import Iterator3+from contextlib import contextmanager4+5+6+class TextWrapper(textwrap.TextWrapper):7+ def _handle_long_word(8+ self,9+ reversed_chunks: list[str],10+ cur_line: list[str],11+ cur_len: int,12+ width: int,13+ ) -> None:14+ space_left = max(width - cur_len, 1)15+16+ last = reversed_chunks[-1]17+ cut = last[:space_left]18+ res = last[space_left:]19+ cur_line.append(cut)20+ reversed_chunks[-1] = res21+22+ @contextmanager23+ def extra_indent(self, indent: str) -> Iterator[None]:24+ old_initial_indent = self.initial_indent25+ old_subsequent_indent = self.subsequent_indent26+ self.initial_indent += indent27+ self.subsequent_indent += indent28+29+ try:30+ yield31+ finally:32+ self.initial_indent = old_initial_indent33+ self.subsequent_indent = old_subsequent_indent34+35+ def indent_only(self, text: str) -> str:36+ rv = []37+38+ for idx, line in enumerate(text.splitlines()):39+ indent = self.initial_indent40+41+ if idx > 0:42+ indent = self.subsequent_indent43+44+ rv.append(f"{indent}{line}")45+46+ return "\n".join(rv)added:typer/_click/_winconsole.py+300 added
1+# This module is based on the excellent work by Adam Bartoš who2+# provided a lot of what went into the implementation here in3+# the discussion to issue1602 in the Python bug tracker.4+#5+# There are some general differences in regards to how this works6+# compared to the original patches as we do not need to patch7+# the entire interpreter but just work in our little world of8+# echo and prompt.9+import io10+import sys11+import time12+from collections.abc import Callable, Iterable, Mapping13+from ctypes import (14+ POINTER,15+ Array,16+ Structure,17+ byref,18+ c_char,19+ c_char_p,20+ c_int,21+ c_ssize_t,22+ c_ulong,23+ c_void_p,24+ py_object,25+)26+from ctypes.wintypes import DWORD, HANDLE, LPCWSTR, LPWSTR27+from typing import (28+ TYPE_CHECKING,29+ Any,30+ AnyStr,31+ BinaryIO,32+ Literal,33+ TextIO,34+ cast,35+)36+37+from ._compat import _NonClosingTextIOWrapper38+39+assert sys.platform == "win32"40+import msvcrt # noqa: E40241+from ctypes import WINFUNCTYPE, windll # noqa: E40242+43+c_ssize_p = POINTER(c_ssize_t)44+45+kernel32 = windll.kernel3246+GetStdHandle = kernel32.GetStdHandle47+ReadConsoleW = kernel32.ReadConsoleW48+WriteConsoleW = kernel32.WriteConsoleW49+GetConsoleMode = kernel32.GetConsoleMode50+GetLastError = kernel32.GetLastError51+GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))52+CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(53+ ("CommandLineToArgvW", windll.shell32)54+)55+LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))56+57+STDIN_HANDLE = GetStdHandle(-10)58+STDOUT_HANDLE = GetStdHandle(-11)59+STDERR_HANDLE = GetStdHandle(-12)60+61+PyBUF_SIMPLE = 062+PyBUF_WRITABLE = 163+64+ERROR_SUCCESS = 065+ERROR_NOT_ENOUGH_MEMORY = 866+ERROR_OPERATION_ABORTED = 99567+68+STDIN_FILENO = 069+STDOUT_FILENO = 170+STDERR_FILENO = 271+72+EOF = b"\x1a"73+MAX_BYTES_WRITTEN = 3276774+75+if TYPE_CHECKING:76+ try:77+ # Using `typing_extensions.Buffer` instead of `collections.abc`78+ # on Windows for some reason does not have `Sized` implemented.79+ from collections.abc import Buffer # type: ignore80+ except ImportError:81+ from typing_extensions import Buffer82+83+try:84+ from ctypes import pythonapi85+except ImportError: # pragma: no cover86+ # On PyPy we cannot get buffers so our ability to operate here is87+ # severely limited.88+ get_buffer = None89+else:90+91+ class Py_buffer(Structure):92+ _fields_ = [ # noqa: RUF01293+ ("buf", c_void_p),94+ ("obj", py_object),95+ ("len", c_ssize_t),96+ ("itemsize", c_ssize_t),97+ ("readonly", c_int),98+ ("ndim", c_int),99+ ("format", c_char_p),100+ ("shape", c_ssize_p),101+ ("strides", c_ssize_p),102+ ("suboffsets", c_ssize_p),103+ ("internal", c_void_p),104+ ]105+106+ PyObject_GetBuffer = pythonapi.PyObject_GetBuffer107+ PyBuffer_Release = pythonapi.PyBuffer_Release108+109+ def get_buffer(obj: "Buffer", writable: bool = False) -> Array[c_char]:110+ buf = Py_buffer()111+ flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE112+ PyObject_GetBuffer(py_object(obj), byref(buf), flags)113+114+ try:115+ buffer_type = c_char * buf.len116+ out: Array[c_char] = buffer_type.from_address(buf.buf)117+ return out118+ finally:119+ PyBuffer_Release(byref(buf))120+121+122+class _WindowsConsoleRawIOBase(io.RawIOBase):123+ def __init__(self, handle: int | None) -> None:124+ self.handle = handle125+126+ def isatty(self) -> Literal[True]:127+ super().isatty()128+ return True129+130+131+class _WindowsConsoleReader(_WindowsConsoleRawIOBase):132+ def readable(self) -> Literal[True]:133+ return True134+135+ def readinto(self, b: "Buffer") -> int:136+ bytes_to_be_read = len(b)137+ if not bytes_to_be_read:138+ return 0139+ elif bytes_to_be_read % 2:140+ raise ValueError(141+ "cannot read odd number of bytes from UTF-16-LE encoded console"142+ )143+144+ buffer = get_buffer(b, writable=True)145+ code_units_to_be_read = bytes_to_be_read // 2146+ code_units_read = c_ulong()147+148+ rv = ReadConsoleW(149+ HANDLE(self.handle),150+ buffer,151+ code_units_to_be_read,152+ byref(code_units_read),153+ None,154+ )155+ if GetLastError() == ERROR_OPERATION_ABORTED:156+ # wait for KeyboardInterrupt157+ time.sleep(0.1)158+ if not rv:159+ raise OSError(f"Windows error: {GetLastError()}")160+161+ if buffer[0] == EOF:162+ return 0163+ return 2 * code_units_read.value164+165+166+class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):167+ def writable(self) -> Literal[True]:168+ return True169+170+ @staticmethod171+ def _get_error_message(errno: int) -> str:172+ if errno == ERROR_SUCCESS:173+ return "ERROR_SUCCESS"174+ elif errno == ERROR_NOT_ENOUGH_MEMORY:175+ return "ERROR_NOT_ENOUGH_MEMORY"176+ return f"Windows error {errno}"177+178+ def write(self, b: "Buffer") -> int:179+ bytes_to_be_written = len(b)180+ buf = get_buffer(b)181+ code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2182+ code_units_written = c_ulong()183+184+ WriteConsoleW(185+ HANDLE(self.handle),186+ buf,187+ code_units_to_be_written,188+ byref(code_units_written),189+ None,190+ )191+ bytes_written = 2 * code_units_written.value192+193+ if bytes_written == 0 and bytes_to_be_written > 0:194+ raise OSError(self._get_error_message(GetLastError())) # pragma: no cover195+ return bytes_written196+197+198+class ConsoleStream:199+ def __init__(self, text_stream: TextIO, byte_stream: BinaryIO) -> None:200+ self._text_stream = text_stream201+ self.buffer = byte_stream202+203+ @property204+ def name(self) -> str:205+ return self.buffer.name206+207+ def write(self, x: AnyStr) -> int:208+ if isinstance(x, str):209+ return self._text_stream.write(x)210+ try:211+ self.flush()212+ except Exception: # pragma: no cover213+ pass214+ return self.buffer.write(x)215+216+ def writelines(self, lines: Iterable[AnyStr]) -> None:217+ for line in lines:218+ self.write(line)219+220+ def __getattr__(self, name: str) -> Any:221+ return getattr(self._text_stream, name)222+223+ def isatty(self) -> bool:224+ return self.buffer.isatty()225+226+ def __repr__(self) -> str:227+ return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"228+229+230+def _get_text_stdin(buffer_stream: BinaryIO) -> TextIO:231+ text_stream = _NonClosingTextIOWrapper(232+ io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),233+ "utf-16-le",234+ "strict",235+ line_buffering=True,236+ )237+ return cast(TextIO, ConsoleStream(text_stream, buffer_stream))238+239+240+def _get_text_stdout(buffer_stream: BinaryIO) -> TextIO:241+ text_stream = _NonClosingTextIOWrapper(242+ io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),243+ "utf-16-le",244+ "strict",245+ line_buffering=True,246+ )247+ return cast(TextIO, ConsoleStream(text_stream, buffer_stream))248+249+250+def _get_text_stderr(buffer_stream: BinaryIO) -> TextIO:251+ text_stream = _NonClosingTextIOWrapper(252+ io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),253+ "utf-16-le",254+ "strict",255+ line_buffering=True,256+ )257+ return cast(TextIO, ConsoleStream(text_stream, buffer_stream))258+259+260+_stream_factories: Mapping[int, Callable[[BinaryIO], TextIO]] = {261+ 0: _get_text_stdin,262+ 1: _get_text_stdout,263+ 2: _get_text_stderr,264+}265+266+267+def _is_console(f: TextIO) -> bool:268+ if not hasattr(f, "fileno"):269+ return False270+271+ try:272+ fileno = f.fileno()273+ except (OSError, io.UnsupportedOperation):274+ return False275+276+ handle = msvcrt.get_osfhandle(fileno)277+ return bool(GetConsoleMode(handle, byref(DWORD())))278+279+280+def _get_windows_console_stream(281+ f: TextIO, encoding: str | None, errors: str | None282+) -> TextIO | None:283+ if (284+ get_buffer is None285+ or encoding not in {"utf-16-le", None}286+ or errors not in {"strict", None}287+ or not _is_console(f)288+ ):289+ return None290+291+ func = _stream_factories.get(f.fileno())292+ if func is None:293+ return None294+295+ b = getattr(f, "buffer", None)296+297+ if b is None:298+ return None299+300+ return func(b)added:typer/_click/core.py+1111 added
1+import enum2+import inspect3+import os4+from abc import ABC, abstractmethod5+from collections.abc import Callable, Iterator, Mapping, MutableMapping, Sequence6+from contextlib import AbstractContextManager, ExitStack, contextmanager7+from types import TracebackType8+from typing import (9+ TYPE_CHECKING,10+ Any,11+ Literal,12+ NoReturn,13+ TypeVar,14+ Union,15+ cast,16+ overload,17+)18+19+from . import types20+from .exceptions import (21+ Abort,22+ BadParameter,23+ Exit,24+ MissingParameter,25+ NoArgsIsHelpError,26+ UsageError,27+)28+from .formatting import HelpFormatter29+from .globals import pop_context, push_context30+from .parser import _OptionParser31+from .termui import style32+from .utils import echo, make_default_short_help33+34+if TYPE_CHECKING:35+ from ..core import TyperOption36+ from .shell_completion import CompletionItem37+38+F = TypeVar("F", bound="Callable[..., Any]")39+V = TypeVar("V")40+41+42+def _complete_visible_commands(43+ ctx: "Context", incomplete: str44+) -> Iterator[tuple[str, "Command"]]:45+ """List all the subcommands of a group that start with the46+ incomplete value and aren't hidden.47+ """48+ # avoid circular imports49+ from ..core import TyperGroup50+51+ multi = cast(TyperGroup, ctx.command)52+53+ for name in multi.list_commands(ctx):54+ if name.startswith(incomplete):55+ command = multi.get_command(ctx, name)56+57+ if command is not None and not command.hidden:58+ yield name, command59+60+61+@contextmanager62+def augment_usage_errors(63+ ctx: "Context", param: Union["Parameter", None] = None64+) -> Iterator[None]:65+ """Context manager that attaches extra information to exceptions."""66+ try:67+ yield68+ except BadParameter as e:69+ if e.ctx is None:70+ e.ctx = ctx71+ if param is not None and e.param is None:72+ e.param = param73+ raise74+ except UsageError as e: # pragma: no cover75+ if e.ctx is None:76+ e.ctx = ctx77+ raise78+79+80+def iter_params_for_processing(81+ invocation_order: Sequence["Parameter"],82+ declaration_order: Sequence["Parameter"],83+) -> list["Parameter"]:84+ """Returns all declared parameters in the order they should be processed.85+86+ The declared parameters are re-shuffled depending on the order in which87+ they were invoked, as well as the eagerness of each parameters.88+89+ The invocation order takes precedence over the declaration order. I.e. the90+ order in which the user provided them to the CLI is respected.91+92+ This behavior and its effect on callback evaluation is detailed at:93+ https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order94+ """95+96+ def sort_key(item: Parameter) -> tuple[bool, float]:97+ try:98+ idx: float = invocation_order.index(item)99+ except ValueError:100+ idx = float("inf")101+102+ return not item.is_eager, idx103+104+ return sorted(declaration_order, key=sort_key)105+106+107+class ParameterSource(enum.Enum):108+ """This is an `Enum` that indicates the source of a109+ parameter's value.110+ """111+112+ COMMANDLINE = enum.auto()113+ """The value was provided by the command line args."""114+ ENVIRONMENT = enum.auto()115+ """The value was provided with an environment variable."""116+ DEFAULT = enum.auto()117+ """Used the default specified by the parameter."""118+ DEFAULT_MAP = enum.auto()119+ """Used a default provided by `Context.default_map`."""120+ PROMPT = enum.auto()121+ """Used a prompt to confirm a default or provide a value."""122+123+124+class Context:125+ """The context is a special internal object that holds state relevant126+ for the script execution at every single level. It's normally invisible127+ to commands unless they opt-in to getting access to it.128+129+ The context is useful as it can pass internal objects around and can130+ control special execution features such as reading data from131+ environment variables.132+133+ A context can be used as context manager in which case it will call134+ `close` on teardown.135+ """136+137+ formatter_class: type[HelpFormatter] = HelpFormatter138+139+ def __init__(140+ self,141+ command: "Command",142+ parent: Union["Context", None] = None,143+ info_name: str | None = None,144+ obj: Any | None = None,145+ auto_envvar_prefix: str | None = None,146+ default_map: MutableMapping[str, Any] | None = None,147+ terminal_width: int | None = None,148+ max_content_width: int | None = None,149+ resilient_parsing: bool = False,150+ allow_extra_args: bool | None = None,151+ allow_interspersed_args: bool | None = None,152+ ignore_unknown_options: bool | None = None,153+ help_option_names: list[str] | None = None,154+ token_normalize_func: Callable[[str], str] | None = None,155+ color: bool | None = None,156+ show_default: bool | None = None,157+ ) -> None:158+ self.parent = parent159+ self.command = command160+ self.info_name = info_name161+ # Map of parameter names to their parsed values.162+ self.params: dict[str, Any] = {}163+ # the leftover arguments.164+ self.args: list[str] = []165+ # protected arguments. used to implement nested parsing.166+ self._protected_args: list[str] = []167+ # the collected prefixes of the command's options.168+ self._opt_prefixes: set[str] = set(parent._opt_prefixes) if parent else set()169+170+ if obj is None and parent is not None:171+ obj = parent.obj172+173+ self.obj: Any = obj174+ self._meta: dict[str, Any] = getattr(parent, "meta", {})175+176+ # A dictionary (-like object) with defaults for parameters.177+ if (178+ default_map is None179+ and info_name is not None180+ and parent is not None181+ and parent.default_map is not None182+ ):183+ default_map = parent.default_map.get(info_name)184+185+ self.default_map: MutableMapping[str, Any] | None = default_map186+187+ # This flag indicates if a subcommand is going to be executed.188+ self.invoked_subcommand: str | None = None189+190+ if terminal_width is None and parent is not None:191+ terminal_width = parent.terminal_width192+193+ # The width of the terminal (None is autodetection).194+ self.terminal_width: int | None = terminal_width195+196+ if max_content_width is None and parent is not None:197+ max_content_width = parent.max_content_width198+199+ self.max_content_width: int | None = max_content_width200+201+ if allow_extra_args is None:202+ allow_extra_args = command.allow_extra_args203+204+ self.allow_extra_args = allow_extra_args205+206+ if allow_interspersed_args is None:207+ allow_interspersed_args = command.allow_interspersed_args208+209+ self.allow_interspersed_args: bool = allow_interspersed_args210+211+ if ignore_unknown_options is None:212+ ignore_unknown_options = command.ignore_unknown_options213+214+ self.ignore_unknown_options: bool = ignore_unknown_options215+216+ if help_option_names is None:217+ if parent is not None:218+ help_option_names = parent.help_option_names219+ else:220+ help_option_names = ["--help"]221+222+ self.help_option_names: list[str] = help_option_names223+224+ if token_normalize_func is None and parent is not None:225+ token_normalize_func = parent.token_normalize_func226+227+ # An optional normalization function for tokens. (options, choices, commands etc.)228+ self.token_normalize_func: Callable[[str], str] | None = token_normalize_func229+230+ # Indicates if resilient parsing is enabled.231+ self.resilient_parsing: bool = resilient_parsing232+233+ # If there is no envvar prefix yet, but the parent has one and234+ # the command on this level has a name, we can expand the envvar235+ # prefix automatically.236+ if auto_envvar_prefix is None:237+ if (238+ parent is not None239+ and parent.auto_envvar_prefix is not None240+ and self.info_name is not None241+ ):242+ auto_envvar_prefix = (243+ f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"244+ )245+ else:246+ auto_envvar_prefix = auto_envvar_prefix.upper()247+248+ if auto_envvar_prefix is not None:249+ auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")250+251+ self.auto_envvar_prefix: str | None = auto_envvar_prefix252+253+ if color is None and parent is not None:254+ color = parent.color255+256+ # Controls if styling output is wanted or not.257+ self.color: bool | None = color258+259+ if show_default is None and parent is not None:260+ show_default = parent.show_default261+262+ # Show option default values when formatting help text.263+ self.show_default: bool | None = show_default264+265+ self._close_callbacks: list[Callable[[], Any]] = []266+ self._depth = 0267+ self._parameter_source: dict[str, ParameterSource] = {}268+ self._exit_stack = ExitStack()269+270+ def __enter__(self) -> "Context":271+ self._depth += 1272+ push_context(self)273+ return self274+275+ def __exit__(276+ self,277+ exc_type: type[BaseException] | None,278+ exc_value: BaseException | None,279+ tb: TracebackType | None,280+ ) -> bool | None:281+ self._depth -= 1282+ exit_result: bool | None = None283+ if self._depth == 0:284+ exit_result = self._close_with_exception_info(exc_type, exc_value, tb)285+ pop_context()286+287+ return exit_result288+289+ @contextmanager290+ def scope(self, cleanup: bool = True) -> Iterator["Context"]:291+ """This helper method can be used with the context object to promote292+ it to the current thread local (see `get_current_context`).293+ The default behavior of this is to invoke the cleanup functions which294+ can be disabled by setting `cleanup` to `False`. The cleanup295+ functions are typically used for things such as closing file handles.296+297+ If the cleanup is intended the context object can also be directly298+ used as a context manager.299+ """300+ if not cleanup:301+ self._depth += 1302+ try:303+ with self as rv:304+ yield rv305+ finally:306+ if not cleanup:307+ self._depth -= 1308+309+ @property310+ def meta(self) -> dict[str, Any]:311+ """This is a dictionary which is shared with all the contexts312+ that are nested. It exists so that click utilities can store some313+ state here if they need to. It is however the responsibility of314+ that code to manage this dictionary well.315+316+ The keys are supposed to be unique dotted strings. For instance317+ module paths are a good choice for it. What is stored in there is318+ irrelevant for the operation of click. However what is important is319+ that code that places data here adheres to the general semantics of320+ the system.321+ """322+ return self._meta323+324+ def make_formatter(self) -> HelpFormatter:325+ """Creates the HelpFormatter for the help and326+ usage output.327+ """328+ return self.formatter_class(329+ width=self.terminal_width, max_width=self.max_content_width330+ )331+332+ def with_resource(self, context_manager: AbstractContextManager[V]) -> V:333+ """Register a resource as if it were used in a ``with``334+ statement. The resource will be cleaned up when the context is335+ popped.336+337+ Uses `contextlib.ExitStack.enter_context`. It calls the338+ resource's ``__enter__()`` method and returns the result. When339+ the context is popped, it closes the stack, which calls the340+ resource's ``__exit__()`` method.341+342+ To register a cleanup function for something that isn't a343+ context manager, use `call_on_close`. Or use something344+ from `contextlib` to turn it into a context manager first.345+ """346+ return self._exit_stack.enter_context(context_manager)347+348+ def call_on_close(self, f: Callable[..., Any]) -> Callable[..., Any]:349+ """Register a function to be called when the context tears down.350+351+ This can be used to close resources opened during the script352+ execution. Resources that support Python's context manager353+ protocol which would be used in a ``with`` statement should be354+ registered with `with_resource` instead.355+ """356+ return self._exit_stack.callback(f)357+358+ def close(self) -> None:359+ """Invoke all close callbacks registered with `call_on_close`,360+ and exit all context managers entered with `with_resource`.361+ """362+ self._close_with_exception_info(None, None, None)363+364+ def _close_with_exception_info(365+ self,366+ exc_type: type[BaseException] | None,367+ exc_value: BaseException | None,368+ tb: TracebackType | None,369+ ) -> bool | None:370+ """Unwind the exit stack by calling its `__exit__` providing the exception371+ information to allow for exception handling by the various resources registered372+ using `with_resource`373+ """374+ exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)375+ # In case the context is reused, create a new exit stack.376+ self._exit_stack = ExitStack()377+378+ return exit_result379+380+ @property381+ def command_path(self) -> str:382+ """The computed command path. This is used for the ``usage``383+ information on the help page. It's automatically created by384+ combining the info names of the chain of contexts to the root.385+ """386+ rv = ""387+ if self.info_name is not None:388+ rv = self.info_name389+ if self.parent is not None:390+ parent_command_path = [self.parent.command_path]391+392+ if isinstance(self.parent.command, Command):393+ for param in self.parent.command.get_params(self):394+ parent_command_path.extend(param.get_usage_pieces(self))395+396+ rv = f"{' '.join(parent_command_path)} {rv}"397+ return rv.lstrip()398+399+ def find_root(self) -> "Context":400+ """Finds the outermost context."""401+ node = self402+ while node.parent is not None:403+ node = node.parent404+ return node405+406+ def find_object(self, object_type: type[V]) -> V | None:407+ """Finds the closest object of a given type."""408+ node: Context | None = self409+410+ while node is not None:411+ if isinstance(node.obj, object_type):412+ return node.obj413+414+ node = node.parent415+416+ return None417+418+ def ensure_object(self, object_type: type[V]) -> V:419+ """Like `find_object` but sets the innermost object to a420+ new instance of `object_type` if it does not exist.421+ """422+ rv = self.find_object(object_type)423+ if rv is None:424+ self.obj = rv = object_type()425+ return rv426+427+ @overload428+ def lookup_default(self, name: str, call: Literal[True] = True) -> Any | None: ...429+430+ @overload431+ def lookup_default(432+ self, name: str, call: Literal[False] = ...433+ ) -> Any | Callable[[], Any] | None: ...434+435+ def lookup_default(self, name: str, call: bool = True) -> Any | None:436+ """Get the default for a parameter from `default_map`."""437+ if self.default_map is not None:438+ value = self.default_map.get(name)439+440+ if call and callable(value):441+ return value()442+443+ return value444+445+ return None446+447+ def fail(self, message: str) -> NoReturn:448+ """Aborts the execution of the program with a specific error449+ message.450+ """451+ raise UsageError(message, self)452+453+ def abort(self) -> NoReturn:454+ """Aborts the script."""455+ raise Abort()456+457+ def exit(self, code: int = 0) -> NoReturn:458+ """Exits the application with a given exit code."""459+ self.close()460+ raise Exit(code)461+462+ def get_usage(self) -> str:463+ """Helper method to get formatted usage string for the current464+ context and command.465+ """466+ return self.command.get_usage(self)467+468+ def get_help(self) -> str:469+ """Helper method to get formatted help page for the current470+ context and command.471+ """472+ return self.command.get_help(self)473+474+ def invoke(self, callback: Callable[..., V], /, *args: Any, **kwargs: Any) -> V:475+ """Invokes a command callback in exactly the way it expects. There476+ are two ways to invoke this method:477+478+ 1. the first argument can be a callback and all other arguments and479+ keyword arguments are forwarded directly to the function.480+ 2. the first argument is a click command object. In that case all481+ arguments are forwarded as well but proper click parameters482+ (options and click arguments) must be keyword arguments and Click483+ will fill in defaults.484+ """485+ ctx = self486+487+ with augment_usage_errors(self):488+ with ctx:489+ return callback(*args, **kwargs)490+491+ def set_parameter_source(self, name: str, source: ParameterSource) -> None:492+ """Set the source of a parameter. This indicates the location493+ from which the value of the parameter was obtained.494+ """495+ self._parameter_source[name] = source496+497+ def get_parameter_source(self, name: str) -> ParameterSource | None:498+ """Get the source of a parameter. This indicates the location499+ from which the value of the parameter was obtained.500+501+ This can be useful for determining when a user specified a value502+ on the command line that is the same as the default value. It503+ will be `ParameterSource.DEFAULT` only if the504+ value was actually taken from the default.505+ """506+ return self._parameter_source.get(name)507+508+509+class Command(ABC):510+ """Commands are the basic building block of command line interfaces in511+ Click. A basic command handles command line parsing and might dispatch512+ more parsing to commands nested below it.513+ """514+515+ context_class: type[Context] = Context516+ allow_extra_args = False517+ allow_interspersed_args = True518+ ignore_unknown_options = False519+520+ def __init__(521+ self,522+ name: str | None,523+ context_settings: MutableMapping[str, Any] | None = None,524+ callback: Callable[..., Any] | None = None,525+ params: list["Parameter"] | None = None,526+ help: str | None = None,527+ epilog: str | None = None,528+ short_help: str | None = None,529+ options_metavar: str | None = "[OPTIONS]",530+ add_help_option: bool = True,531+ no_args_is_help: bool = False,532+ hidden: bool = False,533+ deprecated: bool | str = False,534+ ) -> None:535+ self.name = name536+537+ if context_settings is None:538+ context_settings = {}539+540+ self.context_settings: MutableMapping[str, Any] = context_settings541+542+ self.callback = callback543+ self.params: list[Parameter] = params or []544+ self.help = help545+ self.epilog = epilog546+ self.options_metavar = options_metavar547+ self.short_help = short_help548+ self.add_help_option = add_help_option549+ self._help_option: TyperOption | None = None550+ self.no_args_is_help = no_args_is_help551+ self.hidden = hidden552+ self.deprecated = deprecated553+554+ def __repr__(self) -> str:555+ return f"<{self.__class__.__name__} {self.name}>"556+557+ def get_usage(self, ctx: Context) -> str:558+ """Formats the usage line into a string and returns it."""559+ formatter = ctx.make_formatter()560+ self.format_usage(ctx, formatter)561+ return formatter.getvalue().rstrip("\n")562+563+ def get_params(self, ctx: Context) -> list["Parameter"]:564+ params = self.params565+ help_option = self.get_help_option(ctx)566+567+ if help_option is not None:568+ params = [*params, help_option]569+570+ return params571+572+ def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:573+ """Writes the usage line into the formatter."""574+ pieces = self.collect_usage_pieces(ctx)575+ formatter.write_usage(ctx.command_path, " ".join(pieces))576+577+ def collect_usage_pieces(self, ctx: Context) -> list[str]:578+ """Returns all the pieces that go into the usage line and returns579+ it as a list of strings.580+ """581+ rv = [self.options_metavar] if self.options_metavar else []582+583+ for param in self.get_params(ctx):584+ rv.extend(param.get_usage_pieces(ctx))585+586+ return rv587+588+ def get_help_option_names(self, ctx: Context) -> list[str]:589+ """Returns the names for the help option."""590+ all_names = set(ctx.help_option_names)591+ for param in self.params:592+ all_names.difference_update(param.opts)593+ all_names.difference_update(param.secondary_opts)594+ return list(all_names)595+596+ def get_help_option(self, ctx: Context) -> Union["TyperOption", None]:597+ """Returns the help option object."""598+ help_option_names = self.get_help_option_names(ctx)599+600+ if not help_option_names or not self.add_help_option:601+ return None602+603+ # Cache the help option object in private _help_option attribute to604+ # avoid creating it multiple times. Not doing this will break the605+ # callback ordering by iter_params_for_processing(), which relies on606+ # object comparison.607+ if self._help_option is None:608+ # Avoid circular import.609+ from .decorators import help_option610+611+ # Apply help_option decorator and pop resulting option612+ help_option(help_option_names)(self)613+ self._help_option = cast("TyperOption", self.params.pop())614+615+ return self._help_option616+617+ def make_parser(self, ctx: Context) -> _OptionParser:618+ """Creates the underlying option parser for this command."""619+ parser = _OptionParser(ctx)620+ for param in self.get_params(ctx):621+ param.add_to_parser(parser, ctx)622+ return parser623+624+ def get_help(self, ctx: Context) -> str:625+ """Formats the help into a string and returns it."""626+ formatter = ctx.make_formatter()627+ self.format_help(ctx, formatter)628+ return formatter.getvalue().rstrip("\n")629+630+ def get_short_help_str(self, limit: int = 45) -> str:631+ """Gets short help for the command or makes it by shortening the632+ long help string.633+ """634+ if self.short_help:635+ text = inspect.cleandoc(self.short_help)636+ elif self.help:637+ text = make_default_short_help(self.help, limit)638+ else:639+ text = ""640+641+ if self.deprecated:642+ deprecated_message = (643+ f"(DEPRECATED: {self.deprecated})"644+ if isinstance(self.deprecated, str)645+ else "(DEPRECATED)"646+ )647+ text = f"{text} {deprecated_message}"648+649+ return text.strip()650+651+ def format_help(self, ctx: Context, formatter: HelpFormatter) -> None:652+ """Writes the help into the formatter if it exists."""653+ self.format_usage(ctx, formatter)654+ self.format_help_text(ctx, formatter)655+ self.format_options(ctx, formatter)656+ self.format_epilog(ctx, formatter)657+658+ def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:659+ """Writes the help text to the formatter if it exists."""660+ if self.help is not None:661+ # truncate the help text to the first form feed662+ text = inspect.cleandoc(self.help).partition("\f")[0]663+ else:664+ text = ""665+666+ if self.deprecated:667+ deprecated_message = (668+ f"(DEPRECATED: {self.deprecated})"669+ if isinstance(self.deprecated, str)670+ else "(DEPRECATED)"671+ )672+ text = f"{text} {deprecated_message}"673+674+ if text:675+ formatter.write_paragraph()676+677+ with formatter.indentation():678+ formatter.write_text(text)679+680+ @abstractmethod681+ def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:682+ pass # pragma: no cover683+684+ def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:685+ """Writes the epilog into the formatter if it exists."""686+ if self.epilog:687+ epilog = inspect.cleandoc(self.epilog)688+ formatter.write_paragraph()689+690+ with formatter.indentation():691+ formatter.write_text(epilog)692+693+ def make_context(694+ self,695+ info_name: str | None,696+ args: list[str],697+ parent: Context | None = None,698+ **extra: Any,699+ ) -> Context:700+ """This function when given an info name and arguments will kick701+ off the parsing and create a new `Context`. It does not702+ invoke the actual command callback though.703+704+ To quickly customize the context class used without overriding705+ this method, set the `context_class` attribute.706+ """707+ for key, value in self.context_settings.items():708+ if key not in extra:709+ extra[key] = value710+711+ ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)712+713+ with ctx.scope(cleanup=False):714+ self.parse_args(ctx, args)715+ return ctx716+717+ def parse_args(self, ctx: Context, args: list[str]) -> list[str]:718+ if not args and self.no_args_is_help and not ctx.resilient_parsing:719+ raise NoArgsIsHelpError(ctx) # pragma: no cover720+721+ parser = self.make_parser(ctx)722+ opts, args, param_order = parser.parse_args(args=args)723+724+ for param in iter_params_for_processing(param_order, self.get_params(ctx)):725+ _, args = param.handle_parse_result(ctx, opts, args)726+727+ if args and not ctx.allow_extra_args and not ctx.resilient_parsing:728+ ctx.fail(f"Got unexpected extra argument(s) ({' '.join(map(str, args))})")729+730+ ctx.args = args731+ ctx._opt_prefixes.update(parser._opt_prefixes)732+ return args733+734+ def invoke(self, ctx: Context) -> Any:735+ """Given a context, this invokes the attached callback (if it exists)736+ in the right way.737+ """738+ if self.deprecated:739+ extra_message = (740+ f" {self.deprecated}" if isinstance(self.deprecated, str) else ""741+ )742+ message = f"DeprecationWarning: The command {self.name!r} is deprecated.{extra_message}"743+ echo(style(message, fg="red"), err=True)744+745+ if self.callback is not None:746+ return ctx.invoke(self.callback, **ctx.params)747+748+ def shell_complete(self, ctx: Context, incomplete: str) -> list["CompletionItem"]:749+ """Return a list of completions for the incomplete value. Looks750+ at the names of options and chained multi-commands.751+752+ Any command could be part of a chained multi-command, so sibling753+ commands are valid at any point during command completion.754+ """755+ # avoid circular imports756+ from .shell_completion import CompletionItem757+758+ results: list[CompletionItem] = []759+760+ if incomplete and not incomplete[0].isalnum():761+ # avoid circular imports762+ from ..core import TyperOption763+764+ for param in self.get_params(ctx):765+ if (766+ not isinstance(param, TyperOption)767+ or param.hidden768+ or (769+ not param.multiple770+ and ctx.get_parameter_source(param.name) # type: ignore771+ is ParameterSource.COMMANDLINE772+ )773+ ):774+ continue775+776+ results.extend(777+ CompletionItem(name, help=param.help)778+ for name in [*param.opts, *param.secondary_opts]779+ if name.startswith(incomplete)780+ )781+782+ return results783+784+ @abstractmethod785+ def main(786+ self,787+ args: Sequence[str] | None = None,788+ prog_name: str | None = None,789+ complete_var: str | None = None,790+ standalone_mode: bool = True,791+ windows_expand_args: bool = True,792+ **extra: Any,793+ ) -> Any:794+ pass # pragma: no cover795+796+ @abstractmethod797+ def _main_shell_completion(798+ self,799+ ctx_args: MutableMapping[str, Any],800+ prog_name: str,801+ complete_var: str | None = None,802+ ) -> None:803+ pass # pragma: no cover804+805+ def __call__(self, *args: Any, **kwargs: Any) -> Any:806+ """Alias for self.main"""807+ return self.main(*args, **kwargs)808+809+810+class Parameter(ABC):811+ r"""A parameter to a command comes in two versions: they are either812+ `Option`\s or `Argument`\s.813+814+ Some settings are supported by both options and arguments.815+ """816+817+ param_type_name = "parameter"818+819+ def __init__(820+ self,821+ param_decls: Sequence[str] | None = None,822+ type: types.ParamType | Any | None = None,823+ required: bool = False,824+ default: Any | Callable[[], Any] | None = None,825+ callback: Callable[[Context, "Parameter", Any], Any] | None = None,826+ nargs: int | None = None,827+ multiple: bool = False,828+ metavar: str | None = None,829+ expose_value: bool = True,830+ is_eager: bool = False,831+ envvar: str | Sequence[str] | None = None,832+ shell_complete: Callable[833+ [Context, "Parameter", str], list["CompletionItem"] | list[str]834+ ]835+ | None = None,836+ ) -> None:837+ self.name: str | None838+ self.opts: list[str]839+ self.secondary_opts: list[str]840+ self.name, self.opts, self.secondary_opts = self._parse_decls(841+ param_decls or (), expose_value842+ )843+ self.type: types.ParamType = types.convert_type(type, default)844+845+ # Default nargs to what the type tells us if we have that846+ # information available.847+ if nargs is None:848+ if self.type.is_composite:849+ nargs = self.type.arity850+ else:851+ nargs = 1852+853+ self.required = required854+ self.callback = callback855+ self.nargs = nargs856+ self.multiple = multiple857+ self.expose_value = expose_value858+ self.default: Any | Callable[[], Any] | None = default859+ self.is_eager = is_eager860+ self.metavar = metavar861+ self.envvar = envvar862+ self._custom_shell_complete = shell_complete863+864+ def __repr__(self) -> str:865+ return f"<{self.__class__.__name__} {self.name}>"866+867+ @abstractmethod868+ def _parse_decls(869+ self, decls: Sequence[str], expose_value: bool870+ ) -> tuple[str | None, list[str], list[str]]:871+ pass # pragma: no cover872+873+ @property874+ def human_readable_name(self) -> str:875+ """Returns the human readable name of this parameter. This is the876+ same as the name for options, but the metavar for arguments.877+ """878+ assert self.name is not None, "self.name should be set"879+ return self.name880+881+ def make_metavar(self, ctx: Context) -> str:882+ if self.metavar is not None:883+ return self.metavar884+885+ metavar = self.type.get_metavar(param=self, ctx=ctx)886+887+ if metavar is None:888+ metavar = self.type.name.upper()889+890+ if self.nargs != 1:891+ metavar += "..."892+893+ return metavar894+895+ @overload896+ def get_default(self, ctx: Context, call: Literal[True] = True) -> Any | None: ...897+898+ @overload899+ def get_default(900+ self, ctx: Context, call: bool = ...901+ ) -> Any | Callable[[], Any] | None: ...902+903+ def get_default(904+ self, ctx: Context, call: bool = True905+ ) -> Any | Callable[[], Any] | None:906+ """Get the default for the parameter"""907+ value = ctx.lookup_default(self.name, call=False) # type: ignore908+909+ if value is None:910+ value = self.default911+912+ if call and callable(value):913+ value = value()914+915+ return value916+917+ @abstractmethod918+ def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:919+ pass # pragma: no cover920+921+ def consume_value(922+ self, ctx: Context, opts: Mapping[str, Any]923+ ) -> tuple[Any, ParameterSource]:924+ value = opts.get(self.name) # type: ignore925+ source = ParameterSource.COMMANDLINE926+927+ if value is None:928+ value = self.value_from_envvar(ctx)929+ source = ParameterSource.ENVIRONMENT930+931+ if value is None:932+ value = ctx.lookup_default(self.name) # type: ignore933+ source = ParameterSource.DEFAULT_MAP934+935+ if value is None:936+ value = self.get_default(ctx)937+ source = ParameterSource.DEFAULT938+939+ return value, source940+941+ def type_cast_value(self, ctx: Context, value: Any) -> Any:942+ """Convert and validate a value against the parameter's943+ `type`, `multiple`, and `nargs`.944+ """945+ if value is None:946+ return () if self.multiple or self.nargs == -1 else None947+948+ def check_iter(value: Any) -> Iterator[Any]:949+ if isinstance(value, str):950+ raise BadParameter("Value must be an iterable.", ctx=ctx, param=self)951+ else:952+ return iter(value)953+954+ # Define the conversion function based on nargs and type.955+ if self.nargs == 1 or self.type.is_composite:956+957+ def convert(value: Any) -> Any:958+ return self.type(value, param=self, ctx=ctx)959+960+ elif self.nargs == -1:961+962+ def convert(value: Any) -> Any: # tuple[t.Any, ...]963+ return tuple(self.type(x, self, ctx) for x in check_iter(value))964+965+ # TODO: evaluate whether we need to keep this in Typer966+ else: # nargs > 1967+968+ def convert(value: Any) -> Any: # tuple[t.Any, ...]969+ value = tuple(check_iter(value))970+971+ if len(value) != self.nargs:972+ raise BadParameter(973+ f"Takes {self.nargs} values but {len(value)} given.",974+ ctx=ctx,975+ param=self,976+ )977+978+ return tuple(self.type(x, self, ctx) for x in value)979+980+ if self.multiple:981+ return tuple(convert(x) for x in check_iter(value))982+983+ return convert(value)984+985+ @abstractmethod986+ def value_is_missing(self, value: Any) -> bool:987+ pass # pragma: no cover988+989+ def process_value(self, ctx: Context, value: Any) -> Any:990+ """Process the value of this parameter"""991+ value = self.type_cast_value(ctx, value)992+993+ if self.required and self.value_is_missing(value):994+ raise MissingParameter(ctx=ctx, param=self)995+996+ if self.callback is not None:997+ value = self.callback(ctx, self, value)998+999+ return value1000+1001+ def resolve_envvar_value(self, ctx: Context) -> str | None:1002+ """Returns the value found in the environment variable(s) attached to this1003+ parameter.1004+1005+ Environment variables values are `always returned as strings1006+ <https://docs.python.org/3/library/os.html#os.environ>`_.1007+1008+ This method returns ``None`` if:1009+1010+ - the `envvar` property is not set on `Parameter`,1011+ - the environment variable is not found in the environment,1012+ - the variable is found in the environment but its value is empty (i.e. the1013+ environment variable is present but has an empty string).1014+1015+ If `envvar` is setup with multiple environment variables,1016+ then only the first non-empty value is returned.1017+ """1018+ if self.envvar is None:1019+ return None1020+1021+ if isinstance(self.envvar, str):1022+ rv = os.environ.get(self.envvar)1023+1024+ if rv:1025+ return rv1026+ else:1027+ for envvar in self.envvar:1028+ rv = os.environ.get(envvar)1029+1030+ # Return the first non-empty value of the list of environment variables.1031+ if rv:1032+ return rv1033+ # Else, absence of value is interpreted as an environment variable that1034+ # is not set, so proceed to the next one.1035+1036+ return None1037+1038+ def value_from_envvar(self, ctx: Context) -> str | Sequence[str] | None:1039+ """Process the raw environment variable string for this parameter.1040+1041+ Returns the string as-is or splits it into a sequence of strings if the1042+ parameter is expecting multiple values (i.e. its `nargs` property is set1043+ to a value other than ``1``).1044+ """1045+ rv: Any | None = self.resolve_envvar_value(ctx)1046+1047+ if rv is not None and self.nargs != 1:1048+ rv = self.type.split_envvar_value(rv)1049+1050+ return rv1051+1052+ def handle_parse_result(1053+ self, ctx: Context, opts: Mapping[str, Any], args: list[str]1054+ ) -> tuple[Any, list[str]]:1055+ """Process the value produced by the parser from user input.1056+1057+ Always process the value through the Parameter's `type`, wherever it1058+ comes from.1059+1060+ If the parameter is deprecated, this method warn the user about it. But only if1061+ the value has been explicitly set by the user (and as such, is not coming from1062+ a default).1063+ """1064+ with augment_usage_errors(ctx, param=self):1065+ value, source = self.consume_value(ctx, opts)1066+1067+ ctx.set_parameter_source(self.name, source) # type: ignore1068+1069+ # Process the value through the parameter's type.1070+ try:1071+ value = self.process_value(ctx, value)1072+ except Exception:1073+ if not ctx.resilient_parsing:1074+ raise1075+ value = None1076+1077+ if self.expose_value:1078+ ctx.params[self.name] = value # type: ignore1079+1080+ return value, args1081+1082+ @abstractmethod1083+ def get_help_record(self, ctx: Context) -> tuple[str, str] | None:1084+ pass # pragma: no cover1085+1086+ def get_usage_pieces(self, ctx: Context) -> list[str]:1087+ return []1088+1089+ def get_error_hint(self, ctx: Context) -> str:1090+ """Get a stringified version of the param for use in error messages to1091+ indicate which param caused the error.1092+ """1093+ hint_list = self.opts or [self.human_readable_name]1094+ return " / ".join(f"'{x}'" for x in hint_list)1095+1096+ def shell_complete(self, ctx: Context, incomplete: str) -> list["CompletionItem"]:1097+ """Return a list of completions for the incomplete value. If a1098+ ``shell_complete`` function was given during init, it is used.1099+ Otherwise, the `type` `ParamType.shell_complete` function is used.1100+ """1101+ if self._custom_shell_complete is not None:1102+ results = self._custom_shell_complete(ctx, self, incomplete)1103+1104+ if results and isinstance(results[0], str):1105+ from .shell_completion import CompletionItem1106+1107+ results = [CompletionItem(c) for c in results]1108+1109+ return cast("list[CompletionItem]", results)1110+1111+ return self.type.shell_complete(ctx, self, incomplete)added:typer/_click/decorators.py+60 added
1+from collections.abc import Callable2+from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar3+4+from .core import Command, Context, Parameter5+from .utils import echo6+7+if TYPE_CHECKING:8+ from ..core import TyperGroup, TyperOption9+10+ GrpType = TypeVar("GrpType", bound=TyperGroup)11+12+13+P = ParamSpec("P")14+15+R = TypeVar("R")16+T = TypeVar("T")17+_AnyCallable = Callable[..., Any]18+19+20+CmdType = TypeVar("CmdType", bound=Command)21+22+23+def option(24+ param_decls: list[str], cls: type["TyperOption"] | None = None, **attrs: Any25+) -> Callable[[Command], Command]:26+ """Attaches an option to the command."""27+ if cls is None:28+ # avoid circular imports29+ from ..core import TyperOption30+31+ cls = TyperOption32+33+ def decorator(f: Command) -> Command:34+ param = cls(param_decls=param_decls, **attrs)35+ f.params.append(param)36+ return f37+38+ return decorator39+40+41+def help_option(param_decls: list[str]) -> Callable[[Command], Command]:42+ """Help option which prints the help page and exits the program."""43+44+ def show_help(ctx: Context, param: Parameter, value: bool) -> None:45+ """Callback that print the help page on ``<stdout>`` and exits."""46+ if value and not ctx.resilient_parsing:47+ echo(ctx.get_help(), color=ctx.color)48+ ctx.exit()49+50+ assert len(param_decls) > 0, "At least one help option should be provided"51+52+ return option(53+ param_decls,54+ is_flag=True,55+ expose_value=False,56+ is_eager=True,57+ help="Show this message and exit.",58+ callback=show_help,59+ required=False,60+ )added:typer/_click/exceptions.py+260 added
1+from collections.abc import Sequence2+from typing import IO, TYPE_CHECKING, Any, Union3+4+from ._compat import get_text_stderr5+from .globals import resolve_color_default6+from .utils import echo, format_filename7+8+if TYPE_CHECKING:9+ from .core import Command, Context, Parameter10+11+12+def _join_param_hints(param_hint: Sequence[str] | str | None) -> str | None:13+ if param_hint is not None and not isinstance(param_hint, str):14+ return " / ".join(repr(x) for x in param_hint)15+16+ return param_hint17+18+19+class ClickException(Exception):20+ """An exception that Click can handle and show to the user."""21+22+ exit_code = 123+24+ def __init__(self, message: str) -> None:25+ super().__init__(message)26+ # The context will be removed by the time we print the message, so cache27+ # the color settings here to be used later on (in `show`)28+ self.show_color: bool | None = resolve_color_default()29+ self.message = message30+31+ def format_message(self) -> str:32+ return self.message33+34+ def __str__(self) -> str:35+ return self.message36+37+ def show(self, file: IO[Any] | None = None) -> None:38+ if file is None:39+ file = get_text_stderr()40+41+ echo(42+ f"Error: {self.format_message()}",43+ file=file,44+ color=self.show_color,45+ )46+47+48+class UsageError(ClickException):49+ """An internal exception that signals a usage error. This typically50+ aborts any further handling.51+ """52+53+ exit_code = 254+55+ def __init__(self, message: str, ctx: Union["Context", None] = None) -> None:56+ super().__init__(message)57+ self.ctx = ctx58+ self.cmd: Command | None = self.ctx.command if self.ctx else None59+60+ def show(self, file: IO[Any] | None = None) -> None:61+ if file is None:62+ file = get_text_stderr()63+ color = None64+ hint = ""65+ if (66+ self.ctx is not None67+ and self.ctx.command.get_help_option(self.ctx) is not None68+ ):69+ command = self.ctx.command_path70+ option = self.ctx.help_option_names[0]71+ hint = f"Try '{command} {option}' for help.\n"72+ if self.ctx is not None:73+ color = self.ctx.color74+ echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)75+ echo(76+ f"Error: {self.format_message()}",77+ file=file,78+ color=color,79+ )80+81+82+class BadParameter(UsageError):83+ """An exception that formats out a standardized error message for a84+ bad parameter. This is useful when thrown from a callback or type as85+ Click will attach contextual information to it (for instance, which86+ parameter it is).87+ """88+89+ def __init__(90+ self,91+ message: str,92+ ctx: Union["Context", None] = None,93+ param: Union["Parameter", None] = None,94+ param_hint: Sequence[str] | str | None = None,95+ ) -> None:96+ super().__init__(message, ctx)97+ self.param = param98+ self.param_hint = param_hint99+100+ def format_message(self) -> str:101+ if self.param_hint is not None:102+ param_hint = self.param_hint103+ elif self.param is not None:104+ param_hint = self.param.get_error_hint(self.ctx) # type: ignore105+ else:106+ return f"Invalid value: {self.message}"107+108+ hint = _join_param_hints(param_hint)109+ return f"Invalid value for {hint}: {self.message}"110+111+112+class MissingParameter(BadParameter):113+ """Raised if click required an option or argument but it was not114+ provided when invoking the script.115+ """116+117+ def __init__(118+ self,119+ message: str | None = None,120+ ctx: Union["Context", None] = None,121+ param: Union["Parameter", None] = None,122+ param_hint: Sequence[str] | str | None = None,123+ param_type: str | None = None,124+ ) -> None:125+ super().__init__(message or "", ctx, param, param_hint)126+ self.param_type = param_type127+128+ def format_message(self) -> str:129+ if self.param_hint is not None:130+ param_hint: Sequence[str] | str | None = self.param_hint131+ elif self.param is not None:132+ param_hint = self.param.get_error_hint(self.ctx) # type: ignore133+ else:134+ param_hint = None135+136+ param_hint = _join_param_hints(param_hint)137+ param_hint = f" {param_hint}" if param_hint else ""138+139+ param_type = self.param_type140+ if param_type is None and self.param is not None:141+ param_type = self.param.param_type_name142+143+ msg = self.message144+ if self.param is not None:145+ msg_extra = self.param.type.get_missing_message(146+ param=self.param, ctx=self.ctx147+ )148+ if msg_extra:149+ if msg:150+ msg += f". {msg_extra}"151+ else:152+ msg = msg_extra153+154+ msg = f" {msg}" if msg else ""155+156+ # Translate param_type for known types.157+ if param_type == "argument":158+ missing = "Missing argument"159+ elif param_type == "option":160+ missing = "Missing option"161+ elif param_type == "parameter":162+ missing = "Missing parameter"163+ else:164+ missing = f"Missing {param_type}"165+166+ return f"{missing}{param_hint}.{msg}"167+168+ def __str__(self) -> str:169+ if not self.message:170+ param_name = self.param.name if self.param else None171+ return f"Missing parameter: {param_name}"172+ else:173+ return self.message174+175+176+class NoSuchOption(UsageError):177+ """Raised if click attempted to handle an option that does not178+ exist.179+ """180+181+ def __init__(182+ self,183+ option_name: str,184+ message: str | None = None,185+ possibilities: Sequence[str] | None = None,186+ ctx: Union["Context", None] = None,187+ ) -> None:188+ if message is None:189+ message = f"No such option: {option_name}"190+191+ super().__init__(message, ctx)192+ self.option_name = option_name193+ self.possibilities = possibilities194+195+ def format_message(self) -> str:196+ if not self.possibilities:197+ return self.message198+199+ possibility_str = ", ".join(sorted(self.possibilities))200+ suggest = (f"(Possible options: {possibility_str})",)201+ return f"{self.message} {suggest}"202+203+204+class BadOptionUsage(UsageError):205+ """Raised if an option is generally supplied but the use of the option206+ was incorrect. This is for instance raised if the number of arguments207+ for an option is not correct.208+ """209+210+ def __init__(211+ self, option_name: str, message: str, ctx: Union["Context", None] = None212+ ) -> None:213+ super().__init__(message, ctx)214+ self.option_name = option_name215+216+217+class BadArgumentUsage(UsageError):218+ """Raised if an argument is generally supplied but the use of the argument219+ was incorrect. This is for instance raised if the number of values220+ for an argument is not correct.221+ """222+223+224+class NoArgsIsHelpError(UsageError):225+ def __init__(self, ctx: "Context") -> None:226+ self.ctx: Context227+ super().__init__(ctx.get_help(), ctx=ctx)228+229+ def show(self, file: IO[Any] | None = None) -> None:230+ echo(self.format_message(), file=file, err=True, color=self.ctx.color)231+232+233+class FileError(ClickException):234+ """Raised if a file cannot be opened."""235+236+ def __init__(self, filename: str, hint: str | None = None) -> None:237+ if hint is None:238+ hint = "unknown error"239+240+ super().__init__(hint)241+ self.ui_filename: str = format_filename(filename)242+ self.filename = filename243+244+ def format_message(self) -> str:245+ return f"Could not open file {self.ui_filename!r}: {self.message}"246+247+248+class Abort(RuntimeError):249+ """An internal signalling exception that signals Click to abort."""250+251+252+class Exit(RuntimeError):253+ """An exception that indicates that the application should exit with some254+ status code.255+ """256+257+ __slots__ = ("exit_code",)258+259+ def __init__(self, code: int = 0) -> None:260+ self.exit_code: int = codeadded:typer/_click/formatting.py+272 added
1+from collections.abc import Iterable, Iterator, Sequence2+from contextlib import contextmanager3+4+from ._compat import term_len5+from .parser import _split_opt6+7+# Can force a width. This is used by the test system8+FORCED_WIDTH: int | None = None9+10+11+def measure_table(rows: Iterable[tuple[str, str]]) -> tuple[int, ...]:12+ widths: dict[int, int] = {}13+14+ for row in rows:15+ for idx, col in enumerate(row):16+ widths[idx] = max(widths.get(idx, 0), term_len(col))17+18+ return tuple(y for x, y in sorted(widths.items()))19+20+21+def iter_rows(22+ rows: Iterable[tuple[str, str]], col_count: int23+) -> Iterator[tuple[str, ...]]:24+ for row in rows:25+ yield row + ("",) * (col_count - len(row))26+27+28+def wrap_text(29+ text: str,30+ width: int = 78,31+ initial_indent: str = "",32+ subsequent_indent: str = "",33+ preserve_paragraphs: bool = False,34+) -> str:35+ """A helper function that intelligently wraps text. By default, it36+ assumes that it operates on a single paragraph of text but if the37+ `preserve_paragraphs` parameter is provided it will intelligently38+ handle paragraphs (defined by two empty lines).39+40+ If paragraphs are handled, a paragraph can be prefixed with an empty41+ line containing the ``\\b`` character (``\\x08``) to indicate that42+ no rewrapping should happen in that block.43+ """44+ from ._textwrap import TextWrapper45+46+ text = text.expandtabs()47+ wrapper = TextWrapper(48+ width,49+ initial_indent=initial_indent,50+ subsequent_indent=subsequent_indent,51+ replace_whitespace=False,52+ )53+ if not preserve_paragraphs:54+ return wrapper.fill(text)55+56+ p: list[tuple[int, bool, str]] = []57+ buf: list[str] = []58+ indent = None59+60+ def _flush_par() -> None:61+ if not buf:62+ return63+ if buf[0].strip() == "\b":64+ p.append((indent or 0, True, "\n".join(buf[1:])))65+ else:66+ p.append((indent or 0, False, " ".join(buf)))67+ del buf[:]68+69+ for line in text.splitlines():70+ if not line:71+ _flush_par()72+ indent = None73+ else:74+ if indent is None:75+ orig_len = term_len(line)76+ line = line.lstrip()77+ indent = orig_len - term_len(line)78+ buf.append(line)79+ _flush_par()80+81+ rv = []82+ for indent, raw, text in p:83+ with wrapper.extra_indent(" " * indent):84+ if raw:85+ rv.append(wrapper.indent_only(text))86+ else:87+ rv.append(wrapper.fill(text))88+89+ return "\n\n".join(rv)90+91+92+class HelpFormatter:93+ """This class helps with formatting text-based help pages. It's94+ usually just needed for very special internal cases, but it's also95+ exposed so that developers can write their own fancy outputs.96+97+ At present, it always writes into memory.98+ """99+100+ def __init__(101+ self,102+ indent_increment: int = 2,103+ width: int | None = None,104+ max_width: int | None = None,105+ ) -> None:106+ self.indent_increment = indent_increment107+ if max_width is None:108+ max_width = 80109+ if width is None:110+ import shutil111+112+ width = FORCED_WIDTH113+ if width is None:114+ width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)115+ self.width = width116+ self.current_indent: int = 0117+ self.buffer: list[str] = []118+119+ def write(self, string: str) -> None:120+ """Writes a unicode string into the internal buffer."""121+ self.buffer.append(string)122+123+ def indent(self) -> None:124+ """Increases the indentation."""125+ self.current_indent += self.indent_increment126+127+ def dedent(self) -> None:128+ """Decreases the indentation."""129+ self.current_indent -= self.indent_increment130+131+ def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None:132+ """Writes a usage line into the buffer."""133+ if prefix is None:134+ prefix = "Usage: "135+136+ usage_prefix = f"{prefix:>{self.current_indent}}{prog} "137+ text_width = self.width - self.current_indent138+139+ if text_width >= (term_len(usage_prefix) + 20):140+ # The arguments will fit to the right of the prefix.141+ indent = " " * term_len(usage_prefix)142+ self.write(143+ wrap_text(144+ args,145+ text_width,146+ initial_indent=usage_prefix,147+ subsequent_indent=indent,148+ )149+ )150+ else:151+ # The prefix is too long, put the arguments on the next line.152+ self.write(usage_prefix)153+ self.write("\n")154+ indent = " " * (max(self.current_indent, term_len(prefix)) + 4)155+ self.write(156+ wrap_text(157+ args, text_width, initial_indent=indent, subsequent_indent=indent158+ )159+ )160+161+ self.write("\n")162+163+ def write_heading(self, heading: str) -> None:164+ """Writes a heading into the buffer."""165+ self.write(f"{'':>{self.current_indent}}{heading}:\n")166+167+ def write_paragraph(self) -> None:168+ """Writes a paragraph into the buffer."""169+ if self.buffer:170+ self.write("\n")171+172+ def write_text(self, text: str) -> None:173+ """Writes re-indented text into the buffer. This rewraps and174+ preserves paragraphs.175+ """176+ indent = " " * self.current_indent177+ self.write(178+ wrap_text(179+ text,180+ self.width,181+ initial_indent=indent,182+ subsequent_indent=indent,183+ preserve_paragraphs=True,184+ )185+ )186+ self.write("\n")187+188+ def write_dl(189+ self,190+ rows: Sequence[tuple[str, str]],191+ col_max: int = 30,192+ col_spacing: int = 2,193+ ) -> None:194+ """Writes a definition list into the buffer. This is how options195+ and commands are usually formatted.196+ """197+ rows = list(rows)198+ widths = measure_table(rows)199+ if len(widths) != 2: # pragma: no cover200+ raise TypeError("Expected two columns for definition list")201+202+ first_col = min(widths[0], col_max) + col_spacing203+204+ for first, second in iter_rows(rows, len(widths)):205+ self.write(f"{'':>{self.current_indent}}{first}")206+ if not second:207+ self.write("\n")208+ continue209+ if term_len(first) <= first_col - col_spacing:210+ self.write(" " * (first_col - term_len(first)))211+ else:212+ self.write("\n")213+ self.write(" " * (first_col + self.current_indent))214+215+ text_width = max(self.width - first_col - 2, 10)216+ wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)217+ lines = wrapped_text.splitlines()218+219+ if lines:220+ self.write(f"{lines[0]}\n")221+222+ for line in lines[1:]:223+ self.write(f"{'':>{first_col + self.current_indent}}{line}\n")224+ else: # pragma: no cover225+ self.write("\n")226+227+ @contextmanager228+ def section(self, name: str) -> Iterator[None]:229+ """Helpful context manager that writes a paragraph, a heading,230+ and the indents.231+ """232+ self.write_paragraph()233+ self.write_heading(name)234+ self.indent()235+ try:236+ yield237+ finally:238+ self.dedent()239+240+ @contextmanager241+ def indentation(self) -> Iterator[None]:242+ """A context manager that increases the indentation."""243+ self.indent()244+ try:245+ yield246+ finally:247+ self.dedent()248+249+ def getvalue(self) -> str:250+ """Returns the buffer contents."""251+ return "".join(self.buffer)252+253+254+def join_options(options: Sequence[str]) -> tuple[str, bool]:255+ """Given a list of option strings this joins them in the most appropriate256+ way and returns them in the form ``(formatted_string,257+ any_prefix_is_slash)`` where the second item in the tuple is a flag that258+ indicates if any of the option prefixes was a slash.259+ """260+ rv = []261+ any_prefix_is_slash = False262+263+ for opt in options:264+ prefix = _split_opt(opt)[0]265+266+ if prefix == "/":267+ any_prefix_is_slash = True268+269+ rv.append((len(prefix), opt))270+271+ rv.sort(key=lambda x: x[0])272+ return ", ".join(x[1] for x in rv), any_prefix_is_slashadded:typer/_click/globals.py+61 added
1+from threading import local2+from typing import TYPE_CHECKING, Literal, Union, cast, overload3+4+if TYPE_CHECKING:5+ from .core import Context6+7+_local = local()8+9+10+@overload11+def get_current_context(silent: Literal[False] = False) -> "Context": ...12+13+14+@overload15+def get_current_context(silent: bool = ...) -> Union["Context", None]: ...16+17+18+def get_current_context(silent: bool = False) -> Union["Context", None]:19+ """Returns the current click context. This can be used as a way to20+ access the current context object from anywhere. This is a more implicit21+ alternative to the `pass_context` decorator. This function is22+ primarily useful for helpers such as `echo` which might be23+ interested in changing its behavior based on the current context.24+25+ To push the current context, `Context.scope` can be used.26+ """27+ try:28+ return cast("Context", _local.stack[-1])29+ except (AttributeError, IndexError) as e:30+ if not silent:31+ raise RuntimeError(32+ "There is no active click context."33+ ) from e # pragma: no cover34+35+ return None36+37+38+def push_context(ctx: "Context") -> None:39+ """Pushes a new context to the current stack."""40+ _local.__dict__.setdefault("stack", []).append(ctx)41+42+43+def pop_context() -> None:44+ """Removes the top level from the stack."""45+ _local.stack.pop()46+47+48+def resolve_color_default(color: bool | None = None) -> bool | None:49+ """Internal helper to get the default value of the color flag. If a50+ value is passed it's returned unchanged, otherwise it's looked up from51+ the current context.52+ """53+ if color is not None:54+ return color55+56+ ctx = get_current_context(silent=True)57+58+ if ctx is not None:59+ return ctx.color60+61+ return Noneadded:typer/_click/LICENSE.txt+28 added
1+Copyright 2014 Pallets2+3+Redistribution and use in source and binary forms, with or without4+modification, are permitted provided that the following conditions are5+met:6+7+1. Redistributions of source code must retain the above copyright8+ notice, this list of conditions and the following disclaimer.9+10+2. Redistributions in binary form must reproduce the above copyright11+ notice, this list of conditions and the following disclaimer in the12+ documentation and/or other materials provided with the distribution.13+14+3. Neither the name of the copyright holder nor the names of its15+ contributors may be used to endorse or promote products derived from16+ this software without specific prior written permission.17+18+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.added:typer/_click/parser.py+459 added
1+"""2+This module started out as largely a copy paste from the stdlib's3+optparse module with the features removed that we do not need from4+optparse because we implement them in Click on a higher level (for5+instance type handling, help formatting and a lot more).6+7+The plan is to remove more and more from here over time.8+9+The reason this is a different module and not optparse from the stdlib10+is that there are differences in 2.x and 3.x about the error messages11+generated and optparse in the stdlib uses gettext for no good reason12+and might cause us issues.13+14+Click uses parts of optparse written by Gregory P. Ward and maintained15+by the Python Software Foundation. This is limited to code in parser.py.16+17+Copyright 2001-2006 Gregory P. Ward. All rights reserved.18+Copyright 2002-2006 Python Software Foundation. All rights reserved.19+"""20+21+# This code uses parts of optparse written by Gregory P. Ward and22+# maintained by the Python Software Foundation.23+# Copyright 2001-2006 Gregory P. Ward24+# Copyright 2002-2006 Python Software Foundation25+from collections import deque26+from collections.abc import Sequence27+from typing import (28+ TYPE_CHECKING,29+ Any,30+ TypeVar,31+ Union,32+)33+34+from .exceptions import BadArgumentUsage, BadOptionUsage, NoSuchOption, UsageError35+36+if TYPE_CHECKING:37+ from typer.core import TyperArgument as CoreArgument38+ from typer.core import TyperOption as CoreOption39+40+ from .core import Context41+ from .core import Parameter as CoreParameter42+43+V = TypeVar("V")44+45+46+def _unpack_args(47+ args: Sequence[str], nargs_spec: Sequence[int]48+) -> tuple[Sequence[str | Sequence[str | None] | None], list[str]]:49+ """Given an iterable of arguments and an iterable of nargs specifications,50+ it returns a tuple with all the unpacked arguments at the first index51+ and all remaining arguments as the second.52+53+ The nargs specification is the number of arguments that should be consumed54+ or `-1` to indicate that this position should eat up all the remainders.55+ """56+ args = deque(args)57+ nargs_spec = deque(nargs_spec)58+ rv: list[str | tuple[str | None, ...] | None] = []59+ spos: int | None = None60+61+ def _fetch(c: deque[V]) -> V | None:62+ try:63+ if spos is None:64+ return c.popleft()65+ else:66+ return c.pop()67+ except IndexError:68+ return None69+70+ while nargs_spec:71+ nargs = _fetch(nargs_spec)72+ assert nargs is not None73+74+ if nargs == 1:75+ rv.append(_fetch(args))76+ elif nargs > 1:77+ x = [_fetch(args) for _ in range(nargs)]78+79+ # If we're reversed, we're pulling in the arguments in reverse,80+ # so we need to turn them around.81+ if spos is not None:82+ x.reverse()83+84+ rv.append(tuple(x))85+ elif nargs < 0:86+ if spos is not None: # pragma: no cover87+ raise TypeError("Cannot have two nargs < 0")88+89+ spos = len(rv)90+ rv.append(None)91+92+ # spos is the position of the wildcard (star). If it's not `None`,93+ # we fill it with the remainder.94+ if spos is not None:95+ rv[spos] = tuple(args)96+ args = []97+ rv[spos + 1 :] = reversed(rv[spos + 1 :])98+99+ return tuple(rv), list(args)100+101+102+def _split_opt(opt: str) -> tuple[str, str]:103+ first = opt[:1]104+ if first.isalnum():105+ return "", opt106+ if opt[1:2] == first:107+ return opt[:2], opt[2:]108+ return first, opt[1:]109+110+111+def _normalize_opt(opt: str, ctx: Union["Context", None]) -> str:112+ if ctx is None or ctx.token_normalize_func is None:113+ return opt114+ prefix, opt = _split_opt(opt)115+ return f"{prefix}{ctx.token_normalize_func(opt)}"116+117+118+class _Option:119+ def __init__(120+ self,121+ obj: "CoreOption",122+ opts: Sequence[str],123+ dest: str | None,124+ action: str = "store",125+ nargs: int = 1,126+ const: Any | None = None,127+ ):128+ self._short_opts = []129+ self._long_opts = []130+ self.prefixes: set[str] = set()131+132+ for opt in opts:133+ prefix, value = _split_opt(opt)134+ if not prefix: # pragma: no cover135+ raise ValueError(f"Invalid start character for option ({opt})")136+ self.prefixes.add(prefix[0])137+ if len(prefix) == 1 and len(value) == 1:138+ self._short_opts.append(opt)139+ else:140+ self._long_opts.append(opt)141+ self.prefixes.add(prefix)142+143+ self.dest = dest144+ self.action = action145+ self.nargs = nargs146+ self.const = const147+ self.obj = obj148+149+ @property150+ def takes_value(self) -> bool:151+ return self.action in ("store", "append")152+153+ def process(self, value: Any, state: "_ParsingState") -> None:154+ if self.action == "store":155+ state.opts[self.dest] = value # type: ignore156+ elif self.action == "store_const":157+ state.opts[self.dest] = self.const # type: ignore158+ elif self.action == "append":159+ state.opts.setdefault(self.dest, []).append(value) # type: ignore160+ elif self.action == "append_const":161+ state.opts.setdefault(self.dest, []).append(self.const) # type: ignore162+ elif self.action == "count":163+ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore164+ else: # pragma: no cover165+ raise ValueError(f"unknown action '{self.action}'")166+ state.order.append(self.obj)167+168+169+class _Argument:170+ def __init__(self, obj: "CoreArgument", dest: str | None, nargs: int = 1):171+ self.dest = dest172+ self.nargs = nargs173+ self.obj = obj174+175+ def process(176+ self,177+ value: str | Sequence[str | None] | None,178+ state: "_ParsingState",179+ ) -> None:180+ if self.nargs > 1:181+ assert value is not None182+ holes = sum(1 for x in value if x is None)183+ if holes == len(value):184+ value = None185+ elif holes != 0:186+ raise BadArgumentUsage(187+ f"Argument {self.dest!r} takes {self.nargs} values."188+ )189+190+ if self.nargs == -1 and self.obj.envvar is not None and value == ():191+ # Replace empty tuple with None so that a value from the192+ # environment may be tried.193+ value = None194+195+ state.opts[self.dest] = value # type: ignore196+ state.order.append(self.obj)197+198+199+class _ParsingState:200+ def __init__(self, rargs: list[str]) -> None:201+ self.opts: dict[str, Any] = {}202+ self.largs: list[str] = []203+ self.rargs = rargs204+ self.order: list[CoreParameter] = []205+206+207+class _OptionParser:208+ """The option parser is an internal class that is ultimately used to209+ parse options and arguments. It's modelled after optparse and brings210+ a similar but vastly simplified API. It should generally not be used211+ directly as the high level Click classes wrap it for you.212+213+ It's not nearly as extensible as optparse or argparse as it does not214+ implement features that are implemented on a higher level (such as215+ types or defaults).216+ """217+218+ def __init__(self, ctx: Union["Context", None] = None) -> None:219+ self.ctx = ctx220+ # This controls how the parser deals with interspersed arguments.221+ # If this is set to `False`, the parser will stop on the first222+ # non-option. Click uses this to implement nested subcommands223+ # safely.224+ self.allow_interspersed_args: bool = True225+ # This tells the parser how to deal with unknown options. By226+ # default it will error out (which is sensible), but there is a227+ # second mode where it will ignore it and continue processing228+ # after shifting all the unknown options into the resulting args.229+ self.ignore_unknown_options: bool = False230+231+ if ctx is not None:232+ self.allow_interspersed_args = ctx.allow_interspersed_args233+ self.ignore_unknown_options = ctx.ignore_unknown_options234+235+ self._short_opt: dict[str, _Option] = {}236+ self._long_opt: dict[str, _Option] = {}237+ self._opt_prefixes = {"-", "--"}238+ self._args: list[_Argument] = []239+240+ def add_option(241+ self,242+ obj: "CoreOption",243+ opts: Sequence[str],244+ dest: str | None,245+ action: str = "store",246+ nargs: int = 1,247+ const: Any | None = None,248+ ) -> None:249+ """Adds a new option named `dest` to the parser. The destination250+ is not inferred (unlike with optparse) and needs to be explicitly251+ provided. Action can be any of ``store``, ``store_const``,252+ ``append``, ``append_const`` or ``count``.253+254+ The `obj` can be used to identify the option in the order list255+ that is returned from the parser.256+ """257+ opts = [_normalize_opt(opt, self.ctx) for opt in opts]258+ option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const)259+ self._opt_prefixes.update(option.prefixes)260+ for opt in option._short_opts:261+ self._short_opt[opt] = option262+ for opt in option._long_opts:263+ self._long_opt[opt] = option264+265+ def add_argument(266+ self, obj: "CoreArgument", dest: str | None, nargs: int = 1267+ ) -> None:268+ """Adds a positional argument named `dest` to the parser.269+270+ The `obj` can be used to identify the option in the order list271+ that is returned from the parser.272+ """273+ self._args.append(_Argument(obj, dest=dest, nargs=nargs))274+275+ def parse_args(276+ self, args: list[str]277+ ) -> tuple[dict[str, Any], list[str], list["CoreParameter"]]:278+ """Parses positional arguments and returns ``(values, args, order)``279+ for the parsed options and arguments as well as the leftover280+ arguments if there are any. The order is a list of objects as they281+ appear on the command line. If arguments appear multiple times they282+ will be memorized multiple times as well.283+ """284+ state = _ParsingState(args)285+ try:286+ self._process_args_for_options(state)287+ self._process_args_for_args(state)288+ except UsageError:289+ if self.ctx is None or not self.ctx.resilient_parsing:290+ raise291+ return state.opts, state.largs, state.order292+293+ def _process_args_for_args(self, state: _ParsingState) -> None:294+ pargs, args = _unpack_args(295+ state.largs + state.rargs, [x.nargs for x in self._args]296+ )297+298+ for idx, arg in enumerate(self._args):299+ arg.process(pargs[idx], state)300+301+ state.largs = args302+ state.rargs = []303+304+ def _process_args_for_options(self, state: _ParsingState) -> None:305+ while state.rargs:306+ arg = state.rargs.pop(0)307+ arglen = len(arg)308+ # Double dashes always handled explicitly regardless of what309+ # prefixes are valid.310+ if arg == "--":311+ return312+ elif arg[:1] in self._opt_prefixes and arglen > 1:313+ self._process_opts(arg, state)314+ elif self.allow_interspersed_args:315+ state.largs.append(arg)316+ else:317+ state.rargs.insert(0, arg)318+ return319+320+ # Say this is the original argument list:321+ # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]322+ # ^323+ # (we are about to process arg(i)).324+ #325+ # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of326+ # [arg0, ..., arg(i-1)] (any options and their arguments will have327+ # been removed from largs).328+ #329+ # The while loop will usually consume 1 or more arguments per pass.330+ # If it consumes 1 (eg. arg is an option that takes no arguments),331+ # then after _process_arg() is done the situation is:332+ #333+ # largs = subset of [arg0, ..., arg(i)]334+ # rargs = [arg(i+1), ..., arg(N-1)]335+ #336+ # If allow_interspersed_args is false, largs will always be337+ # *empty* -- still a subset of [arg0, ..., arg(i-1)], but338+ # not a very interesting subset!339+340+ def _match_long_opt(341+ self, opt: str, explicit_value: str | None, state: _ParsingState342+ ) -> None:343+ if opt not in self._long_opt:344+ from difflib import get_close_matches345+346+ possibilities = get_close_matches(opt, self._long_opt)347+ raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)348+349+ option = self._long_opt[opt]350+ if option.takes_value:351+ # At this point it's safe to modify rargs by injecting the352+ # explicit value, because no exception is raised in this353+ # branch. This means that the inserted value will be fully354+ # consumed.355+ if explicit_value is not None:356+ state.rargs.insert(0, explicit_value)357+358+ value = self._get_value_from_state(opt, option, state)359+360+ elif explicit_value is not None: # pragma: no cover361+ raise BadOptionUsage(opt, f"Option {opt!r} does not take a value.")362+363+ else:364+ value = None365+366+ option.process(value, state)367+368+ def _match_short_opt(self, arg: str, state: _ParsingState) -> None:369+ stop = False370+ i = 1371+ prefix = arg[0]372+ unknown_options = []373+374+ for ch in arg[1:]:375+ opt = _normalize_opt(f"{prefix}{ch}", self.ctx)376+ option = self._short_opt.get(opt)377+ i += 1378+379+ if not option:380+ if self.ignore_unknown_options:381+ unknown_options.append(ch)382+ continue383+ raise NoSuchOption(opt, ctx=self.ctx)384+ if option.takes_value:385+ # Any characters left in arg? Pretend they're the386+ # next arg, and stop consuming characters of arg.387+ if i < len(arg):388+ state.rargs.insert(0, arg[i:])389+ stop = True390+391+ value = self._get_value_from_state(opt, option, state)392+393+ else:394+ value = None395+396+ option.process(value, state)397+398+ if stop:399+ break400+401+ # If we got any unknown options we recombine the string of the402+ # remaining options and re-attach the prefix, then report that403+ # to the state as new 'largs'. This way there is basic combinatorics404+ # that can be achieved while still ignoring unknown arguments.405+ if self.ignore_unknown_options and unknown_options:406+ state.largs.append(f"{prefix}{''.join(unknown_options)}")407+408+ def _get_value_from_state(409+ self, option_name: str, option: _Option, state: _ParsingState410+ ) -> str | Sequence[str]:411+ nargs = option.nargs412+413+ value: str | Sequence[str]414+415+ if len(state.rargs) < nargs:416+ msg = "an argument." if nargs == 1 else f"{nargs} arguments."417+ raise BadOptionUsage(418+ option_name,419+ f"Option {option_name!r} requires {msg}",420+ )421+ elif nargs == 1:422+ value = state.rargs.pop(0)423+ else:424+ value = tuple(state.rargs[:nargs])425+ del state.rargs[:nargs]426+427+ return value428+429+ def _process_opts(self, arg: str, state: _ParsingState) -> None:430+ explicit_value = None431+ # Long option handling happens in two parts. The first part is432+ # supporting explicitly attached values. In any case, we will try433+ # to long match the option first.434+ if "=" in arg:435+ long_opt, explicit_value = arg.split("=", 1)436+ else:437+ long_opt = arg438+ norm_long_opt = _normalize_opt(long_opt, self.ctx)439+440+ # At this point we will match the (assumed) long option through441+ # the long option matching code. Note that this allows options442+ # like "-foo" to be matched as long options.443+ try:444+ self._match_long_opt(norm_long_opt, explicit_value, state)445+ except NoSuchOption:446+ # At this point the long option matching failed, and we need447+ # to try with short options. However there is a special rule448+ # which says, that if we have a two character options prefix449+ # (applies to "--foo" for instance), we do not dispatch to the450+ # short option code and will instead raise the no option451+ # error.452+ if arg[:2] not in self._opt_prefixes:453+ self._match_short_opt(arg, state)454+ return455+456+ if not self.ignore_unknown_options:457+ raise458+459+ state.largs.append(arg)added:typer/_click/py.typed
added:typer/_click/shell_completion.py+306 added
1+import re2+from abc import ABC, abstractmethod3+from collections.abc import MutableMapping4+from typing import Any, ClassVar, TypeVar5+6+from .core import Command, Context, Parameter, ParameterSource7+8+9+class CompletionItem:10+ """Represents a completion value and metadata about the value. The11+ default metadata is ``type`` to indicate special shell handling,12+ and ``help`` if a shell supports showing a help string next to the13+ value.14+15+ Arbitrary parameters can be passed when creating the object, and16+ accessed using ``item.attr``. If an attribute wasn't passed,17+ accessing it returns ``None``.18+ """19+20+ __slots__ = ("value", "type", "help", "_info")21+22+ def __init__(23+ self,24+ value: Any,25+ type: str = "plain",26+ help: str | None = None,27+ **kwargs: Any,28+ ) -> None:29+ self.value: Any = value30+ self.type: str = type31+ self.help: str | None = help32+ self._info = kwargs33+34+ def __getattr__(self, name: str) -> Any:35+ return self._info.get(name)36+37+38+class ShellComplete(ABC):39+ """Base class for providing shell completion support. A subclass for40+ a given shell will override attributes and methods to implement the41+ completion instructions (``source`` and ``complete``).42+ """43+44+ name: ClassVar[str]45+ """Name to register the shell as with `add_completion_class`.46+ This is used in completion instructions (``{name}_source`` and47+ ``{name}_complete``).48+ """49+50+ source_template: ClassVar[str]51+ """Completion script template formatted by `source`. This must52+ be provided by subclasses.53+ """54+55+ def __init__(56+ self,57+ cli: Command,58+ ctx_args: MutableMapping[str, Any],59+ prog_name: str,60+ complete_var: str,61+ ) -> None:62+ self.cli = cli63+ self.ctx_args = ctx_args64+ self.prog_name = prog_name65+ self.complete_var = complete_var66+67+ @property68+ def func_name(self) -> str:69+ """The name of the shell function defined by the completion70+ script.71+ """72+ safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)73+ return f"_{safe_name}_completion"74+75+ @abstractmethod76+ def source_vars(self) -> dict[str, Any]:77+ """Vars for formatting `source_template`."""78+ pass # pragma: no cover79+80+ def source(self) -> str:81+ """Produce the shell script that defines the completion82+ function. By default this ``%``-style formats83+ `source_template` with the dict returned by `source_vars`.84+ """85+ return self.source_template % self.source_vars()86+87+ @abstractmethod88+ def get_completion_args(self) -> tuple[list[str], str]:89+ """Use the env vars defined by the shell script to return a90+ tuple of ``args, incomplete``. This must be implemented by91+ subclasses.92+ """93+ pass # pragma: no cover94+95+ def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:96+ """Determine the context and last complete command or parameter97+ from the complete args. Call that object's ``shell_complete``98+ method to get the completions for the incomplete value.99+ """100+ ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)101+ obj, incomplete = _resolve_incomplete(ctx, args, incomplete)102+ return obj.shell_complete(ctx, incomplete)103+104+ @abstractmethod105+ def format_completion(self, item: CompletionItem) -> str:106+ """Format a completion item into the form recognized by the107+ shell script. This must be implemented by subclasses.108+ """109+ pass # pragma: no cover110+111+ def complete(self) -> str:112+ """Produce the completion data to send back to the shell.113+114+ By default this calls `get_completion_args`, gets the115+ completions, then calls `format_completion` for each116+ completion.117+ """118+ args, incomplete = self.get_completion_args()119+ completions = self.get_completions(args, incomplete)120+ out = [self.format_completion(item) for item in completions]121+ return "\n".join(out)122+123+124+ShellCompleteType = TypeVar("ShellCompleteType", bound="type[ShellComplete]")125+126+127+_available_shells: dict[str, type[ShellComplete]] = {}128+129+130+def add_completion_class(cls: ShellCompleteType, name: str) -> ShellCompleteType:131+ """Register a `ShellComplete` subclass under the given name.132+ The name will be provided by the completion instruction environment133+ variable during completion.134+ """135+ _available_shells[name] = cls136+137+ return cls138+139+140+def get_completion_class(shell: str) -> type[ShellComplete] | None:141+ """Look up a registered `ShellComplete` subclass by the name142+ provided by the completion instruction environment variable. If the143+ name isn't registered, returns ``None``.144+ """145+ return _available_shells.get(shell)146+147+148+def split_arg_string(string: str) -> list[str]:149+ """Split an argument string as with `shlex.split`, but don't150+ fail if the string is incomplete. Ignores a missing closing quote or151+ incomplete escape sequence and uses the partial token as-is.152+ """153+ import shlex154+155+ lex = shlex.shlex(string, posix=True)156+ lex.whitespace_split = True157+ lex.commenters = ""158+ out = []159+160+ try:161+ for token in lex:162+ out.append(token)163+ except ValueError: # pragma: no cover164+ # Raised when end-of-string is reached in an invalid state. Use165+ # the partial token as-is. The quote or escape character is in166+ # lex.state, not lex.token.167+ out.append(lex.token)168+169+ return out170+171+172+def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:173+ """Determine if the given parameter is an argument that can still174+ accept values.175+ """176+ # avoid circular imports177+ from ..core import TyperArgument178+179+ if not isinstance(param, TyperArgument):180+ return False181+182+ assert param.name is not None183+ # Will be None if expose_value is False.184+ value = ctx.params.get(param.name)185+ return (186+ param.nargs == -1187+ or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE188+ or (189+ param.nargs > 1190+ and isinstance(value, (tuple, list))191+ and len(value) < param.nargs192+ )193+ )194+195+196+def _start_of_option(ctx: Context, value: str) -> bool:197+ """Check if the value looks like the start of an option."""198+ if not value:199+ return False200+201+ c = value[0]202+ return c in ctx._opt_prefixes203+204+205+def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:206+ """Determine if the given parameter is an option that needs a value."""207+ # avoid circular imports208+ from ..core import TyperOption209+210+ if not isinstance(param, TyperOption):211+ return False212+213+ if param.is_flag or param.count:214+ return False215+216+ last_option = None217+218+ for index, arg in enumerate(reversed(args)):219+ if index + 1 > param.nargs:220+ break221+222+ if _start_of_option(ctx, arg):223+ last_option = arg224+ break225+226+ return last_option is not None and last_option in param.opts227+228+229+def _resolve_context(230+ cli: Command,231+ ctx_args: MutableMapping[str, Any],232+ prog_name: str,233+ args: list[str],234+) -> Context:235+ """Produce the context hierarchy starting with the command and236+ traversing the complete arguments. This only follows the commands,237+ it doesn't trigger input prompts or callbacks.238+ """239+ # avoid circular imports240+ from ..core import TyperGroup241+242+ ctx_args["resilient_parsing"] = True243+ with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx:244+ args = ctx._protected_args + ctx.args245+246+ while args:247+ command = ctx.command248+249+ if isinstance(command, TyperGroup):250+ # if not command.chain:251+ name, cmd, args = command.resolve_command(ctx, args)252+253+ if cmd is None:254+ return ctx255+256+ with cmd.make_context(257+ name, args, parent=ctx, resilient_parsing=True258+ ) as sub_ctx:259+ ctx = sub_ctx260+ args = ctx._protected_args + ctx.args261+ else: # pragma: no cover262+ break263+264+ return ctx265+266+267+def _resolve_incomplete(268+ ctx: Context, args: list[str], incomplete: str269+) -> tuple[Command | Parameter, str]:270+ """Find the Click object that will handle the completion of the271+ incomplete value. Return the object and the incomplete value.272+ """273+ # Different shells treat an "=" between a long option name and274+ # value differently. Might keep the value joined, return the "="275+ # as a separate item, or return the split name and value. Always276+ # split and discard the "=" to make completion easier.277+ if incomplete == "=":278+ incomplete = ""279+ elif "=" in incomplete and _start_of_option(ctx, incomplete):280+ name, _, incomplete = incomplete.partition("=")281+ args.append(name)282+283+ # The "--" marker tells Click to stop treating values as options284+ # even if they start with the option character. If it hasn't been285+ # given and the incomplete arg looks like an option, the current286+ # command will provide option name completions.287+ if "--" not in args and _start_of_option(ctx, incomplete):288+ return ctx.command, incomplete289+290+ params = ctx.command.get_params(ctx)291+292+ # If the last complete arg is an option name with an incomplete293+ # value, the option will provide value completions.294+ for param in params:295+ if _is_incomplete_option(ctx, args, param):296+ return param, incomplete297+298+ # It's not an option name or value. The first argument without a299+ # parsed value will provide value completions.300+ for param in params:301+ if _is_incomplete_argument(ctx, param):302+ return param, incomplete303+304+ # There were no unparsed arguments, the command may be a group that305+ # will provide command name completions.306+ return ctx.command, incompleteadded:typer/_click/termui.py+430 added
1+import io2+from collections.abc import Callable, Iterable3+from contextlib import AbstractContextManager4+from typing import IO, TYPE_CHECKING, Any, AnyStr, TextIO, TypeVar, overload5+6+from .exceptions import Abort, UsageError7+from .globals import resolve_color_default8+from .types import ParamType, convert_type9+from .utils import LazyFile, echo10+11+if TYPE_CHECKING:12+ from ._termui_impl import ProgressBar13+14+V = TypeVar("V")15+16+# The prompt functions to use. The doc tools currently override these17+# functions to customize how they work.18+visible_prompt_func: Callable[[str], str] = input19+20+_ansi_colors = {21+ "black": 30,22+ "red": 31,23+ "green": 32,24+ "yellow": 33,25+ "blue": 34,26+ "magenta": 35,27+ "cyan": 36,28+ "white": 37,29+ "reset": 39,30+ "bright_black": 90,31+ "bright_red": 91,32+ "bright_green": 92,33+ "bright_yellow": 93,34+ "bright_blue": 94,35+ "bright_magenta": 95,36+ "bright_cyan": 96,37+ "bright_white": 97,38+}39+_ansi_reset_all = "\033[0m"40+41+42+def hidden_prompt_func(prompt: str) -> str:43+ import getpass44+45+ return getpass.getpass(prompt)46+47+48+def _build_prompt(49+ text: str,50+ suffix: str,51+ show_default: bool = False,52+ default: Any | None = None,53+ show_choices: bool = True,54+ type: ParamType | None = None,55+) -> str:56+ # prevent circular imports57+ from .._types import TyperChoice58+59+ prompt = text60+ if type is not None and show_choices and isinstance(type, TyperChoice):61+ prompt += f" ({', '.join(map(str, type.choices))})"62+ if default is not None and show_default:63+ prompt = f"{prompt} [{_format_default(default)}]"64+ return f"{prompt}{suffix}"65+66+67+def _format_default(default: Any) -> Any:68+ if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):69+ return default.name70+71+ return default72+73+74+def prompt(75+ text: str,76+ default: Any | None = None,77+ hide_input: bool = False,78+ confirmation_prompt: bool | str = False,79+ type: ParamType | Any | None = None,80+ value_proc: Callable[[str], Any] | None = None,81+ prompt_suffix: str = ": ",82+ show_default: bool = True,83+ err: bool = False,84+ show_choices: bool = True,85+) -> Any:86+ """Prompts a user for input. This is a convenience function that can87+ be used to prompt a user for input later.88+89+ If the user aborts the input by sending an interrupt signal, this90+ function will catch it and raise an `Abort` exception.91+ """92+93+ def prompt_func(text: str) -> str:94+ f = hidden_prompt_func if hide_input else visible_prompt_func95+ try:96+ # Write the prompt separately so that we get nice97+ # coloring through colorama on Windows98+ echo(text[:-1], nl=False, err=err)99+ # Echo the last character to stdout to work around an issue where100+ # readline causes backspace to clear the whole line.101+ return f(text[-1:])102+ except (KeyboardInterrupt, EOFError): # pragma: no cover103+ # getpass doesn't print a newline if the user aborts input with ^C.104+ # Allegedly this behavior is inherited from getpass(3).105+ # A doc bug has been filed at https://bugs.python.org/issue24711106+ if hide_input:107+ echo(None, err=err)108+ raise Abort() from None109+110+ if value_proc is None:111+ value_proc = convert_type(type, default)112+113+ prompt = _build_prompt(114+ text, prompt_suffix, show_default, default, show_choices, type115+ )116+117+ if confirmation_prompt:118+ if confirmation_prompt is True:119+ confirmation_prompt = "Repeat for confirmation"120+121+ confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)122+123+ while True:124+ while True:125+ value = prompt_func(prompt)126+ if value:127+ break128+ elif default is not None:129+ value = default130+ break131+ try:132+ result = value_proc(value)133+ except UsageError as e: # pragma: no cover134+ if hide_input:135+ echo("Error: The value you entered was invalid.", err=err)136+ else:137+ echo(f"Error: {e.message}", err=err)138+ continue139+ if not confirmation_prompt:140+ return result141+ while True:142+ value2 = prompt_func(confirmation_prompt)143+ is_empty = not value and not value2144+ if value2 or is_empty:145+ break146+ if value == value2:147+ return result148+ echo("Error: The two entered values do not match.", err=err)149+150+151+def confirm(152+ text: str,153+ default: bool | None = False,154+ abort: bool = False,155+ prompt_suffix: str = ": ",156+ show_default: bool = True,157+ err: bool = False,158+) -> bool:159+ """Prompts for confirmation (yes/no question).160+161+ If the user aborts the input by sending a interrupt signal this162+ function will catch it and raise an `Abort` exception.163+ """164+ prompt = _build_prompt(165+ text,166+ prompt_suffix,167+ show_default,168+ "y/n" if default is None else ("Y/n" if default else "y/N"),169+ )170+171+ while True:172+ try:173+ # Write the prompt separately so that we get nice174+ # coloring through colorama on Windows175+ echo(prompt[:-1], nl=False, err=err)176+ # Echo the last character to stdout to work around an issue where177+ # readline causes backspace to clear the whole line.178+ value = visible_prompt_func(prompt[-1:]).lower().strip()179+ except (KeyboardInterrupt, EOFError): # pragma: no cover180+ raise Abort() from None181+ if value in ("y", "yes"):182+ rv = True183+ elif value in ("n", "no"):184+ rv = False185+ elif default is not None and value == "":186+ rv = default187+ else: # pragma: no cover188+ echo("Error: invalid input", err=err)189+ continue190+ break191+ if abort and not rv:192+ raise Abort()193+ return rv194+195+196+@overload197+def progressbar(198+ *,199+ length: int,200+ label: str | None = None,201+ hidden: bool = False,202+ show_eta: bool = True,203+ show_percent: bool | None = None,204+ show_pos: bool = False,205+ fill_char: str = "#",206+ empty_char: str = "-",207+ bar_template: str = "%(label)s [%(bar)s] %(info)s",208+ info_sep: str = " ",209+ width: int = 36,210+ file: TextIO | None = None,211+ color: bool | None = None,212+ update_min_steps: int = 1,213+) -> "ProgressBar[int]": ...214+215+216+@overload217+def progressbar(218+ iterable: Iterable[V] | None = None,219+ length: int | None = None,220+ label: str | None = None,221+ hidden: bool = False,222+ show_eta: bool = True,223+ show_percent: bool | None = None,224+ show_pos: bool = False,225+ item_show_func: Callable[[V | None], str | None] | None = None,226+ fill_char: str = "#",227+ empty_char: str = "-",228+ bar_template: str = "%(label)s [%(bar)s] %(info)s",229+ info_sep: str = " ",230+ width: int = 36,231+ file: TextIO | None = None,232+ color: bool | None = None,233+ update_min_steps: int = 1,234+) -> "ProgressBar[V]": ...235+236+237+def progressbar(238+ iterable: Iterable[V] | None = None,239+ length: int | None = None,240+ label: str | None = None,241+ hidden: bool = False,242+ show_eta: bool = True,243+ show_percent: bool | None = None,244+ show_pos: bool = False,245+ item_show_func: Callable[[V | None], str | None] | None = None,246+ fill_char: str = "#",247+ empty_char: str = "-",248+ bar_template: str = "%(label)s [%(bar)s] %(info)s",249+ info_sep: str = " ",250+ width: int = 36,251+ file: TextIO | None = None,252+ color: bool | None = None,253+ update_min_steps: int = 1,254+) -> "ProgressBar[V]":255+ """This function creates an iterable context manager that can be used256+ to iterate over something while showing a progress bar. It will257+ either iterate over the `iterable` or `length` items (that are counted258+ up). While iteration happens, this function will print a rendered259+ progress bar to the given `file` (defaults to stdout) and will attempt260+ to calculate remaining time and more. By default, this progress bar261+ will not be rendered if the file is not a terminal.262+263+ The context manager creates the progress bar. When the context264+ manager is entered the progress bar is already created. With every265+ iteration over the progress bar, the iterable passed to the bar is266+ advanced and the bar is updated. When the context manager exits,267+ a newline is printed and the progress bar is finalized on screen.268+269+ Note: The progress bar is currently designed for use cases where the270+ total progress can be expected to take at least several seconds.271+ Because of this, the ProgressBar class object won't display272+ progress that is considered too fast, and progress where the time273+ between steps is less than a second.274+275+ No printing must happen or the progress bar will be unintentionally276+ destroyed.277+ """278+ from ._termui_impl import ProgressBar279+280+ color = resolve_color_default(color)281+ return ProgressBar(282+ iterable=iterable,283+ length=length,284+ hidden=hidden,285+ show_eta=show_eta,286+ show_percent=show_percent,287+ show_pos=show_pos,288+ item_show_func=item_show_func,289+ fill_char=fill_char,290+ empty_char=empty_char,291+ bar_template=bar_template,292+ info_sep=info_sep,293+ file=file,294+ label=label,295+ width=width,296+ color=color,297+ update_min_steps=update_min_steps,298+ )299+300+301+def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:302+ if isinstance(color, int):303+ return f"{38 + offset};5;{color:d}"304+305+ if isinstance(color, (tuple, list)):306+ r, g, b = color307+ return f"{38 + offset};2;{r:d};{g:d};{b:d}"308+309+ return str(_ansi_colors[color] + offset)310+311+312+def style(313+ text: Any,314+ fg: int | tuple[int, int, int] | str | None = None,315+ bg: int | tuple[int, int, int] | str | None = None,316+ bold: bool | None = None,317+ dim: bool | None = None,318+ underline: bool | None = None,319+ overline: bool | None = None,320+ italic: bool | None = None,321+ blink: bool | None = None,322+ reverse: bool | None = None,323+ strikethrough: bool | None = None,324+ reset: bool = True,325+) -> str:326+ """Styles a text with ANSI styles and returns the new string. By327+ default the styling is self contained which means that at the end328+ of the string a reset code is issued. This can be prevented by329+ passing ``reset=False``.330+ """331+ if not isinstance(text, str):332+ text = str(text)333+334+ bits = []335+336+ if fg:337+ try:338+ bits.append(f"\033[{_interpret_color(fg)}m")339+ except KeyError:340+ raise TypeError(f"Unknown color {fg!r}") from None341+342+ if bg:343+ try:344+ bits.append(f"\033[{_interpret_color(bg, 10)}m")345+ except KeyError:346+ raise TypeError(f"Unknown color {bg!r}") from None347+348+ if bold is not None:349+ bits.append(f"\033[{1 if bold else 22}m")350+ if dim is not None:351+ bits.append(f"\033[{2 if dim else 22}m")352+ if underline is not None:353+ bits.append(f"\033[{4 if underline else 24}m")354+ if overline is not None:355+ bits.append(f"\033[{53 if overline else 55}m")356+ if italic is not None:357+ bits.append(f"\033[{3 if italic else 23}m")358+ if blink is not None:359+ bits.append(f"\033[{5 if blink else 25}m")360+ if reverse is not None:361+ bits.append(f"\033[{7 if reverse else 27}m")362+ if strikethrough is not None:363+ bits.append(f"\033[{9 if strikethrough else 29}m")364+ bits.append(text)365+ if reset:366+ bits.append(_ansi_reset_all)367+ return "".join(bits)368+369+370+def secho(371+ message: Any | None = None,372+ file: IO[AnyStr] | None = None,373+ nl: bool = True,374+ err: bool = False,375+ color: bool | None = None,376+ **styles: Any,377+) -> None:378+ """This function combines `echo` and `style` into one call."""379+ if message is not None and not isinstance(message, (bytes, bytearray)):380+ message = style(message, **styles)381+382+ return echo(message, file=file, nl=nl, err=err, color=color)383+384+385+def launch(url: str, wait: bool = False, locate: bool = False) -> int:386+ """This function launches the given URL (or filename) in the default387+ viewer application for this file type. If this is an executable, it388+ might launch the executable in a new session. The return value is389+ the exit code of the launched application. Usually, ``0`` indicates390+ success.391+ """392+ from ._termui_impl import open_url393+394+ return open_url(url, wait=wait, locate=locate)395+396+397+# If this is provided, getchar() calls into this instead. This is used398+# for unittesting purposes.399+_getchar: Callable[[bool], str] | None = None400+401+402+def getchar(echo: bool = False) -> str:403+ """Fetches a single character from the terminal and returns it. This404+ will always return a unicode character and under certain rare405+ circumstances this might return more than one character. The406+ situations which more than one character is returned is when for407+ whatever reason multiple characters end up in the terminal buffer or408+ standard input was not actually a terminal.409+410+ Note that this will always read from the terminal, even if something411+ is piped into the standard input.412+413+ Note for Windows: in rare cases when typing non-ASCII characters, this414+ function might wait for a second character and then return both at once.415+ This is because certain Unicode characters look like special-key markers.416+ """417+ global _getchar418+419+ if _getchar is None:420+ from ._termui_impl import getchar as f421+422+ _getchar = f423+424+ return _getchar(echo)425+426+427+def raw_terminal() -> AbstractContextManager[int]:428+ from ._termui_impl import raw_terminal as f429+430+ return f()added:typer/_click/testing.py+366 added
1+import contextlib2+import io3+import os4+import shlex5+import sys6+from collections.abc import Iterator, Mapping, Sequence7+from types import TracebackType8+from typing import IO, TYPE_CHECKING, Any, BinaryIO, cast9+10+from . import _compat, formatting, termui, utils11+from ._compat import _find_binary_reader12+from .core import Command13+14+if TYPE_CHECKING:15+ from _typeshed import ReadableBuffer16+17+18+class BytesIOCopy(io.BytesIO):19+ """Patch ``io.BytesIO`` to let the written stream be copied to another."""20+21+ def __init__(self, copy_to: io.BytesIO) -> None:22+ super().__init__()23+ self.copy_to = copy_to24+25+ def flush(self) -> None:26+ super().flush()27+ self.copy_to.flush()28+29+ def write(self, b: "ReadableBuffer") -> int:30+ self.copy_to.write(b)31+ return super().write(b)32+33+34+class StreamMixer:35+ """Mixes `<stdout>` and `<stderr>` streams.36+37+ The result is available in the ``output`` attribute.38+ """39+40+ def __init__(self) -> None:41+ self.output: io.BytesIO = io.BytesIO()42+ self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)43+ self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)44+45+ def __del__(self) -> None:46+ """47+ Guarantee that embedded file-like objects are closed in a48+ predictable order, protecting against races between49+ self.output being closed and other streams being flushed on close50+ """51+ self.stderr.close()52+ self.stdout.close()53+ self.output.close()54+55+56+class _NamedTextIOWrapper(io.TextIOWrapper):57+ def __init__(self, buffer: BinaryIO, name: str, mode: str, **kwargs: Any) -> None:58+ super().__init__(buffer, **kwargs)59+ self._name = name60+ self._mode = mode61+62+ @property63+ def name(self) -> str:64+ return self._name # pragma: no cover65+66+ @property67+ def mode(self) -> str:68+ return self._mode # pragma: no cover69+70+71+def make_input_stream(input: str | bytes | IO[Any] | None, charset: str) -> BinaryIO:72+ # Is already an input stream.73+ if hasattr(input, "read"):74+ rv = _find_binary_reader(cast("IO[Any]", input))75+76+ if rv is not None:77+ return rv78+79+ raise TypeError(80+ "Could not find binary reader for input stream."81+ ) # pragma: no cover82+83+ if input is None:84+ input = b""85+ elif isinstance(input, str):86+ input = input.encode(charset)87+88+ return io.BytesIO(input)89+90+91+class Result:92+ """Holds the captured result of an invoked CLI script."""93+94+ def __init__(95+ self,96+ runner: "CliRunner",97+ stdout_bytes: bytes,98+ stderr_bytes: bytes,99+ output_bytes: bytes,100+ return_value: Any,101+ exit_code: int,102+ exception: BaseException | None,103+ exc_info: tuple[type[BaseException], BaseException, TracebackType]104+ | None = None,105+ ):106+ self.runner = runner107+ self.stdout_bytes = stdout_bytes108+ self.stderr_bytes = stderr_bytes109+ self.output_bytes = output_bytes110+ self.return_value = return_value111+ self.exit_code = exit_code112+ self.exception = exception113+ self.exc_info = exc_info114+115+ @property116+ def output(self) -> str:117+ """The terminal output as unicode string, as the user would see it."""118+ return self.output_bytes.decode(self.runner.charset, "replace").replace(119+ "\r\n", "\n"120+ )121+122+ @property123+ def stdout(self) -> str:124+ """The standard output as unicode string."""125+ return self.stdout_bytes.decode(self.runner.charset, "replace").replace(126+ "\r\n", "\n"127+ )128+129+ @property130+ def stderr(self) -> str:131+ """The standard error as unicode string."""132+ return self.stderr_bytes.decode(self.runner.charset, "replace").replace(133+ "\r\n", "\n"134+ )135+136+ def __repr__(self) -> str:137+ exc_str = repr(self.exception) if self.exception else "okay"138+ return f"<{type(self).__name__} {exc_str}>"139+140+141+class CliRunner:142+ """The CLI runner provides functionality to invoke a Click command line143+ script for unittesting purposes in a isolated environment. This only144+ works in single-threaded systems without any concurrency as it changes the145+ global interpreter state.146+ """147+148+ def __init__(149+ self,150+ charset: str = "utf-8",151+ env: Mapping[str, str | None] | None = None,152+ catch_exceptions: bool = True,153+ ) -> None:154+ self.charset = charset155+ self.env: Mapping[str, str | None] = env or {}156+ self.catch_exceptions = catch_exceptions157+158+ def get_default_prog_name(self, cli: Command) -> str:159+ """Given a command object it will return the default program name160+ for it. The default is the `name` attribute or ``"root"`` if not161+ set.162+ """163+ return cli.name or "root"164+165+ def make_env(166+ self, overrides: Mapping[str, str | None] | None = None167+ ) -> Mapping[str, str | None]:168+ """Returns the environment overrides for invoking a script."""169+ rv = dict(self.env)170+ if overrides:171+ rv.update(overrides)172+ return rv173+174+ @contextlib.contextmanager175+ def isolation(176+ self,177+ input: str | bytes | IO[Any] | None = None,178+ env: Mapping[str, str | None] | None = None,179+ color: bool = False,180+ ) -> Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:181+ """A context manager that sets up the isolation for invoking of a182+ command line tool. This sets up `<stdin>` with the given input data183+ and `os.environ` with the overrides from the given dictionary.184+ This also rebinds some internals in Click to be mocked (like the185+ prompt functionality).186+ """187+ bytes_input = make_input_stream(input, self.charset)188+189+ old_stdin = sys.stdin190+ old_stdout = sys.stdout191+ old_stderr = sys.stderr192+ old_forced_width = formatting.FORCED_WIDTH193+ formatting.FORCED_WIDTH = 80194+195+ env = self.make_env(env)196+197+ stream_mixer = StreamMixer()198+199+ sys.stdin = text_input = _NamedTextIOWrapper(200+ bytes_input, encoding=self.charset, name="<stdin>", mode="r"201+ )202+203+ sys.stdout = _NamedTextIOWrapper(204+ stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"205+ )206+207+ sys.stderr = _NamedTextIOWrapper(208+ stream_mixer.stderr,209+ encoding=self.charset,210+ name="<stderr>",211+ mode="w",212+ errors="backslashreplace",213+ )214+215+ def visible_input(prompt: str | None = None) -> str:216+ sys.stdout.write(prompt or "")217+ try:218+ val = next(text_input).rstrip("\r\n")219+ except StopIteration as e: # pragma: no cover220+ raise EOFError() from e221+ sys.stdout.write(f"{val}\n")222+ sys.stdout.flush()223+ return val224+225+ def hidden_input(prompt: str | None = None) -> str:226+ sys.stdout.write(f"{prompt or ''}\n")227+ sys.stdout.flush()228+ try:229+ return next(text_input).rstrip("\r\n")230+ except StopIteration as e: # pragma: no cover231+ raise EOFError() from e232+233+ def _getchar(echo: bool) -> str:234+ char = sys.stdin.read(1)235+236+ if echo:237+ sys.stdout.write(char)238+239+ sys.stdout.flush()240+ return char241+242+ default_color = color243+244+ def should_strip_ansi(245+ stream: IO[Any] | None = None, color: bool | None = None246+ ) -> bool:247+ if color is None:248+ return not default_color249+ return not color250+251+ old_visible_prompt_func = termui.visible_prompt_func252+ old_hidden_prompt_func = termui.hidden_prompt_func253+ old__getchar_func = termui._getchar254+ old_should_strip_ansi = utils.should_strip_ansi # type: ignore[attr-defined]255+ old__compat_should_strip_ansi = _compat.should_strip_ansi256+ termui.visible_prompt_func = visible_input257+ termui.hidden_prompt_func = hidden_input # ty: ignore[invalid-assignment]258+ termui._getchar = _getchar259+ utils.should_strip_ansi = should_strip_ansi # type: ignore260+ _compat.should_strip_ansi = should_strip_ansi # ty: ignore[invalid-assignment]261+262+ old_env = {}263+ try:264+ for key, value in env.items():265+ old_env[key] = os.environ.get(key)266+ if value is None:267+ try:268+ del os.environ[key]269+ except Exception: # pragma: no cover270+ pass271+ else:272+ os.environ[key] = value273+ yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)274+ finally:275+ for key, value in old_env.items():276+ if value is None:277+ try:278+ del os.environ[key]279+ except Exception: # pragma: no cover280+ pass281+ else:282+ os.environ[key] = value283+ sys.stdout = old_stdout284+ sys.stderr = old_stderr285+ sys.stdin = old_stdin286+ termui.visible_prompt_func = old_visible_prompt_func287+ termui.hidden_prompt_func = old_hidden_prompt_func288+ termui._getchar = old__getchar_func289+ utils.should_strip_ansi = old_should_strip_ansi # type: ignore[attr-defined]290+ _compat.should_strip_ansi = old__compat_should_strip_ansi291+ formatting.FORCED_WIDTH = old_forced_width292+293+ def invoke(294+ self,295+ cli: Command,296+ args: str | Sequence[str] | None = None,297+ input: str | bytes | IO[Any] | None = None,298+ env: Mapping[str, str | None] | None = None,299+ catch_exceptions: bool | None = None,300+ color: bool = False,301+ **extra: Any,302+ ) -> Result:303+ """Invokes a command in an isolated environment. The arguments are304+ forwarded directly to the command line script, the `extra` keyword305+ arguments are passed to the `Command.main` function of306+ the command.307+ """308+ exc_info = None309+ if catch_exceptions is None:310+ catch_exceptions = self.catch_exceptions311+312+ with self.isolation(input=input, env=env, color=color) as outstreams:313+ return_value = None314+ exception: BaseException | None = None315+ exit_code = 0316+317+ if isinstance(args, str):318+ args = shlex.split(args)319+320+ try:321+ prog_name = extra.pop("prog_name")322+ except KeyError:323+ prog_name = self.get_default_prog_name(cli)324+325+ try:326+ return_value = cli.main(args=args or (), prog_name=prog_name, **extra)327+ except SystemExit as e:328+ exc_info = sys.exc_info()329+ e_code = cast("int | Any | None", e.code)330+331+ if e_code is None:332+ e_code = 0333+334+ if e_code != 0:335+ exception = e336+337+ if not isinstance(e_code, int):338+ sys.stdout.write(str(e_code))339+ sys.stdout.write("\n")340+ e_code = 1341+342+ exit_code = e_code343+344+ except Exception as e:345+ if not catch_exceptions:346+ raise347+ exception = e348+ exit_code = 1349+ exc_info = sys.exc_info()350+ finally:351+ sys.stdout.flush()352+ sys.stderr.flush()353+ stdout = outstreams[0].getvalue()354+ stderr = outstreams[1].getvalue()355+ output = outstreams[2].getvalue()356+357+ return Result(358+ runner=self,359+ stdout_bytes=stdout,360+ stderr_bytes=stderr,361+ output_bytes=output,362+ return_value=return_value,363+ exit_code=exit_code,364+ exception=exception,365+ exc_info=exc_info, # type: ignore366+ )added:typer/_click/types.py+695 added
1+import os2+import sys3+from collections.abc import Callable, Sequence4+from datetime import datetime5+from typing import (6+ IO,7+ TYPE_CHECKING,8+ Any,9+ ClassVar,10+ Literal,11+ NoReturn,12+ TypedDict,13+ TypeGuard,14+ TypeVar,15+ Union,16+ cast,17+)18+19+from ._compat import _get_argv_encoding, open_stream20+from .exceptions import BadParameter21+from .utils import LazyFile, format_filename, safecall22+23+if TYPE_CHECKING:24+ from .core import Context, Parameter25+ from .shell_completion import CompletionItem26+27+ParamTypeValue = TypeVar("ParamTypeValue")28+29+30+class ParamType:31+ """Represents the type of a parameter. Validates and converts values32+ from the command line or Python into the correct type.33+34+ To implement a custom type, subclass and implement at least the35+ following:36+37+ - The `name` class attribute must be set.38+ - Calling an instance of the type with ``None`` must return39+ ``None``. This is already implemented by default.40+ - `convert` must convert string values to the correct type.41+ - `convert` must accept values that are already the correct42+ type.43+ - It must be able to convert a value if the ``ctx`` and ``param``44+ arguments are ``None``. This can occur when converting prompt45+ input.46+ """47+48+ is_composite: ClassVar[bool] = False49+ arity: ClassVar[int] = 150+ name: str51+52+ # if a list of this type is expected and the value is pulled from a53+ # string environment variable, this is what splits it up. `None`54+ # means any whitespace. For all parameters the general rule is that55+ # whitespace splits them up. The exception are paths and files which56+ # are split by ``os.path.pathsep`` by default (":" on Unix and ";" on57+ # Windows).58+ envvar_list_splitter: ClassVar[str | None] = None59+60+ def __call__(61+ self,62+ value: Any,63+ param: Union["Parameter", None] = None,64+ ctx: Union["Context", None] = None,65+ ) -> Any:66+ if value is not None:67+ return self.convert(value, param, ctx)68+69+ def get_metavar(self, param: "Parameter", ctx: "Context") -> str | None:70+ """Returns the metavar default for this param if it provides one."""71+ pass # pragma: no cover72+73+ def get_missing_message(74+ self, param: "Parameter", ctx: Union["Context", None]75+ ) -> str | None:76+ """Optionally might return extra information about a missing77+ parameter.78+ """79+ pass # pragma: no cover80+81+ def convert(82+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]83+ ) -> Any:84+ pass # pragma: no cover85+86+ def split_envvar_value(self, rv: str) -> Sequence[str]:87+ """Given a value from an environment variable this splits it up88+ into small chunks depending on the defined envvar list splitter.89+90+ If the splitter is set to `None`, which means that whitespace splits,91+ then leading and trailing whitespace is ignored. Otherwise, leading92+ and trailing splitters usually lead to empty items being included.93+ """94+ return (rv or "").split(self.envvar_list_splitter)95+96+ def fail(97+ self,98+ message: str,99+ param: Union["Parameter", None] = None,100+ ctx: Union["Context", None] = None,101+ ) -> NoReturn:102+ """Helper method to fail with an invalid value message."""103+ raise BadParameter(message, ctx=ctx, param=param)104+105+ def shell_complete(106+ self, ctx: "Context", param: "Parameter", incomplete: str107+ ) -> list["CompletionItem"]:108+ """Return a list of `CompletionItem` objects for the109+ incomplete value. Most types do not provide completions, but110+ some do, and this allows custom types to provide custom111+ completions as well.112+ """113+ return []114+115+116+class CompositeParamType(ParamType):117+ is_composite = True118+119+ @property120+ def arity(self) -> int: # type: ignore121+ raise NotImplementedError() # pragma: no cover122+123+124+class FuncParamType(ParamType):125+ def __init__(self, func: Callable[[Any], Any]) -> None:126+ self.name: str = getattr(func, "__name__", "function")127+ self.func = func128+129+ def convert(130+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]131+ ) -> Any:132+ try:133+ return self.func(value)134+ except ValueError:135+ try:136+ value = str(value)137+ except UnicodeError: # pragma: no cover138+ assert isinstance(value, bytes)139+ value = value.decode("utf-8", "replace")140+141+ self.fail(value, param, ctx)142+143+144+class StringParamType(ParamType):145+ name = "text"146+147+ def convert(148+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]149+ ) -> Any:150+ if isinstance(value, bytes):151+ enc = _get_argv_encoding()152+ try:153+ value = value.decode(enc)154+ except UnicodeError:155+ fs_enc = sys.getfilesystemencoding()156+ if fs_enc != enc:157+ try:158+ value = value.decode(fs_enc)159+ except UnicodeError:160+ value = value.decode("utf-8", "replace")161+ else:162+ value = value.decode("utf-8", "replace")163+ return value164+ return str(value)165+166+ def __repr__(self) -> str:167+ return "STRING"168+169+170+class DateTime(ParamType):171+ """The DateTime type converts date strings into `datetime` objects.172+173+ The format strings which are checked are configurable, but default to some174+ common (non-timezone aware) ISO 8601 formats.175+176+ When specifying *DateTime* formats, you should only pass a list or a tuple.177+ Other iterables, like generators, may lead to surprising results.178+179+ The format strings are processed using ``datetime.strptime``, and this180+ consequently defines the format strings which are allowed.181+182+ Parsing is tried using each format, in order, and the first format which183+ parses successfully is used.184+ """185+186+ name = "datetime"187+188+ def __init__(self, formats: Sequence[str] | None = None):189+ self.formats: Sequence[str] = formats or [190+ "%Y-%m-%d",191+ "%Y-%m-%dT%H:%M:%S",192+ "%Y-%m-%d %H:%M:%S",193+ ]194+195+ def get_metavar(self, param: "Parameter", ctx: "Context") -> str | None:196+ return f"[{'|'.join(self.formats)}]"197+198+ def _try_to_convert_date(self, value: Any, format: str) -> datetime | None:199+ try:200+ return datetime.strptime(value, format)201+ except ValueError:202+ return None203+204+ def convert(205+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]206+ ) -> Any:207+ if isinstance(value, datetime):208+ return value209+210+ for format in self.formats:211+ converted = self._try_to_convert_date(value, format)212+213+ if converted is not None:214+ return converted215+216+ formats_str = ", ".join(map(repr, self.formats))217+ self.fail(218+ f"{value!r} does not match the formats {formats_str}.",219+ param,220+ ctx,221+ )222+223+ def __repr__(self) -> str:224+ return "DateTime"225+226+227+class _NumberParamTypeBase(ParamType):228+ _number_class: ClassVar[type[Any]]229+230+ def convert(231+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]232+ ) -> Any:233+ try:234+ return self._number_class(value)235+ except ValueError:236+ self.fail(237+ f"{value!r} is not a valid {self.name}.",238+ param,239+ ctx,240+ )241+242+243+class _NumberRangeBase(_NumberParamTypeBase):244+ def __init__(245+ self,246+ min: float | None = None,247+ max: float | None = None,248+ min_open: bool = False,249+ max_open: bool = False,250+ clamp: bool = False,251+ ) -> None:252+ self.min = min253+ self.max = max254+ self.min_open = min_open255+ self.max_open = max_open256+ self.clamp = clamp257+258+ def convert(259+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]260+ ) -> Any:261+ import operator262+263+ rv = super().convert(value, param, ctx)264+ lt_min: bool = self.min is not None and (265+ operator.le if self.min_open else operator.lt266+ )(rv, self.min)267+ gt_max: bool = self.max is not None and (268+ operator.ge if self.max_open else operator.gt269+ )(rv, self.max)270+271+ if self.clamp:272+ if lt_min:273+ return self._clamp(self.min, 1, self.min_open) # type: ignore[arg-type]274+275+ if gt_max:276+ return self._clamp(self.max, -1, self.max_open) # type: ignore[arg-type]277+278+ if lt_min or gt_max:279+ self.fail(280+ f"{rv} is not in the range {self._describe_range()}.",281+ param,282+ ctx,283+ )284+285+ return rv286+287+ def _clamp(self, bound: float, dir: Literal[1, -1], open: bool) -> float:288+ """Find the valid value to clamp to bound in the given289+ direction.290+ """291+ raise NotImplementedError # pragma: no cover292+293+ def _describe_range(self) -> str:294+ """Describe the range for use in help text."""295+ if self.min is None:296+ op = "<" if self.max_open else "<="297+ return f"x{op}{self.max}"298+299+ if self.max is None:300+ op = ">" if self.min_open else ">="301+ return f"x{op}{self.min}"302+303+ lop = "<" if self.min_open else "<="304+ rop = "<" if self.max_open else "<="305+ return f"{self.min}{lop}x{rop}{self.max}"306+307+ def __repr__(self) -> str:308+ clamp = " clamped" if self.clamp else ""309+ return f"<{type(self).__name__} {self._describe_range()}{clamp}>"310+311+312+class IntParamType(_NumberParamTypeBase):313+ name = "integer"314+ _number_class = int315+316+ def __repr__(self) -> str:317+ return "INT"318+319+320+class IntRange(_NumberRangeBase, IntParamType):321+ """Restrict an `INT` value to a range of accepted values. See322+323+ If ``min`` or ``max`` are not passed, any value is accepted in that324+ direction. If ``min_open`` or ``max_open`` are enabled, the325+ corresponding boundary is not included in the range.326+327+ If ``clamp`` is enabled, a value outside the range is clamped to the328+ boundary instead of failing.329+ """330+331+ name = "integer range"332+333+ def _clamp( # type: ignore334+ self, bound: int, dir: Literal[1, -1], open: bool335+ ) -> int:336+ if not open:337+ return bound338+339+ return bound + dir340+341+342+class FloatParamType(_NumberParamTypeBase):343+ name = "float"344+ _number_class = float345+346+ def __repr__(self) -> str:347+ return "FLOAT"348+349+350+class FloatRange(_NumberRangeBase, FloatParamType):351+ """Restrict a `FLOAT` value to a range of accepted352+ values. See `ranges`.353+354+ If ``min`` or ``max`` are not passed, any value is accepted in that355+ direction. If ``min_open`` or ``max_open`` are enabled, the356+ corresponding boundary is not included in the range.357+358+ If ``clamp`` is enabled, a value outside the range is clamped to the359+ boundary instead of failing. This is not supported if either360+ boundary is marked ``open``.361+ """362+363+ name = "float range"364+365+ def __init__(366+ self,367+ min: float | None = None,368+ max: float | None = None,369+ min_open: bool = False,370+ max_open: bool = False,371+ clamp: bool = False,372+ ) -> None:373+ super().__init__(374+ min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp375+ )376+377+ if (min_open or max_open) and clamp:378+ raise TypeError("Clamping is not supported for open bounds.")379+380+ def _clamp(self, bound: float, dir: Literal[1, -1], open: bool) -> float:381+ if not open:382+ return bound383+384+ # Could use math.nextafter here, but clamping an385+ # open float range doesn't seem to be particularly useful. It's386+ # left up to the user to write a callback to do it if needed.387+ raise RuntimeError(388+ "Clamping is not supported for open bounds."389+ ) # pragma: no cover390+391+392+class BoolParamType(ParamType):393+ name = "boolean"394+395+ bool_states: dict[str, bool] = {396+ "1": True,397+ "0": False,398+ "yes": True,399+ "no": False,400+ "true": True,401+ "false": False,402+ "on": True,403+ "off": False,404+ "t": True,405+ "f": False,406+ "y": True,407+ "n": False,408+ # Absence of value is considered False.409+ "": False,410+ }411+ """A mapping of string values to boolean states.412+413+ Mapping is inspired by `configparser.ConfigParser.BOOLEAN_STATES`414+ and extends it.415+ """416+417+ @staticmethod418+ def str_to_bool(value: str | bool) -> bool | None:419+ """Convert a string to a boolean value.420+421+ If the value is already a boolean, it is returned as-is. If the value is a422+ string, it is stripped of whitespaces and lower-cased, then checked against423+ the known boolean states pre-defined in the `BoolParamType.bool_states` mapping424+ above.425+426+ Returns `None` if the value does not match any known boolean state.427+ """428+ if isinstance(value, bool):429+ return value430+ return BoolParamType.bool_states.get(value.strip().lower())431+432+ def convert(433+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]434+ ) -> bool:435+ normalized = self.str_to_bool(value)436+ if normalized is None:437+ states = ", ".join(sorted(self.bool_states))438+ self.fail(439+ f"{value!r} is not a valid boolean. Recognized values: {states}",440+ param,441+ ctx,442+ )443+ return normalized444+445+ def __repr__(self) -> str:446+ return "BOOL"447+448+449+class UUIDParameterType(ParamType):450+ name = "uuid"451+452+ def convert(453+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]454+ ) -> Any:455+ import uuid456+457+ if isinstance(value, uuid.UUID):458+ return value459+460+ value = value.strip()461+462+ try:463+ return uuid.UUID(value)464+ except ValueError:465+ self.fail(f"{value!r} is not a valid UUID.", param, ctx)466+467+ def __repr__(self) -> str:468+ return "UUID"469+470+471+class File(ParamType):472+ """Declares a parameter to be a file for reading or writing. The file473+ is automatically closed once the context tears down (after the command474+ finished working).475+476+ Files can be opened for reading or writing. The special value ``-``477+ indicates stdin or stdout depending on the mode.478+479+ By default, the file is opened for reading text data, but it can also be480+ opened in binary mode or for writing. The encoding parameter can be used481+ to force a specific encoding.482+483+ The `lazy` flag controls if the file should be opened immediately or upon484+ first IO. The default is to be non-lazy for standard input and output485+ streams as well as files opened for reading, `lazy` otherwise. When opening a486+ file lazily for reading, it is still opened temporarily for validation, but487+ will not be held open until first IO. lazy is mainly useful when opening488+ for writing to avoid creating the file until it is needed.489+490+ Files can also be opened atomically in which case all writes go into a491+ separate file in the same folder and upon completion the file will492+ be moved over to the original location. This is useful if a file493+ regularly read by other users is modified.494+ """495+496+ name = "filename"497+ envvar_list_splitter: ClassVar[str] = os.path.pathsep498+499+ def __init__(500+ self,501+ mode: str = "r",502+ encoding: str | None = None,503+ errors: str | None = "strict",504+ lazy: bool | None = None,505+ atomic: bool = False,506+ ) -> None:507+ self.mode = mode508+ self.encoding = encoding509+ self.errors = errors510+ self.lazy = lazy511+ self.atomic = atomic512+513+ def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:514+ if self.lazy is not None:515+ return self.lazy516+ if os.fspath(value) == "-":517+ return False518+ elif "w" in self.mode:519+ return True520+ return False521+522+ def convert(523+ self,524+ value: str | os.PathLike[str] | IO[Any],525+ param: Union["Parameter", None],526+ ctx: Union["Context", None],527+ ) -> IO[Any]:528+ if _is_file_like(value):529+ return value530+531+ value = cast("str | os.PathLike[str]", value)532+533+ try:534+ lazy = self.resolve_lazy_flag(value)535+536+ if lazy:537+ lf = LazyFile(538+ value, self.mode, self.encoding, self.errors, atomic=self.atomic539+ )540+541+ if ctx is not None:542+ ctx.call_on_close(lf.close_intelligently)543+544+ return cast("IO[Any]", lf)545+546+ f, should_close = open_stream(547+ value, self.mode, self.encoding, self.errors, atomic=self.atomic548+ )549+550+ # If a context is provided, we automatically close the file551+ # at the end of the context execution (or flush out). If a552+ # context does not exist, it's the caller's responsibility to553+ # properly close the file. This for instance happens when the554+ # type is used with prompts.555+ if ctx is not None:556+ if should_close:557+ ctx.call_on_close(safecall(f.close))558+ else:559+ ctx.call_on_close(safecall(f.flush))560+561+ return f562+ except OSError as e: # pragma: no cover563+ self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)564+565+ def shell_complete(566+ self, ctx: "Context", param: "Parameter", incomplete: str567+ ) -> list["CompletionItem"]:568+ """Return a special completion marker that tells the completion569+ system to use the shell to provide file path completions.570+ """571+ from .shell_completion import CompletionItem572+573+ return [CompletionItem(incomplete, type="file")]574+575+576+def _is_file_like(value: Any) -> TypeGuard[IO[Any]]:577+ return hasattr(value, "read") or hasattr(value, "write")578+579+580+class Tuple(CompositeParamType):581+ """The default behavior of Click is to apply a type on a value directly.582+ This works well in most cases, except for when `nargs` is set to a fixed583+ count and different types should be used for different items. In this584+ case the `Tuple` type can be used. This type can only be used585+ if `nargs` is set to a fixed number.586+587+ For more information see `tuple-type`.588+589+ This can be selected by using a Python tuple literal as a type.590+ """591+592+ def __init__(self, types: Sequence[type[Any] | ParamType]) -> None:593+ self.types: Sequence[ParamType] = [convert_type(ty) for ty in types]594+595+ @property596+ def name(self) -> str: # type: ignore[override]597+ return f"<{' '.join(ty.name for ty in self.types)}>"598+599+ @property600+ def arity(self) -> int: # type: ignore601+ return len(self.types)602+603+ def convert(604+ self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]605+ ) -> Any:606+ len_type = len(self.types)607+ len_value = len(value)608+609+ if len_value != len_type:610+ self.fail(611+ f"{len_type} values are required, but {len_value} given.",612+ param=param,613+ ctx=ctx,614+ )615+616+ return tuple(617+ ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)618+ )619+620+621+def convert_type(ty: Any | None, default: Any | None = None) -> ParamType:622+ """Find the most appropriate `ParamType` for the given Python623+ type. If the type isn't provided, it can be inferred from a default624+ value.625+ """626+ guessed_type = False627+628+ if ty is None and default is not None:629+ if isinstance(default, (tuple, list)):630+ # If the default is empty, ty will remain None and will631+ # return STRING.632+ if default:633+ item = default[0]634+635+ # A tuple of tuples needs to detect the inner types.636+ # Can't call convert recursively because that would637+ # incorrectly unwind the tuple to a single type.638+ if isinstance(item, (tuple, list)):639+ ty = tuple(map(type, item))640+ else:641+ ty = type(item)642+ else:643+ ty = type(default)644+645+ guessed_type = True646+647+ if isinstance(ty, tuple):648+ return Tuple(ty)649+650+ if isinstance(ty, ParamType):651+ return ty652+653+ if ty is str or ty is None:654+ return STRING655+656+ if ty is int:657+ return INT658+659+ if ty is float:660+ return FLOAT661+662+ if ty is bool:663+ return BOOL664+665+ if guessed_type:666+ return STRING667+668+ return FuncParamType(ty)669+670+671+# A unicode string parameter type which is the implicit default. This672+# can also be selected by using ``str`` as type.673+STRING = StringParamType()674+675+# An integer parameter. This can also be selected by using ``int`` as676+# type.677+INT = IntParamType()678+679+# A floating point value parameter. This can also be selected by using680+# ``float`` as type.681+FLOAT = FloatParamType()682+683+# A boolean parameter. This is the default for boolean flags. This can684+# also be selected by using ``bool`` as a type.685+BOOL = BoolParamType()686+687+# A UUID parameter.688+UUID = UUIDParameterType()689+690+691+class OptionHelpExtra(TypedDict, total=False):692+ envvars: tuple[str, ...]693+ default: str694+ range: str695+ required: stradded:typer/_click/utils.py+470 added
1+import os2+import re3+import sys4+from collections.abc import Callable, Iterable, Iterator5+from functools import update_wrapper6+from types import ModuleType, TracebackType7+from typing import (8+ IO,9+ Any,10+ AnyStr,11+ BinaryIO,12+ Literal,13+ ParamSpec,14+ TextIO,15+ TypeVar,16+ cast,17+)18+19+from ._compat import (20+ WIN,21+ _default_text_stderr,22+ _default_text_stdout,23+ _find_binary_writer,24+ auto_wrap_for_ansi,25+ binary_streams,26+ open_stream,27+ should_strip_ansi,28+ strip_ansi,29+ text_streams,30+)31+from .globals import resolve_color_default32+33+P = ParamSpec("P")34+R = TypeVar("R")35+36+37+def _posixify(name: str) -> str:38+ return "-".join(name.split()).lower()39+40+41+def safecall(func: Callable[P, R]) -> Callable[P, R | None]:42+ """Wraps a function so that it swallows exceptions."""43+44+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:45+ try:46+ return func(*args, **kwargs)47+ except Exception: # pragma: no cover48+ pass49+ return None # pragma: no cover50+51+ return update_wrapper(wrapper, func)52+53+54+def make_default_short_help(help: str, max_length: int = 45) -> str:55+ """Returns a condensed version of help string."""56+ # Consider only the first paragraph.57+ paragraph_end = help.find("\n\n")58+59+ if paragraph_end != -1:60+ help = help[:paragraph_end]61+62+ # Collapse newlines, tabs, and spaces.63+ words = help.split()64+65+ if not words:66+ return ""67+68+ # The first paragraph started with a "no rewrap" marker, ignore it.69+ if words[0] == "\b":70+ words = words[1:]71+72+ total_length = 073+ last_index = len(words) - 174+75+ for i, word in enumerate(words):76+ total_length += len(word) + (i > 0)77+78+ if total_length > max_length: # too long, truncate79+ break80+81+ if word[-1] == ".": # sentence end, truncate without "..."82+ return " ".join(words[: i + 1])83+84+ if total_length == max_length and i != last_index:85+ break # not at sentence end, truncate with "..."86+ else:87+ return " ".join(words) # no truncation needed88+89+ # Account for the length of the suffix.90+ total_length += len("...")91+92+ # remove words until the length is short enough93+ while i > 0:94+ total_length -= len(words[i]) + (i > 0)95+96+ if total_length <= max_length:97+ break98+99+ i -= 1100+101+ return " ".join(words[:i]) + "..."102+103+104+class LazyFile:105+ """A lazy file works like a regular file but it does not fully open106+ the file but it does perform some basic checks early to see if the107+ filename parameter does make sense. This is useful for safely opening108+ files for writing.109+ """110+111+ def __init__(112+ self,113+ filename: str | os.PathLike[str],114+ mode: str = "r",115+ encoding: str | None = None,116+ errors: str | None = "strict",117+ atomic: bool = False,118+ ):119+ self.name: str = os.fspath(filename)120+ self.mode = mode121+ self.encoding = encoding122+ self.errors = errors123+ self.atomic = atomic124+ self._f: IO[Any] | None125+ self.should_close: bool126+127+ if self.name == "-":128+ self._f, self.should_close = open_stream(filename, mode, encoding, errors)129+ else:130+ if "r" in mode:131+ # Open and close the file in case we're opening it for132+ # reading so that we can catch at least some errors in133+ # some cases early.134+ open(filename, mode).close()135+ self._f = None136+ self.should_close = True137+138+ def __getattr__(self, name: str) -> Any:139+ return getattr(self.open(), name)140+141+ def __repr__(self) -> str:142+ if self._f is not None:143+ return repr(self._f)144+ return f"<unopened file '{format_filename(self.name)}' {self.mode}>"145+146+ def open(self) -> IO[Any]:147+ """Opens the file if it's not yet open. This call might fail with148+ a `FileError`. Not handling this error will produce an error149+ that Click shows.150+ """151+ if self._f is not None:152+ return self._f153+ try:154+ rv, self.should_close = open_stream(155+ self.name, self.mode, self.encoding, self.errors, atomic=self.atomic156+ )157+ except OSError as e:158+ from .exceptions import FileError159+160+ raise FileError(self.name, hint=e.strerror) from e161+ self._f = rv162+ return rv163+164+ def close(self) -> None:165+ """Closes the underlying file, no matter what."""166+ if self._f is not None:167+ self._f.close()168+169+ def close_intelligently(self) -> None:170+ """This function only closes the file if it was opened by the lazy171+ file wrapper. For instance this will never close stdin.172+ """173+ if self.should_close:174+ self.close()175+176+ def __enter__(self) -> "LazyFile":177+ return self178+179+ def __exit__(180+ self,181+ exc_type: type[BaseException] | None,182+ exc_value: BaseException | None,183+ tb: TracebackType | None,184+ ) -> None:185+ self.close_intelligently()186+187+ def __iter__(self) -> Iterator[AnyStr]:188+ self.open()189+ return iter(self._f) # type: ignore190+191+192+def echo(193+ message: Any | None = None,194+ file: IO[Any] | None = None,195+ nl: bool = True,196+ err: bool = False,197+ color: bool | None = None,198+) -> None:199+ """Print a message and newline to stdout or a file. This should be200+ used instead of `print` because it provides better support201+ for different data, files, and environments.202+203+ Compared to `print`, this does the following:204+205+ - Ensures that the output encoding is not misconfigured on Linux.206+ - Supports Unicode in the Windows console.207+ - Supports writing to binary outputs, and supports writing bytes208+ to text outputs.209+ - Supports colors and styles on Windows.210+ - Removes ANSI color and style codes if the output does not look211+ like an interactive terminal.212+ - Always flushes the output.213+ """214+ if file is None:215+ if err:216+ file = _default_text_stderr()217+ else:218+ file = _default_text_stdout()219+220+ # There are no standard streams attached to write to. For example,221+ # pythonw on Windows.222+ if file is None:223+ return224+225+ # Convert non bytes/text into the native string type.226+ if message is not None and not isinstance(message, (str, bytes, bytearray)):227+ out: str | bytes | bytearray | None = str(message)228+ else:229+ out = message230+231+ if nl:232+ out = out or ""233+ if isinstance(out, str):234+ out += "\n"235+ else:236+ out += b"\n"237+238+ if not out:239+ file.flush()240+ return241+242+ # If there is a message and the value looks like bytes, we manually243+ # need to find the binary stream and write the message in there.244+ # This is done separately so that most stream types will work as you245+ # would expect. Eg: you can write to StringIO for other cases.246+ if isinstance(out, (bytes, bytearray)):247+ binary_file = _find_binary_writer(file)248+249+ if binary_file is not None:250+ file.flush()251+ binary_file.write(out)252+ binary_file.flush()253+ return254+255+ # ANSI style code support. For no message or bytes, nothing happens.256+ # When outputting to a file instead of a terminal, strip codes.257+ else:258+ color = resolve_color_default(color)259+260+ if should_strip_ansi(file, color):261+ out = strip_ansi(out)262+ elif WIN:263+ if auto_wrap_for_ansi is not None:264+ file = auto_wrap_for_ansi(file, color) # type: ignore[arg-type,call-arg]265+ elif not color:266+ out = strip_ansi(out)267+268+ file.write(out) # type: ignore[arg-type]269+ file.flush()270+271+272+def get_binary_stream(name: Literal["stdin", "stdout", "stderr"]) -> BinaryIO:273+ """Returns a system stream for byte processing."""274+ opener = binary_streams.get(name)275+ if opener is None:276+ raise TypeError(f"Unknown standard stream '{name}'")277+ return opener()278+279+280+def get_text_stream(281+ name: Literal["stdin", "stdout", "stderr"],282+ encoding: str | None = None,283+ errors: str | None = "strict",284+) -> TextIO:285+ """Returns a system stream for text processing. This usually returns286+ a wrapped stream around a binary stream returned from287+ `get_binary_stream` but it also can take shortcuts for already288+ correctly configured streams.289+ """290+ opener = text_streams.get(name)291+ if opener is None:292+ raise TypeError(f"Unknown standard stream '{name}'")293+ return opener(encoding, errors)294+295+296+def format_filename(297+ filename: str | bytes | os.PathLike[str] | os.PathLike[bytes],298+ shorten: bool = False,299+) -> str:300+ """Format a filename as a string for display. Ensures the filename can be301+ displayed by replacing any invalid bytes or surrogate escapes in the name302+ with the replacement character ``�``.303+304+ Invalid bytes or surrogate escapes will raise an error when written to a305+ stream with ``errors="strict"``. This will typically happen with ``stdout``306+ when the locale is something like ``en_GB.UTF-8``.307+308+ Many scenarios *are* safe to write surrogates though, due to PEP 538 and309+ PEP 540, including:310+311+ - Writing to ``stderr``, which uses ``errors="backslashreplace"``.312+ - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens313+ stdout and stderr with ``errors="surrogateescape"``.314+ - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.315+ - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.316+ Python opens stdout and stderr with ``errors="surrogateescape"``.317+ """318+ if shorten:319+ filename = os.path.basename(filename)320+ else:321+ filename = os.fspath(filename)322+323+ if isinstance(filename, bytes):324+ filename = filename.decode(sys.getfilesystemencoding(), "replace")325+ else:326+ filename = filename.encode("utf-8", "surrogateescape").decode(327+ "utf-8", "replace"328+ )329+330+ return filename331+332+333+def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:334+ r"""Returns the config folder for the application. The default behavior335+ is to return whatever is most appropriate for the operating system.336+337+ To give you an idea, for an app called ``"Foo Bar"``, something like338+ the following folders could be returned:339+340+ Mac OS X:341+ ``~/Library/Application Support/Foo Bar``342+ Mac OS X (POSIX):343+ ``~/.foo-bar``344+ Unix:345+ ``~/.config/foo-bar``346+ Unix (POSIX):347+ ``~/.foo-bar``348+ Windows (roaming):349+ ``C:\Users\<user>\AppData\Roaming\Foo Bar``350+ Windows (not roaming):351+ ``C:\Users\<user>\AppData\Local\Foo Bar``352+ """353+ if WIN:354+ key = "APPDATA" if roaming else "LOCALAPPDATA"355+ folder = os.environ.get(key)356+ if folder is None:357+ folder = os.path.expanduser("~")358+ return os.path.join(folder, app_name)359+ if force_posix:360+ return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))361+ if sys.platform == "darwin":362+ return os.path.join(363+ os.path.expanduser("~/Library/Application Support"), app_name364+ )365+ return os.path.join(366+ os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),367+ _posixify(app_name),368+ )369+370+371+class PacifyFlushWrapper:372+ """This wrapper is used to catch and suppress BrokenPipeErrors resulting373+ from ``.flush()`` being called on broken pipe during the shutdown/final-GC374+ of the Python interpreter. Notably ``.flush()`` is always called on375+ ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any376+ other cleanup code, and the case where the underlying file is not a broken377+ pipe, all calls and attributes are proxied.378+ """379+380+ def __init__(self, wrapped: IO[Any]) -> None:381+ self.wrapped = wrapped382+383+ def flush(self) -> None:384+ try:385+ self.wrapped.flush()386+ except OSError as e: # pragma: no cover387+ import errno388+389+ if e.errno != errno.EPIPE:390+ raise391+392+ def __getattr__(self, attr: str) -> Any:393+ return getattr(self.wrapped, attr)394+395+396+def _detect_program_name(397+ path: str | None = None, _main: ModuleType | None = None398+) -> str:399+ """Determine the command used to run the program, for use in help400+ text. If a file or entry point was executed, the file name is401+ returned. If ``python -m`` was used to execute a module or package,402+ ``python -m name`` is returned.403+404+ This doesn't try to be too precise, the goal is to give a concise405+ name for help text. Files are only shown as their name without the406+ path. ``python`` is only shown for modules, and the full path to407+ ``sys.executable`` is not shown.408+ """409+ if _main is None:410+ _main = sys.modules["__main__"]411+412+ if not path:413+ path = sys.argv[0]414+415+ # The value of __package__ indicates how Python was called. It may416+ # not exist if a setuptools script is installed as an egg. It may be417+ # set incorrectly for entry points created with pip on Windows.418+ # It is set to "" inside a Shiv or PEX zipapp.419+ if getattr(_main, "__package__", None) in {None, ""} or (420+ os.name == "nt"421+ and _main.__package__ == ""422+ and not os.path.exists(path)423+ and os.path.exists(f"{path}.exe")424+ ):425+ # Executed a file, like "python app.py".426+ return os.path.basename(path)427+428+ # Executed a module, like "python -m example".429+ # Rewritten by Python from "-m script" to "/path/to/script.py".430+ # Need to look at main module to determine how it was executed.431+ py_module = cast(str, _main.__package__)432+ name = os.path.splitext(os.path.basename(path))[0]433+434+ # A submodule like "example.cli".435+ if name != "__main__":436+ py_module = f"{py_module}.{name}"437+438+ return f"python -m {py_module.lstrip('.')}"439+440+441+def _expand_args(442+ args: Iterable[str],443+ *,444+ user: bool = True,445+ env: bool = True,446+ glob_recursive: bool = True,447+) -> list[str]:448+ """Simulate Unix shell expansion with Python functions."""449+ from glob import glob450+451+ out = []452+453+ for arg in args:454+ if user:455+ arg = os.path.expanduser(arg)456+457+ if env:458+ arg = os.path.expandvars(arg)459+460+ try:461+ matches = glob(arg, recursive=glob_recursive)462+ except re.error: # pragma: no cover463+ matches = []464+465+ if not matches:466+ out.append(arg)467+ else:468+ out.extend(matches)469+470+ return outmodified:typer/.agents/skills/typer/SKILL.md+1 added-1 removed
257 unmodified lines258 ```259 260 ## Click261 262-Originally, Typer was built on Click. However, going forward Typer will vendor Click. As such, Click extensions should not be used anymore.262+Originally, Typer was built on Click. However, since version 0.26.0, Typer has vendored Click. As such, Click extensions should not be used anymore.263 264 Other settings of `Option` and `Argument` that came from Click but shouldn't be used in Typer anymore, include: `expose_value`, `shell_complete`, `show_choices`, `errors`, `prompt_required`, `is_flag`, `flag_value` and `allow_from_autoenv`.265 266 Code bases using these should be refactored to use pure Typer functionality.modified:typer/__init__.py+14 added-21 removed
2 unmodified lines3 __version__ = "0.25.1"4 5 from shutil import get_terminal_size as get_terminal_size6 7-from click.exceptions import Abort as Abort8-from click.exceptions import BadParameter as BadParameter9-from click.exceptions import Exit as Exit10-from click.termui import clear as clear11-from click.termui import confirm as confirm12-from click.termui import echo_via_pager as echo_via_pager13-from click.termui import edit as edit14-from click.termui import getchar as getchar15-from click.termui import pause as pause16-from click.termui import progressbar as progressbar17-from click.termui import prompt as prompt18-from click.termui import secho as secho19-from click.termui import style as style20-from click.termui import unstyle as unstyle21-from click.utils import echo as echo22-from click.utils import format_filename as format_filename23-from click.utils import get_app_dir as get_app_dir24-from click.utils import get_binary_stream as get_binary_stream25-from click.utils import get_text_stream as get_text_stream26-from click.utils import open_file as open_file27-7 from . import colors as colors8+from ._click.exceptions import Abort as Abort9+from ._click.exceptions import BadParameter as BadParameter10+from ._click.exceptions import Exit as Exit11+from ._click.termui import confirm as confirm12+from ._click.termui import getchar as getchar13+from ._click.termui import progressbar as progressbar14+from ._click.termui import prompt as prompt15+from ._click.termui import secho as secho16+from ._click.termui import style as style17+from ._click.utils import echo as echo18+from ._click.utils import format_filename as format_filename19+from ._click.utils import get_app_dir as get_app_dir20+from ._click.utils import get_binary_stream as get_binary_stream21+from ._click.utils import get_text_stream as get_text_stream22 from .main import Typer as Typer23 from .main import launch as launch24 from .main import run as run25 from .models import CallbackParam as CallbackParam7 unmodified linesmodified:typer/_completion_classes.py+50 added-20 removed
2 unmodified lines3 import re4 import sys5 from typing import Any6 7-import click8-import click.parser9-import click.shell_completion10-from click.shell_completion import split_arg_string as click_split_arg_string11-7+from . import _click8+from ._click.shell_completion import CompletionItem, ShellComplete, add_completion_class9+from ._click.shell_completion import split_arg_string as click_split_arg_string10 from ._completion_shared import (11 COMPLETION_SCRIPT_BASH,12 COMPLETION_SCRIPT_FISH,13 COMPLETION_SCRIPT_POWER_SHELL,10 unmodified lines24 25 return rich_utils.rich_render_text(text)26 27 30-class BashComplete(click.shell_completion.BashComplete):28+class BashComplete(ShellComplete):29 name = Shells.bash.value30 source_template = COMPLETION_SCRIPT_BASH31 32 def source_vars(self) -> dict[str, Any]:14 unmodified lines47 incomplete = ""48 49 return args, incomplete50 53- def format_completion(self, item: click.shell_completion.CompletionItem) -> str:51+ def format_completion(self, item: CompletionItem) -> str:52 # TODO: Explore replicating the new behavior from Click, with item types and53 # triggering completion for files and directories54 # return f"{item.type},{item.value}"55 return f"{item.value}"3 unmodified lines59 completions = self.get_completions(args, incomplete)60 out = [self.format_completion(item) for item in completions]61 return "\n".join(out)62 63+ @staticmethod64+ def _check_version() -> None:65+ import shutil66+ import subprocess67 68+ bash_exe = shutil.which("bash")69+70+ if bash_exe is None:71+ match = None # pragma: no cover72+ else:73+ output = subprocess.run(74+ [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],75+ stdout=subprocess.PIPE,76+ )77+ match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())78+79+ if match is not None:80+ major, minor = match.groups()81+82+ if major < "4" or major == "4" and minor < "4":83+ _click.utils.echo(84+ "Shell completion is not supported for Bash versions older than 4.4.",85+ err=True,86+ )87+ else:88+ _click.utils.echo(89+ "Couldn't detect Bash version, shell completion is not supported.",90+ err=True,91+ ) # pragma: no cover92+93+ def source(self) -> str:94+ self._check_version()95+ return super().source()96+97+66-class ZshComplete(click.shell_completion.ZshComplete):98+class ZshComplete(ShellComplete):99 name = Shells.zsh.value100 source_template = COMPLETION_SCRIPT_ZSH101 102 def source_vars(self) -> dict[str, Any]:13 unmodified lines116 else:117 incomplete = ""118 return args, incomplete119 88- def format_completion(self, item: click.shell_completion.CompletionItem) -> str:120+ def format_completion(self, item: CompletionItem) -> str:121 def escape(s: str) -> str:122 return (123 s.replace('"', '""')124 .replace("'", "''")20 unmodified lines145 else:146 return "_files"147 148 117-class FishComplete(click.shell_completion.FishComplete):149+class FishComplete(ShellComplete):150 name = Shells.fish.value151 source_template = COMPLETION_SCRIPT_FISH152 153 def source_vars(self) -> dict[str, Any]:13 unmodified lines167 else:168 incomplete = ""169 return args, incomplete170 139- def format_completion(self, item: click.shell_completion.CompletionItem) -> str:171+ def format_completion(self, item: CompletionItem) -> str:172 # TODO: Explore replicating the new behavior from Click, pay attention to173 # the difference with and without formatted help174 # if item.help:175 # return f"{item.type},{item.value}\t{item.help}"22 unmodified lines198 sys.exit(1)199 return "" # pragma: no cover200 201 170-class PowerShellComplete(click.shell_completion.ShellComplete):202+class PowerShellComplete(ShellComplete):203 name = Shells.powershell.value204 source_template = COMPLETION_SCRIPT_POWER_SHELL205 206 def source_vars(self) -> dict[str, Any]:9 unmodified lines216 cwords = click_split_arg_string(completion_args)217 args = cwords[1:-1] if incomplete else cwords[1:]218 return args, incomplete219 188- def format_completion(self, item: click.shell_completion.CompletionItem) -> str:220+ def format_completion(self, item: CompletionItem) -> str:221 return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}"222 223 224 def completion_init() -> None:193- click.shell_completion.add_completion_class(BashComplete, Shells.bash.value)194- click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value)195- click.shell_completion.add_completion_class(FishComplete, Shells.fish.value)196- click.shell_completion.add_completion_class(197- PowerShellComplete, Shells.powershell.value198- )199- click.shell_completion.add_completion_class(PowerShellComplete, Shells.pwsh.value)225+ add_completion_class(BashComplete, Shells.bash.value)226+ add_completion_class(ZshComplete, Shells.zsh.value)227+ add_completion_class(FishComplete, Shells.fish.value)228+ add_completion_class(PowerShellComplete, Shells.powershell.value)229+ add_completion_class(PowerShellComplete, Shells.pwsh.value)modified:typer/_completion_shared.py+12 added-10 removed
2 unmodified lines3 import subprocess4 from enum import Enum5 from pathlib import Path6 7-import click7 import shellingham8 9+from . import _click10+from ._click.globals import get_current_context11 12+13 class Shells(str, Enum):14 bash = "bash"15 zsh = "zsh"16 fish = "fish"62 unmodified lines79 def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str:80 cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))81 script = _completion_scripts.get(shell)82 if script is None:81- click.echo(f"Shell {shell} not supported.", err=True)82- raise click.exceptions.Exit(1)83+ _click.echo(f"Shell {shell} not supported.", err=True)84+ raise _click.exceptions.Exit(1)85 return (86 script87 % {88 "complete_func": f"_{cf_name}_completion",84 unmodified lines173 check=True,174 stdout=subprocess.PIPE,175 )176 if result.returncode != 0: # pragma: no cover175- click.echo("Couldn't get PowerShell user profile", err=True)176- raise click.exceptions.Exit(result.returncode)177+ _click.echo("Couldn't get PowerShell user profile", err=True)178+ raise _click.exceptions.Exit(result.returncode)179 path_str = ""180 if isinstance(result.stdout, str): # pragma: no cover181 path_str = result.stdout182 if isinstance(result.stdout, bytes):3 unmodified lines186 break187 except UnicodeDecodeError: # pragma: no cover188 pass189 if not path_str: # pragma: no cover188- click.echo("Couldn't decode the path automatically", err=True)189- raise click.exceptions.Exit(1)190+ _click.echo("Couldn't decode the path automatically", err=True)191+ raise _click.exceptions.Exit(1)192 path_obj = Path(path_str.strip())193 parent_dir: Path = path_obj.parent194 parent_dir.mkdir(parents=True, exist_ok=True)195 script_content = get_completion_script(8 unmodified lines204 shell: str | None = None,205 prog_name: str | None = None,206 complete_var: str | None = None,207 ) -> tuple[str, Path]:206- prog_name = prog_name or click.get_current_context().find_root().info_name208+ prog_name = prog_name or get_current_context().find_root().info_name209 assert prog_name210 if complete_var is None:211 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())212 test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")19 unmodified lines232 prog_name=prog_name, complete_var=complete_var, shell=shell233 )234 return shell, installed_path235 else:234- click.echo(f"Shell {shell} is not supported.")235- raise click.exceptions.Exit(1)236+ _click.echo(f"Shell {shell} is not supported.")237+ raise _click.exceptions.Exit(1)238 239 240 def _get_shell_name() -> str | None:241 """Get the current shell name, if available.13 unmodified linesmodified:typer/_types.py+103 added-10 removed
1+from collections.abc import Iterable, Mapping, Sequence2 from enum import Enum2-from typing import TypeVar3+from typing import Any, Generic, TypeVar4 4-import click5+from . import _click6+from ._click import types7+from ._click.shell_completion import CompletionItem8 9 ParamTypeValue = TypeVar("ParamTypeValue")10 11 9-class TyperChoice(click.Choice[ParamTypeValue]):12+class TyperChoice(types.ParamType, Generic[ParamTypeValue]):13+ # Code adapted from Click 8.3.1, with Typer using enum values in normalize_choice14+ name = "choice"15+16+ def __init__(17+ self, choices: Iterable[ParamTypeValue], case_sensitive: bool = True18+ ) -> None:19+ self.choices: Sequence[ParamTypeValue] = tuple(choices)20+ self.case_sensitive = case_sensitive21+22+ def _normalized_mapping(23+ self, ctx: _click.Context | None = None24+ ) -> Mapping[ParamTypeValue, str]:25+ """26+ Returns mapping where keys are the original choices and the values are27+ the normalized values that are accepted via the command line.28+ """29+ return {30+ choice: self.normalize_choice(31+ choice=choice,32+ ctx=ctx,33+ )34+ for choice in self.choices35+ }36+37 def normalize_choice(11- self, choice: ParamTypeValue, ctx: click.Context | None38+ self, choice: ParamTypeValue, ctx: _click.Context | None39 ) -> str:13- # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class14- # to support enums, but it uses the enum names, while Typer has always used the15- # enum values.16- # This class overrides that method to maintain the previous behavior.17- # In Click:18- # normed_value = choice.name if isinstance(choice, Enum) else str(choice)40 normed_value = str(choice.value) if isinstance(choice, Enum) else str(choice)41 42 if ctx is not None and ctx.token_normalize_func is not None:43 normed_value = ctx.token_normalize_func(normed_value)1 unmodified line45 if not self.case_sensitive:46 normed_value = normed_value.casefold()47 48 return normed_value49+50+ def get_metavar(self, param: _click.Parameter, ctx: _click.Context) -> str | None:51+ if param.param_type_name == "option" and not param.show_choices: # type: ignore52+ choice_metavars = [53+ types.convert_type(type(choice)).name.upper() for choice in self.choices54+ ]55+ choices_str = "|".join([*dict.fromkeys(choice_metavars)])56+ else:57+ choices_str = "|".join(58+ [str(i) for i in self._normalized_mapping(ctx=ctx).values()]59+ )60+61+ # Use curly braces to indicate a required argument.62+ if param.required and param.param_type_name == "argument":63+ return f"{{{choices_str}}}"64+65+ # Use square braces to indicate an option or optional argument.66+ return f"[{choices_str}]"67+68+ def get_missing_message(69+ self, param: _click.Parameter, ctx: _click.Context | None70+ ) -> str:71+ """Message shown when no choice is passed."""72+ choices = ",\n\t".join(self._normalized_mapping(ctx=ctx).values())73+ return f"Choose from:\n\t{choices}"74+75+ def convert(76+ self, value: Any, param: _click.Parameter | None, ctx: _click.Context | None77+ ) -> ParamTypeValue:78+ """79+ For a given value from the parser, normalize it and find its80+ matching normalized value in the list of choices. Then return the81+ matched "original" choice.82+ """83+ normed_value = self.normalize_choice(choice=value, ctx=ctx)84+ normalized_mapping = self._normalized_mapping(ctx=ctx)85+86+ try:87+ return next(88+ original89+ for original, normalized in normalized_mapping.items()90+ if normalized == normed_value91+ )92+ except StopIteration:93+ self.fail(94+ self.get_invalid_choice_message(value=value, ctx=ctx),95+ param=param,96+ ctx=ctx,97+ )98+99+ def get_invalid_choice_message(self, value: Any, ctx: _click.Context | None) -> str:100+ """Get the error message when the given choice is invalid."""101+ choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values()))102+ return f"{value!r} is not one of {choices_str}."103+104+ def __repr__(self) -> str:105+ return f"Choice({list(self.choices)})"106+107+ def shell_complete(108+ self, ctx: _click.Context, param: _click.Parameter, incomplete: str109+ ) -> list[CompletionItem]:110+ """Complete choices that start with the incomplete value."""111+112+ str_choices = map(str, self.choices)113+114+ if self.case_sensitive:115+ matched = (c for c in str_choices if c.startswith(incomplete))116+ else:117+ incomplete = incomplete.lower()118+ matched = (c for c in str_choices if c.lower().startswith(incomplete))119+120+ return [CompletionItem(c) for c in matched]modified:typer/cli.py+11 added-12 removed
2 unmodified lines3 import sys4 from pathlib import Path5 from typing import Any6 7-import click7 import typer8 import typer.core10-from click import Command, Group, Option9 12-from . import __version__13-from .core import HAS_RICH, MARKUP_MODE_KEY10+from . import __version__, _click11+from ._click import Command12+from .core import HAS_RICH, MARKUP_MODE_KEY, TyperGroup, TyperOption13 14 default_app_names = ("app", "cli", "main")15 default_func_names = ("main", "cli", "app")16 12 unmodified lines29 30 state = State()31 32 34-def maybe_update_state(ctx: click.Context) -> None:33+def maybe_update_state(ctx: _click.Context) -> None:34 path_or_module = ctx.params.get("path_or_module")35 if path_or_module:36 file_path = Path(path_or_module)37 if file_path.exists() and file_path.is_file():13 unmodified lines51 state.func = func_name52 53 54 class TyperCLIGroup(typer.core.TyperGroup):56- def list_commands(self, ctx: click.Context) -> list[str]:55+ def list_commands(self, ctx: _click.Context) -> list[str]:56 self.maybe_add_run(ctx)57 return super().list_commands(ctx)58 60- def get_command(self, ctx: click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override]59+ def get_command(self, ctx: _click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override]60 self.maybe_add_run(ctx)61 return super().get_command(ctx, name)62 64- def invoke(self, ctx: click.Context) -> Any:63+ def invoke(self, ctx: _click.Context) -> Any:64 self.maybe_add_run(ctx)65 return super().invoke(ctx)66 68- def maybe_add_run(self, ctx: click.Context) -> None:67+ def maybe_add_run(self, ctx: _click.Context) -> None:68 maybe_update_state(ctx)69 maybe_add_run_to_cli(self)70 71 64 unmodified lines136 obj = get_typer_from_module(module)137 return obj138 139 141-def maybe_add_run_to_cli(cli: click.Group) -> None:140+def maybe_add_run_to_cli(cli: TyperGroup) -> None:141 if "run" not in cli.commands:142 if state.file or state.module:143 obj = get_typer_from_state()144 if obj:4 unmodified lines149 click_obj.help = "Run the provided Typer app."150 cli.add_command(click_obj)151 152 154-def print_version(ctx: click.Context, param: Option, value: bool) -> None:153+def print_version(ctx: _click.Context, param: TyperOption, value: bool) -> None:154 if not value or ctx.resilient_parsing:155 return156 typer.echo(f"Typer version: {__version__}")157 raise typer.Exit()82 unmodified lines240 docs += "\n"241 docs += "\n"242 if obj.epilog:243 docs += f"{obj.epilog}\n\n"245- if isinstance(obj, Group):244+ if isinstance(obj, TyperGroup):245 group = obj246 commands = group.list_commands(ctx)247 if commands:248 docs += "**Commands**:\n\n"69 unmodified linesmodified:typer/completion.py+15 added-16 removed
1 unmodified line2 import sys3 from collections.abc import MutableMapping4 from typing import Any5 6-import click7-6+from . import _click7+from ._click import shell_completion8 from ._completion_classes import completion_init9 from ._completion_shared import Shells, _get_shell_name, get_completion_script, install10 from .models import ParamMeta11 from .params import Option14 unmodified lines26 install_param, show_param = parameters.values()27 return install_param, show_param28 29 30-def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:30+def install_callback(ctx: _click.Context, param: _click.Parameter, value: Any) -> Any:31 if not value or ctx.resilient_parsing:32 return value # pragma: no cover33 if isinstance(value, str):34 shell, path = install(shell=value)35 else:36 shell, path = install()37- click.secho(f"{shell} completion installed in {path}", fg="green")38- click.echo("Completion will take effect once you restart the terminal")37+ _click.termui.secho(f"{shell} completion installed in {path}", fg="green")38+ _click.echo("Completion will take effect once you restart the terminal")39 sys.exit(0)40 41 42-def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:42+def show_callback(ctx: _click.Context, param: _click.Parameter, value: Any) -> Any:43 if not value or ctx.resilient_parsing:44 return value # pragma: no cover45 prog_name = ctx.find_root().info_name46 assert prog_name8 unmodified lines55 shell = detected_shell56 script_content = get_completion_script(57 prog_name=prog_name, complete_var=complete_var, shell=shell58 )59- click.echo(script_content)59+ _click.echo(script_content)60 sys.exit(0)61 62 63 # Create a fake command function to extract the completion parameters38 unmodified lines102 # To use 7.x instruction style for compatibility103 # And to add extra error messages, for compatibility with Typer in previous versions104 # This is only called in new Command method, only used by Click 8.x+105 def shell_complete(106- cli: click.Command,106+ cli: _click.Command,107 ctx_args: MutableMapping[str, Any],108 prog_name: str,109 complete_var: str,110 instruction: str,111 ) -> int:112- import click113- import click.shell_completion112+ from . import _click113 114 if "_" not in instruction:116- click.echo("Invalid completion instruction.", err=True)115+ _click.echo("Invalid completion instruction.", err=True)116 return 1117 118 # Click 8 changed the order/style of shell instructions from e.g.119 # source_bash to bash_source2 unmodified lines122 # shell, _, instruction = instruction.partition("_")123 instruction, _, shell = instruction.partition("_")124 # Typer override end125 127- comp_cls = click.shell_completion.get_completion_class(shell)126+ comp_cls = shell_completion.get_completion_class(shell)127 128 if comp_cls is None:130- click.echo(f"Shell {shell} not supported.", err=True)129+ _click.echo(f"Shell {shell} not supported.", err=True)130 return 1131 132 comp = comp_cls(cli, ctx_args, prog_name, complete_var)133 134 if instruction == "source":136- click.echo(comp.source())135+ _click.echo(comp.source())136 return 0137 138 # Typer override to print the completion help msg with Rich139 if instruction == "complete":141- click.echo(comp.complete())140+ _click.echo(comp.complete())141 return 0142 # Typer override end143 145- click.echo(f'Completion instruction "{instruction}" not supported.', err=True)144+ _click.echo(f'Completion instruction "{instruction}" not supported.', err=True)145 return 1modified:typer/core.py+481 added-92 removed
1 import errno2 import inspect3 import os4 import sys5-from collections.abc import Callable, MutableMapping, Sequence5+from collections.abc import Callable, Mapping, MutableMapping, Sequence6 from difflib import get_close_matches7 from enum import Enum8 from gettext import gettext as _9 from typing import (2 unmodified lines12 Union,13 cast,14 )15 16-import click17-import click.core18-import click.formatting19-import click.shell_completion20-import click.types21-import click.utils22-16+from . import _click17+from ._click import types18+from ._click.parser import _OptionParser19+from ._click.shell_completion import CompletionItem20 from ._typing import Literal21 from .utils import parse_boolean_env_var22 23 MarkupMode = Literal["markdown", "rich", None]6 unmodified lines30 else:31 DEFAULT_MARKUP_MODE = None32 33 37-# Copy from click.parser._split_opt34+# Copy from _click.parser._split_opt35 def _split_opt(opt: str) -> tuple[str, str]:36 first = opt[:1]37 if first.isalnum():38 return "", opt2 unmodified lines41 return first, opt[1:]42 43 44 def _typer_param_setup_autocompletion_compat(48- self: click.Parameter,45+ self: _click.Parameter,46 *,47 autocompletion: Callable[51- [click.Context, list[str], str], list[tuple[str, str] | str]48+ [_click.Context, list[str], str], list[tuple[str, str] | str]49 ]50 | None = None,51 ) -> None:52 if self._custom_shell_complete is not None:8 unmodified lines61 62 if autocompletion is not None:63 64 def compat_autocompletion(68- ctx: click.Context, param: click.core.Parameter, incomplete: str69- ) -> list["click.shell_completion.CompletionItem"]:70- from click.shell_completion import CompletionItem71-65+ ctx: _click.Context, param: _click.core.Parameter, incomplete: str66+ ) -> list[CompletionItem]:67 out = []68 69 for c in autocompletion(ctx, [], incomplete):70 if isinstance(c, tuple):12 unmodified lines83 84 def _get_default_string(85 obj: Union["TyperArgument", "TyperOption"],86 *,92- ctx: click.Context,87+ ctx: _click.Context,88 show_default_is_str: bool,89 default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,90 ) -> str:96- # Extracted from click.core.Option.get_help_record() to be reused by91+ # Extracted from _click.core.Option.get_help_record() to be reused by92 # rich_utils avoiding RegEx hacks93 if show_default_is_str:94 default_string = f"({obj.show_default})"95 elif isinstance(default_value, (list, tuple)):10 unmodified lines106 elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts:107 # For boolean flags that have distinct True/False opts,108 # use the opt without prefix instead of the value.109 # Typer override, original commented115- # default_string = click.parser.split_opt(110+ # default_string = _click.parser.split_opt(111 # (self.opts if self.default else self.secondary_opts)[0]112 # )[1]113 if obj.default:114 if obj.opts:15 unmodified lines130 return default_string131 132 133 def _extract_default_help_str(139- obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context134+ obj: Union["TyperArgument", "TyperOption"], *, ctx: _click.Context135 ) -> Any | Callable[[], Any] | None:141- # Extracted from click.core.Option.get_help_record() to be reused by136+ # Extracted from _click.core.Option.get_help_record() to be reused by137 # rich_utils avoiding RegEx hacks138 # Temporarily enable resilient parsing to avoid type casting139 # failing for the default. Might be possible to extend this to140 # help formatting in general.7 unmodified lines148 return default_value149 150 151 def _main(157- self: click.Command,152+ self: _click.Command,153 *,154 args: Sequence[str] | None = None,155 prog_name: str | None = None,156 complete_var: str | None = None,1 unmodified line158 windows_expand_args: bool = True,159 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,160 **extra: Any,161 ) -> Any:167- # Typer override, duplicated from click.main() to handle custom rich exceptions162+ # Typer override, duplicated from _click.main() to handle custom rich exceptions163 # Verify that the environment is configured correctly, or reject164 # further execution to avoid a broken script.165 if args is None:166 args = sys.argv[1:]167 168 # Covered in Click tests169 if os.name == "nt" and windows_expand_args: # pragma: no cover175- args = click.utils._expand_args(args)170+ args = _click.utils._expand_args(args)171 else:172 args = list(args)173 174 if prog_name is None:180- prog_name = click.utils._detect_program_name()175+ prog_name = _click.utils._detect_program_name()176 177 # Process shell completion requests and exit early.178 self._main_shell_completion(extra, prog_name, complete_var)179 11 unmodified lines191 # even always obvious that `rv` indicates success/failure192 # by its truthiness/falsiness193 ctx.exit()194 except EOFError as e:200- click.echo(file=sys.stderr)201- raise click.Abort() from e195+ _click.echo(file=sys.stderr)196+ raise _click.exceptions.Abort() from e197 except KeyboardInterrupt as e:203- raise click.exceptions.Exit(130) from e204- except click.ClickException as e:198+ raise _click.exceptions.Exit(130) from e199+ except _click.exceptions.ClickException as e:200 if not standalone_mode:201 raise202 # Typer override203 if HAS_RICH and rich_markup_mode is not None:5 unmodified lines209 # Typer override end210 sys.exit(e.exit_code)211 except OSError as e:212 if e.errno == errno.EPIPE:218- sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout))219- sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr))213+ sys.stdout = cast(TextIO, _click.utils.PacifyFlushWrapper(sys.stdout))214+ sys.stderr = cast(TextIO, _click.utils.PacifyFlushWrapper(sys.stderr))215 sys.exit(1)216 else:217 raise223- except click.exceptions.Exit as e:218+ except _click.exceptions.Exit as e:219 if standalone_mode:220 sys.exit(e.exit_code)221 else:222 # in non-standalone mode, return the exit code4 unmodified lines227 # somewhat ambiguous: if there are codepaths which lead to228 # `ctx.exit(1)` and to `return 1`, the caller won't be able to229 # tell the difference between the two230 return e.exit_code236- except click.Abort:231+ except _click.exceptions.Abort:232 if not standalone_mode:233 raise234 # Typer override235 if HAS_RICH and rich_markup_mode is not None:236 from . import rich_utils237 238 rich_utils.rich_abort_error()239 else:245- click.echo(_("Aborted!"), file=sys.stderr)240+ _click.echo(_("Aborted!"), file=sys.stderr)241 # Typer override end242 sys.exit(1)243 244 250-class TyperArgument(click.core.Argument):245+class TyperArgument(_click.core.Parameter):246+ param_type_name = "argument"247+248 def __init__(249 self,250 *,251 # Parameter252 param_decls: list[str],253 type: Any | None = None,257- required: bool | None = None,254+ required: bool = False,255 default: Any | None = None,256 callback: Callable[..., Any] | None = None,257 nargs: int | None = None,258 metavar: str | None = None,2 unmodified lines261 envvar: str | list[str] | None = None,262 # Note that shell_complete is not fully supported and will be removed in future versions263 # TODO: Remove shell_complete in a future version (after 0.16.0)264 shell_complete: Callable[268- [click.Context, click.Parameter, str],269- list["click.shell_completion.CompletionItem"] | list[str],265+ [_click.Context, _click.Parameter, str],266+ list[CompletionItem] | list[str],267 ]268 | None = None,269 autocompletion: Callable[..., Any] | None = None,270 # TyperArgument26 unmodified lines297 shell_complete=shell_complete,298 )299 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)300 301+ @property302+ def human_readable_name(self) -> str:303+ if self.metavar is not None:304+ return self.metavar305+ assert self.name is not None, "self.name or self.metavar should be set"306+ return self.name.upper()307+308 def _get_default_string(309 self,310 *,307- ctx: click.Context,311+ ctx: _click.Context,312 show_default_is_str: bool,313 default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,314 ) -> str:315 return _get_default_string(3 unmodified lines319 default_value=default_value,320 )321 322 def _extract_default_help_str(319- self, *, ctx: click.Context323+ self, *, ctx: _click.Context324 ) -> Any | Callable[[], Any] | None:325 return _extract_default_help_str(self, ctx=ctx)326 323- def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:324- # Modified version of click.core.Option.get_help_record()327+ def get_help_record(self, ctx: _click.Context) -> tuple[str, str] | None:328+ # Modified version of _click.core.Option.get_help_record()329 # to support Arguments330 if self.hidden:331 return None332 name = self.make_metavar(ctx=ctx)46 unmodified lines379 380 help = f"{help} {extra_str}" if help else f"{extra_str}"381 return name, help382 379- def make_metavar(self, ctx: click.Context) -> str:380- # Modified version of click.core.Argument.make_metavar()383+ def make_metavar(self, ctx: _click.Context) -> str:384+ # Modified version of _click.core.Argument.make_metavar()385 # to include Argument name386 if self.metavar is not None:387 var = self.metavar388 if not self.required and not var.startswith("["):11 unmodified lines400 401 def value_is_missing(self, value: Any) -> bool:402 return _value_is_missing(self, value)403 404+ def _parse_decls(405+ self, decls: Sequence[str], expose_value: bool406+ ) -> tuple[str | None, list[str], list[str]]:407+ if not decls:408+ if not expose_value:409+ return None, [], []410+ raise TypeError("Argument is marked as exposed, but does not have a name.")411+ if len(decls) == 1:412+ name = arg = decls[0]413+ name = name.replace("-", "_").lower()414+ else:415+ raise TypeError(416+ "Arguments take exactly one parameter declaration, got"417+ f" {len(decls)}: {decls}."418+ )419+ return name, [arg], []420 421+ def get_usage_pieces(self, ctx: _click.Context) -> list[str]:422+ return [self.make_metavar(ctx)]423+424+ def get_error_hint(self, ctx: _click.Context) -> str:425+ return f"'{self.make_metavar(ctx)}'"426+427+ def add_to_parser(self, parser: _OptionParser, ctx: _click.Context) -> None:428+ parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)429+430+401-class TyperOption(click.core.Option):431+class TyperOption(_click.Parameter):432+ param_type_name = "option"433+434+ _depr_flag_value: bool | None435+436 def __init__(437 self,438 *,439 # Parameter440 param_decls: list[str],407- type: click.types.ParamType | Any | None = None,408- required: bool | None = None,441+ type: types.ParamType | Any | None = None,442+ required: bool = False,443 default: Any | None = None,444 callback: Callable[..., Any] | None = None,445 nargs: int | None = None,446 metavar: str | None = None,2 unmodified lines449 envvar: str | list[str] | None = None,450 # Note that shell_complete is not fully supported and will be removed in future versions451 # TODO: Remove shell_complete in a future version (after 0.16.0)452 shell_complete: Callable[419- [click.Context, click.Parameter, str],420- list["click.shell_completion.CompletionItem"] | list[str],453+ [_click.Context, _click.Parameter, str],454+ list[CompletionItem] | list[str],455 ]456 | None = None,457 autocompletion: Callable[..., Any] | None = None,458 # Option12 unmodified lines471 show_envvar: bool = False,472 # Rich settings473 rich_help_panel: str | None = None,474 ):475+ if help:476+ help = inspect.cleandoc(help)477+478 super().__init__(442- param_decls=param_decls,479+ param_decls,480 type=type,481+ multiple=multiple,482 required=required,483 default=default,484 callback=callback,485 nargs=nargs,486 metavar=metavar,487 expose_value=expose_value,488 is_eager=is_eager,489 envvar=envvar,452- show_default=show_default,453- prompt=prompt,454- confirmation_prompt=confirmation_prompt,455- hide_input=hide_input,456- is_flag=is_flag,457- multiple=multiple,458- count=count,459- allow_from_autoenv=allow_from_autoenv,460- help=help,461- hidden=hidden,462- show_choices=show_choices,463- show_envvar=show_envvar,464- prompt_required=prompt_required,490 shell_complete=shell_complete,491 )492+493+ if prompt is True:494+ if self.name is None:495+ raise TypeError("'name' is required with 'prompt=True'.")496+497+ prompt_text: str | None = self.name.replace("_", " ").capitalize()498+ elif prompt is False:499+ prompt_text = None500+ else:501+ prompt_text = prompt502+503+ self.prompt = prompt_text504+ self.confirmation_prompt = confirmation_prompt505+ self.prompt_required = prompt_required506+ self.hide_input = hide_input507+ self.hidden = hidden508+509+ # TODO: revisit all of this flag stuff510+ if is_flag and type is None:511+ self.type: types.ParamType = types.BoolParamType()512+513+ self.is_flag: bool = bool(is_flag)514+ self.is_bool_flag: bool = bool(515+ is_flag and isinstance(self.type, types.BoolParamType)516+ )517+518+ if self.is_flag:519+ self._depr_flag_value = True520+ else:521+ self._depr_flag_value = None522+523+ # Counting. TODO: test or remove? Not currently in coverage.524+ self.count = count525+ if count and type is None:526+ self.type = types.IntRange(min=0)527+528+ self.allow_from_autoenv = allow_from_autoenv529+ self.help = help530+ self.show_default = show_default531+ self.show_choices = show_choices532+ self.show_envvar = show_envvar533+534 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)535 self.rich_help_panel = rich_help_panel536 537+ def get_error_hint(self, ctx: _click.Context) -> str:538+ result = super().get_error_hint(ctx)539+ if self.show_envvar and self.envvar is not None:540+ result += f" (env var: '{self.envvar}')"541+ return result542+543+ def _parse_decls(544+ self, decls: Sequence[str], expose_value: bool545+ ) -> tuple[str | None, list[str], list[str]]:546+ opts = []547+ secondary_opts = []548+ name = None549+ possible_names = []550+551+ for decl in decls:552+ if decl.isidentifier():553+ if name is not None:554+ raise TypeError(f"Name '{name}' defined twice")555+ name = decl556+ else:557+ split_char = ";" if decl[:1] == "/" else "/"558+ if split_char in decl:559+ first, second = decl.split(split_char, 1)560+ first = first.rstrip()561+ if first:562+ possible_names.append(_split_opt(first))563+ opts.append(first)564+ second = second.lstrip()565+ if second:566+ secondary_opts.append(second.lstrip())567+ if first == second:568+ raise ValueError(569+ f"Boolean option {decl!r} cannot use the"570+ " same flag for true/false."571+ )572+ else:573+ possible_names.append(_split_opt(decl))574+ opts.append(decl)575+576+ if name is None and possible_names:577+ possible_names.sort(key=lambda x: -len(x[0])) # group long options first578+ name = possible_names[0][1].replace("-", "_").lower()579+ if not name.isidentifier():580+ name = None581+582+ return name, opts, secondary_opts583+584+ def add_to_parser(self, parser: _OptionParser, ctx: _click.Context) -> None:585+ if self.multiple:586+ action = "append"587+ elif self.count:588+ action = "count"589+ else:590+ action = "store"591+592+ if self.is_flag:593+ action = f"{action}_const"594+595+ if self.is_bool_flag and self.secondary_opts:596+ parser.add_option(597+ obj=self, opts=self.opts, dest=self.name, action=action, const=True598+ )599+ parser.add_option(600+ obj=self,601+ opts=self.secondary_opts,602+ dest=self.name,603+ action=action,604+ const=False,605+ )606+ else:607+ parser.add_option(608+ obj=self,609+ opts=self.opts,610+ dest=self.name,611+ action=action,612+ const=self._depr_flag_value,613+ )614+ else:615+ parser.add_option(616+ obj=self,617+ opts=self.opts,618+ dest=self.name,619+ action=action,620+ nargs=self.nargs,621+ )622+623+ def prompt_for_value(self, ctx: _click.Context) -> Any:624+ """This is an alternative flow that can be activated in the full625+ value processing if a value does not exist. It will prompt the626+ user until a valid value exists and then returns the processed627+ value as result.628+ """629+ assert self.prompt is not None630+631+ # Calculate the default before prompting anything to lock in the value before632+ # attempting any user interaction.633+ default = self.get_default(ctx)634+635+ # A boolean flag can use a simplified [y/n] confirmation prompt.636+ if self.is_bool_flag:637+ # Nothing prevent you to declare an option that is simultaneously:638+ # 1) auto-detected as a boolean flag,639+ # 2) allowed to prompt, and640+ # 3) still declare a non-boolean default.641+ # This forced casting into a boolean is necessary to align any non-boolean642+ # default to the prompt, which is going to be a [y/n]-style confirmation643+ # because the option is still a boolean flag. That way, instead of [y/n],644+ # we get [Y/n] or [y/N] depending on the truthy value of the default.645+ # Refs: https://github.com/pallets/click/pull/3030#discussion_r2289180249646+ if default is not None:647+ default = bool(default)648+ return _click.termui.confirm(self.prompt, default)649+650+ # If show_default is set to True/False, provide this to `prompt` as well. For651+ # non-bool values of `show_default`, we use `prompt`'s default behavior652+ prompt_kwargs: Any = {}653+ if isinstance(self.show_default, bool):654+ prompt_kwargs["show_default"] = self.show_default655+656+ return _click.termui.prompt(657+ self.prompt,658+ # Use ``None`` to inform the prompt() function to reiterate until a valid659+ # value is provided by the user if we have no default.660+ default=default,661+ type=self.type,662+ hide_input=self.hide_input,663+ show_choices=self.show_choices,664+ confirmation_prompt=self.confirmation_prompt,665+ value_proc=lambda x: self.process_value(ctx, x),666+ **prompt_kwargs,667+ )668+669+ def value_from_envvar(self, ctx: _click.Context) -> Any:670+ rv = self.resolve_envvar_value(ctx)671+672+ # Absent environment variable or an empty string is interpreted as unset.673+ if rv is None:674+ return None675+676+ def resolve_envvar_value(self, ctx: _click.Context) -> str | None:677+ rv = super().resolve_envvar_value(ctx)678+679+ if rv is not None:680+ return rv681+682+ if (683+ self.allow_from_autoenv684+ and ctx.auto_envvar_prefix is not None685+ and self.name is not None686+ ):687+ envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"688+ rv = os.environ.get(envvar)689+690+ if rv:691+ return rv692+693+ return None694+695+ def consume_value(696+ self, ctx: _click.Context, opts: Mapping[str, _click.Parameter]697+ ) -> tuple[Any, _click.core.ParameterSource]:698+ """For `Option`, the value can be collected from an interactive prompt699+ if the option is a flag that needs a value (and the `prompt` property is700+ set).701+702+ Additionally, this method handles flag option that are activated without a703+ value, in which case the `flag_value` is returned.704+ """705+ value, source = super().consume_value(ctx, opts)706+707+ # The value wasn't set, or used the param's default, prompt for one to the user708+ # if prompting is enabled.709+ if (710+ source in {None, _click.core.ParameterSource.DEFAULT}711+ and self.prompt is not None712+ and (self.required or self.prompt_required)713+ and not ctx.resilient_parsing714+ ):715+ value = self.prompt_for_value(ctx)716+ source = _click.core.ParameterSource.PROMPT717+718+ return value, source719+720 def _get_default_string(721 self,722 *,473- ctx: click.Context,723+ ctx: _click.Context,724 show_default_is_str: bool,725 default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,726 ) -> str:727 return _get_default_string(3 unmodified lines731 default_value=default_value,732 )733 734 def _extract_default_help_str(485- self, *, ctx: click.Context735+ self, *, ctx: _click.Context736 ) -> Any | Callable[[], Any] | None:737 return _extract_default_help_str(self, ctx=ctx)738 489- def make_metavar(self, ctx: click.Context) -> str:739+ def make_metavar(self, ctx: _click.Context) -> str:740 return super().make_metavar(ctx=ctx)741 492- def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:742+ def get_help_record(self, ctx: _click.Context) -> tuple[str, str] | None:743 # Duplicate all of Click's logic only to modify a single line, to allow boolean744 # flags with only names for False values as it's currently supported by Typer745 # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false746 if self.hidden:3 unmodified lines750 751 def _write_opts(opts: Sequence[str]) -> str:752 nonlocal any_prefix_is_slash753 504- rv, any_slashes = click.formatting.join_options(opts)754+ rv, any_slashes = _click.formatting.join_options(opts)755 756 if any_slashes:757 any_prefix_is_slash = True758 49 unmodified lines808 # Typer override end809 if default_string:810 extra.append(_("default: {default}").format(default=default_string))811 562- if isinstance(self.type, click.types._NumberRangeBase):812+ if isinstance(self.type, types._NumberRangeBase):813 range_str = self.type._describe_range()814 815 if range_str:816 extra.append(range_str)20 unmodified lines837 def value_is_missing(self, value: Any) -> bool:838 return _value_is_missing(self, value)839 840 591-def _value_is_missing(param: click.Parameter, value: Any) -> bool:841+def _value_is_missing(param: _click.Parameter, value: Any) -> bool:842 if value is None:843 return True844 595- # Click 8.3 and beyond596- # if value is UNSET:597- # return True598-845 if (param.nargs != 1 or param.multiple) and value == ():846 return True # pragma: no cover847 848 return False849 850 851 def _typer_format_options(606- self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter852+ self: _click.core.Command, *, ctx: _click.Context, formatter: _click.HelpFormatter853 ) -> None:854 args = []855 opts = []856 for param in self.get_params(ctx):12 unmodified lines869 formatter.write_dl(opts)870 871 872 def _typer_main_shell_completion(627- self: click.core.Command,873+ self: _click.core.Command,874 *,875 ctx_args: MutableMapping[str, Any],876 prog_name: str,877 complete_var: str | None = None,11 unmodified lines889 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)890 sys.exit(rv)891 892 647-class TyperCommand(click.core.Command):893+class TyperCommand(_click.core.Command):894 def __init__(895 self,896 name: str | None,897 *,898 context_settings: dict[str, Any] | None = None,899 callback: Callable[..., Any] | None = None,654- params: list[click.Parameter] | None = None,900+ params: list[_click.Parameter] | None = None,901 help: str | None = None,902 epilog: str | None = None,903 short_help: str | None = None,904 options_metavar: str | None = "[OPTIONS]",22 unmodified lines927 self.rich_markup_mode: MarkupMode = rich_markup_mode928 self.rich_help_panel = rich_help_panel929 930 def format_options(685- self, ctx: click.Context, formatter: click.HelpFormatter931+ self, ctx: _click.Context, formatter: _click.HelpFormatter932 ) -> None:933 _typer_format_options(self, ctx=ctx, formatter=formatter)934 935 def _main_shell_completion(25 unmodified lines961 rich_markup_mode=self.rich_markup_mode,962 **extra,963 )964 719- def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:965+ def format_help(self, ctx: _click.Context, formatter: _click.HelpFormatter) -> None:966 if not HAS_RICH or self.rich_markup_mode is None:967 if not hasattr(ctx, "obj") or ctx.obj is None:968 ctx.ensure_object(dict)969 if isinstance(ctx.obj, dict):7 unmodified lines977 markup_mode=self.rich_markup_mode,978 )979 980 735-class TyperGroup(click.core.Group):981+class TyperGroup(_click.Command):982+ allow_extra_args = True983+ allow_interspersed_args = False984+ command_class: type[_click.Command] | None = None985+ group_class: type["TyperGroup"] | type[type] | None = None986+987 def __init__(988 self,989 *,990 name: str | None = None,740- commands: dict[str, click.Command] | Sequence[click.Command] | None = None,991+ commands: dict[str, _click.Command] | Sequence[_click.Command] | None = None,992 # Rich settings993 rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,994 rich_help_panel: str | None = None,995 suggest_commands: bool = True,996+ # Click settings997+ invoke_without_command: bool = False,998+ no_args_is_help: bool = False,999+ subcommand_metavar: str | None = None,1000+ result_callback: Callable[..., Any] | None = None,1001 **attrs: Any,1002 ) -> None:747- super().__init__(name=name, commands=commands, **attrs)1003+ super().__init__(name=name, **attrs)1004 self.rich_markup_mode: MarkupMode = rich_markup_mode1005 self.rich_help_panel = rich_help_panel1006 self.suggest_commands = suggest_commands1007 1008+ # copied from Click's init1009+ if commands is None:1010+ commands = {}1011+ elif isinstance(commands, Sequence):1012+ commands = {1013+ c.name: c1014+ for c in commands1015+ if isinstance(c, _click.Command) and c.name is not None1016+ }1017+1018+ self.commands = cast(MutableMapping[str, _click.Command], commands)1019+ self.no_args_is_help = no_args_is_help1020+ self.invoke_without_command = invoke_without_command1021+1022+ if subcommand_metavar is None:1023+ subcommand_metavar = "COMMAND [ARGS]..."1024+1025+ self.subcommand_metavar = subcommand_metavar1026+ self._result_callback = result_callback1027+1028+ def add_command(self, cmd: _click.Command, name: str | None = None) -> None:1029+ name = name or cmd.name1030+ if name is None:1031+ raise TypeError("Command has no name.")1032+ self.commands[name] = cmd1033+1034+ def get_command(self, ctx: _click.Context, cmd_name: str) -> _click.Command | None:1035+ return self.commands.get(cmd_name)1036+1037+ def collect_usage_pieces(self, ctx: _click.Context) -> list[str]:1038+ rv = super().collect_usage_pieces(ctx)1039+ rv.append(self.subcommand_metavar)1040+ return rv1041+1042+ def format_commands(1043+ self, ctx: _click.Context, formatter: _click.HelpFormatter1044+ ) -> None:1045+ commands = []1046+ for subcommand in self.list_commands(ctx):1047+ cmd = self.get_command(ctx, subcommand)1048+1049+ commands.append((subcommand, cmd))1050+1051+ # allow for 3 times the default spacing1052+ if len(commands):1053+ limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)1054+1055+ rows = []1056+ for subcommand, cmd in commands:1057+ assert cmd is not None1058+ help = cmd.get_short_help_str(limit)1059+ rows.append((subcommand, help))1060+1061+ if rows:1062+ with formatter.section(_("Commands")):1063+ formatter.write_dl(rows)1064+1065+ def parse_args(self, ctx: _click.Context, args: list[str]) -> list[str]:1066+ if not args and self.no_args_is_help and not ctx.resilient_parsing:1067+ raise _click.exceptions.NoArgsIsHelpError(ctx)1068+1069+ rest = super().parse_args(ctx, args)1070+1071+ if rest:1072+ ctx._protected_args, ctx.args = rest[:1], rest[1:]1073+1074+ return ctx.args1075+1076+ def invoke(self, ctx: _click.Context) -> Any:1077+ def _process_result(value: Any) -> Any:1078+ if self._result_callback is not None:1079+ value = ctx.invoke(self._result_callback, value, **ctx.params)1080+ return value1081+1082+ if not ctx._protected_args:1083+ if self.invoke_without_command:1084+ # No subcommand was invoked, so the result callback is1085+ # invoked with the group return value for regular1086+ # groups, or an empty list for chained groups.1087+ with ctx:1088+ rv = super().invoke(ctx)1089+ # return _process_result([] if self.chain else rv)1090+ return _process_result(rv)1091+ ctx.fail(_("Missing command."))1092+1093+ # Fetch args back out1094+ args = [*ctx._protected_args, *ctx.args]1095+ ctx.args = []1096+ ctx._protected_args = []1097+1098+ # Make sure the context is entered so we do not clean up1099+ # resources until the result processor has worked.1100+ with ctx:1101+ cmd_name, cmd, args = self.resolve_command(ctx, args)1102+ assert cmd is not None1103+ ctx.invoked_subcommand = cmd_name1104+ super().invoke(ctx)1105+ sub_ctx = cmd.make_context(cmd_name, args, parent=ctx)1106+ with sub_ctx:1107+ return _process_result(sub_ctx.command.invoke(sub_ctx))1108+1109+ def shell_complete(1110+ self, ctx: _click.Context, incomplete: str1111+ ) -> list[CompletionItem]:1112+ """Return a list of completions for the incomplete value. Looks1113+ at the names of options, subcommands, and chained1114+ multi-commands.1115+ """1116+1117+ results = [1118+ CompletionItem(name, help=command.get_short_help_str())1119+ for name, command in _click.core._complete_visible_commands(ctx, incomplete)1120+ ]1121+ results.extend(super().shell_complete(ctx, incomplete))1122+ return results1123+1124 def format_options(753- self, ctx: click.Context, formatter: click.HelpFormatter1125+ self, ctx: _click.Context, formatter: _click.HelpFormatter1126 ) -> None:1127 _typer_format_options(self, ctx=ctx, formatter=formatter)1128 self.format_commands(ctx, formatter)1129 6 unmodified lines1136 _typer_main_shell_completion(1137 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var1138 )1139 1140+ def _click_resolve_command(1141+ self, ctx: _click.Context, args: list[str]1142+ ) -> tuple[str | None, _click.Command | None, list[str]]:1143+ cmd_name = args[0]1144+ original_cmd_name = cmd_name1145+1146+ # Get the command1147+ cmd = self.get_command(ctx, cmd_name)1148+1149+ if cmd is None and ctx.token_normalize_func is not None:1150+ cmd_name = ctx.token_normalize_func(cmd_name)1151+ cmd = self.get_command(ctx, cmd_name)1152+1153+ if cmd is None and not ctx.resilient_parsing:1154+ if _split_opt(cmd_name)[0]:1155+ self.parse_args(ctx, args)1156+ ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1157+ return cmd_name if cmd else None, cmd, args[1:]1158+1159 def resolve_command(769- self, ctx: click.Context, args: list[str]770- ) -> tuple[str | None, click.Command | None, list[str]]:1160+ self, ctx: _click.Context, args: list[str]1161+ ) -> tuple[str | None, _click.Command | None, list[str]]:1162 try:772- return super().resolve_command(ctx, args)773- except click.UsageError as e:1163+ return self._click_resolve_command(ctx, args)1164+ except _click.exceptions.UsageError as e:1165 if self.suggest_commands:1166 available_commands = list(self.commands.keys())1167 if available_commands and args:1168 typo = args[0]23 unmodified lines1192 rich_markup_mode=self.rich_markup_mode,1193 **extra,1194 )1195 805- def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:1196+ def format_help(self, ctx: _click.Context, formatter: _click.HelpFormatter) -> None:1197 if not HAS_RICH or self.rich_markup_mode is None:1198 return super().format_help(ctx, formatter)1199 from . import rich_utils1200 2 unmodified lines1203 ctx=ctx,1204 markup_mode=self.rich_markup_mode,1205 )1206 816- def list_commands(self, ctx: click.Context) -> list[str]:817- """Returns a list of subcommand names.818- Note that in Click's Group class, these are sorted.819- In Typer, we wish to maintain the original order of creation (cf Issue #933)"""1207+ def list_commands(self, ctx: _click.Context) -> list[str]:1208+ """Returns a list of subcommand names, maintaining the original order of creation (cf Issue #933)"""1209 return [n for n, c in self.commands.items()]modified:typer/main.py+38 added-42 removed
13 unmodified lines14 from types import TracebackType15 from typing import Annotated, Any16 from uuid import UUID17 18-import click18 from annotated_doc import Doc19 from typer._types import TyperChoice20 21+from . import _click22+from ._click import types23+from ._click.globals import get_current_context24 from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values25 from .completion import get_completion_inspect_parameters26 from .core import (27 DEFAULT_MARKUP_MODE,46 unmodified lines74 ):75 _original_except_hook(exc_type, exc_value, tb)76 return77 typer_path = os.path.dirname(__file__)76- click_path = os.path.dirname(click.__file__)78+ click_path = os.path.dirname(_click.__file__)79 internal_dir_names = [typer_path, click_path]80 exc = exc_value81 if HAS_RICH:82 from . import rich_utils25 unmodified lines108 print(line, file=sys.stderr)109 return110 111 110-def get_install_completion_arguments() -> tuple[click.Parameter, click.Parameter]:112+def get_install_completion_arguments() -> tuple[_click.Parameter, _click.Parameter]:113 install_param, show_param = get_completion_inspect_parameters()114 click_install_param, _ = get_click_param(install_param)115 click_show_param, _ = get_click_param(show_param)116 return click_install_param, click_show_param1052 unmodified lines1169 )1170 return group1171 1172 1171-def get_command(typer_instance: Typer) -> click.Command:1173+def get_command(typer_instance: Typer) -> _click.Command:1174 if typer_instance._add_completion:1175 click_install_param, click_show_param = get_install_completion_arguments()1176 if (1177 typer_instance.registered_callback1 unmodified line1179 or typer_instance.registered_groups1180 or len(typer_instance.registered_commands) > 11181 ):1182 # Create a Group1181- click_command: click.Command = get_group(typer_instance)1183+ click_command: _click.Command = get_group(typer_instance)1184 if typer_instance._add_completion:1185 click_command.params.append(click_install_param)1186 click_command.params.append(click_show_param)1187 return click_command101 unmodified lines1289 ) -> TyperGroup:1290 assert group_info.typer_instance, (1291 "A Typer instance is needed to generate a Click Group"1292 )1291- commands: dict[str, click.Command] = {}1293+ commands: dict[str, _click.Command] = {}1294 for command_info in group_info.typer_instance.registered_commands:1295 command = get_command_from_info(1296 command_info=command_info,1297 pretty_exceptions_short=pretty_exceptions_short,33 unmodified lines1331 commands=commands,1332 invoke_without_command=solved_info.invoke_without_command,1333 no_args_is_help=solved_info.no_args_is_help,1334 subcommand_metavar=solved_info.subcommand_metavar,1333- chain=solved_info.chain,1335 result_callback=solved_info.result_callback,1336 context_settings=solved_info.context_settings,1337 callback=get_callback(1338 callback=solved_info.callback,23 unmodified lines1362 1363 1364 def get_params_convertors_ctx_param_name_from_function(1365 callback: Callable[..., Any] | None,1365-) -> tuple[list[click.Argument | click.Option], dict[str, Any], str | None]:1366+) -> tuple[list[TyperArgument | TyperOption], dict[str, Any], str | None]:1367 params = []1368 convertors = {}1369 context_param_name = None1370 if callback:1371 parameters = get_params_from_function(callback)1372 for param_name, param in parameters.items():1372- if lenient_issubclass(param.annotation, click.Context):1373+ if lenient_issubclass(param.annotation, _click.Context):1374 context_param_name = param_name1375 continue1376 click_param, convertor = get_click_param(param)1377 if convertor:6 unmodified lines1384 command_info: CommandInfo,1385 *,1386 pretty_exceptions_short: bool,1387 rich_markup_mode: MarkupMode,1387-) -> click.Command:1388+) -> _click.Command:1389 assert command_info.callback, "A command must have a callback function"1390 name = command_info.name or get_command_name(command_info.callback.__name__) # ty: ignore1391 use_help = command_info.help1392 if use_help is None:93 unmodified lines1486 1487 def get_callback(1488 *,1489 callback: Callable[..., Any] | None = None,1489- params: Sequence[click.Parameter] = [],1490+ params: Sequence[_click.Parameter] = [],1491 convertors: dict[str, Callable[[str], Any]] | None = None,1492 context_param_name: str | None = None,1493 pretty_exceptions_short: bool,1494 ) -> Callable[..., Any] | None:15 unmodified lines1510 use_params[k] = use_convertors[k](v)1511 else:1512 use_params[k] = v1513 if context_param_name:1513- use_params[context_param_name] = click.get_current_context()1514+ use_params[context_param_name] = get_current_context()1515 return callback(**use_params)1516 1517 update_wrapper(wrapper, callback)1518 return wrapper1519 1520 1521 def get_click_type(1522 *, annotation: Any, parameter_info: ParameterInfo1522-) -> click.ParamType:1523+) -> types.ParamType:1524 if parameter_info.click_type is not None:1525 return parameter_info.click_type1526 1527 elif parameter_info.parser is not None:1527- return click.types.FuncParamType(parameter_info.parser)1528+ return types.FuncParamType(parameter_info.parser)1529 1530 elif annotation is str:1530- return click.STRING1531+ return types.STRING1532 elif annotation is int:1533 if parameter_info.min is not None or parameter_info.max is not None:1534 min_ = None1535 max_ = None1536 if parameter_info.min is not None:1537 min_ = int(parameter_info.min)1538 if parameter_info.max is not None:1539 max_ = int(parameter_info.max)1539- return click.IntRange(min=min_, max=max_, clamp=parameter_info.clamp)1540+ return types.IntRange(min=min_, max=max_, clamp=parameter_info.clamp)1541 else:1541- return click.INT1542+ return types.INT1543 elif annotation is float:1544 if parameter_info.min is not None or parameter_info.max is not None:1544- return click.FloatRange(1545+ return types.FloatRange(1546 min=parameter_info.min,1547 max=parameter_info.max,1548 clamp=parameter_info.clamp,1549 )1550 else:1550- return click.FLOAT1551+ return types.FLOAT1552 elif annotation is bool:1552- return click.BOOL1553+ return types.BOOL1554 elif annotation == UUID:1554- return click.UUID1555+ return types.UUID1556 elif annotation == datetime:1556- return click.DateTime(formats=parameter_info.formats)1557+ return types.DateTime(formats=parameter_info.formats)1558 elif (1559 annotation == Path1560 or parameter_info.allow_dash1561 or parameter_info.path_type9 unmodified lines1571 allow_dash=parameter_info.allow_dash,1572 path_type=parameter_info.path_type,1573 )1574 elif lenient_issubclass(annotation, FileTextWrite):1574- return click.File(1575+ return types.File(1576 mode=parameter_info.mode or "w",1577 encoding=parameter_info.encoding,1578 errors=parameter_info.errors,1579 lazy=parameter_info.lazy,1580 atomic=parameter_info.atomic,1581 )1582 elif lenient_issubclass(annotation, FileText):1582- return click.File(1583+ return types.File(1584 mode=parameter_info.mode or "r",1585 encoding=parameter_info.encoding,1586 errors=parameter_info.errors,1587 lazy=parameter_info.lazy,1588 atomic=parameter_info.atomic,1589 )1590 elif lenient_issubclass(annotation, FileBinaryRead):1590- return click.File(1591+ return types.File(1592 mode=parameter_info.mode or "rb",1593 encoding=parameter_info.encoding,1594 errors=parameter_info.errors,1595 lazy=parameter_info.lazy,1596 atomic=parameter_info.atomic,1597 )1598 elif lenient_issubclass(annotation, FileBinaryWrite):1598- return click.File(1599+ return types.File(1600 mode=parameter_info.mode or "wb",1601 encoding=parameter_info.encoding,1602 errors=parameter_info.errors,1603 lazy=parameter_info.lazy,1604 atomic=parameter_info.atomic,1605 )1606 elif lenient_issubclass(annotation, Enum):1606- # The custom TyperChoice is only needed for Click < 8.2.0, to parse the1607- # command line values matching them to the enum values. Click 8.2.0 added1608- # support for enum values but reading enum names.1609- # Passing here the list of enum values (instead of just the enum) accounts for1610- # Click < 8.2.0.1607 return TyperChoice(1608 [item.value for item in annotation],1609 case_sensitive=parameter_info.case_sensitive,1610 )1611 elif is_literal_type(annotation):1616- return click.Choice(1612+ return TyperChoice(1613 literal_values(annotation),1614 case_sensitive=parameter_info.case_sensitive,1615 )1616 raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover4 unmodified lines1621 1622 1623 def get_click_param(1624 param: ParamMeta,1629-) -> tuple[click.Argument | click.Option, Any]:1625+) -> tuple[TyperArgument | TyperOption, Any]:1626 # First, find out what will be:1627 # * ParamInfo (ArgumentInfo or OptionInfo)1628 # * default_value1629 # * required149 unmodified lines1779 rich_help_panel=parameter_info.rich_help_panel,1780 ),1781 convertor,1782 )1787- raise AssertionError("A click.Parameter should be returned") # pragma: no cover1783+ raise AssertionError("A _click.Parameter should be returned") # pragma: no cover1784 1785 1786 def get_param_callback(1787 *,7 unmodified lines1795 click_param_name = None1796 value_name = None1797 untyped_names: list[str] = []1798 for param_name, param_sig in parameters.items():1803- if lenient_issubclass(param_sig.annotation, click.Context):1799+ if lenient_issubclass(param_sig.annotation, _click.Context):1800 ctx_name = param_name1805- elif lenient_issubclass(param_sig.annotation, click.Parameter):1801+ elif lenient_issubclass(param_sig.annotation, _click.Parameter):1802 click_param_name = param_name1803 else:1804 untyped_names.append(param_name)1805 # Extract value param name first6 unmodified lines1812 if click_param_name is None:1813 if untyped_names:1814 click_param_name = untyped_names.pop(0)1815 if untyped_names:1820- raise click.ClickException(1816+ raise _click.ClickException(1817 "Too many CLI parameter callback function parameters"1818 )1819 1824- def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any:1820+ def wrapper(ctx: _click.Context, param: _click.Parameter, value: Any) -> Any:1821 use_params: dict[str, Any] = {}1822 if ctx_name:1823 use_params[ctx_name] = ctx1824 if click_param_name:21 unmodified lines1846 incomplete_name = None1847 unassigned_params = list(parameters.values())1848 for param_sig in unassigned_params[:]:1849 origin = get_origin(param_sig.annotation)1854- if lenient_issubclass(param_sig.annotation, click.Context):1850+ if lenient_issubclass(param_sig.annotation, _click.Context):1851 ctx_name = param_sig.name1852 unassigned_params.remove(param_sig)1853 elif lenient_issubclass(origin, list):1854 args_name = param_sig.name14 unmodified lines1869 unassigned_params.remove(param_sig)1870 # Extract value param name first1871 if unassigned_params:1872 show_params = " ".join([param.name for param in unassigned_params])1877- raise click.ClickException(1873+ raise _click.ClickException(1874 f"Invalid autocompletion callback parameters: {show_params}"1875 )1876 1881- def wrapper(ctx: click.Context, args: list[str], incomplete: str | None) -> Any:1877+ def wrapper(ctx: _click.Context, args: list[str], incomplete: str | None) -> Any:1878 use_params: dict[str, Any] = {}1879 if ctx_name:1880 use_params[ctx_name] = ctx1881 if args_name:123 unmodified lines2005 2006 return 02007 2008 else:2013- return click.launch(url, wait=wait, locate=locate)2009+ return _click.launch(url, wait=wait, locate=locate)modified:typer/models.py+109 added-17 removed
1 import inspect2 import io3+import os4+import stat5 from collections.abc import Callable, Sequence6 from typing import (7 TYPE_CHECKING,8 Any,9+ ClassVar,10 Optional,11 TypeVar,12+ cast,13 )14 11-import click12-import click.shell_completion15+from . import _click16+from ._click import types17+from ._click.shell_completion import CompletionItem18 19 if TYPE_CHECKING: # pragma: no cover20 from .core import TyperCommand, TyperGroup21 from .main import Typer5 unmodified lines27 28 Required = ...29 30 26-class Context(click.Context):31+class Context(_click.Context):32 """33 The [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) has some additional data about the current execution of your program.34 When declaring it in a [callback](https://typer.tiangolo.com/tutorial/options/callback-and-context/) function,35 you can access this additional information.121 unmodified lines157 158 pass159 160 156-class CallbackParam(click.Parameter):161+class CallbackParam(_click.Parameter):162 """163 In a callback function, you can declare a function parameter with type `CallbackParam`164 to access the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object.165 """124 unmodified lines290 envvar: str | list[str] | None = None,291 # Note that shell_complete is not fully supported and will be removed in future versions292 # TODO: Remove shell_complete in a future version (after 0.16.0)293 shell_complete: Callable[289- [click.Context, click.Parameter, str],290- list["click.shell_completion.CompletionItem"] | list[str],294+ [_click.Context, _click.Parameter, str],295+ list["CompletionItem"] | list[str],296 ]297 | None = None,298 autocompletion: Callable[..., Any] | None = None,299 default_factory: Callable[[], Any] | None = None,300 # Custom type301 parser: Callable[[str], Any] | None = None,297- click_type: click.ParamType | None = None,302+ click_type: types.ParamType | None = None,303 # TyperArgument304 show_default: bool | str = True,305 show_choices: bool = True,306 show_envvar: bool = True,92 unmodified lines399 envvar: str | list[str] | None = None,400 # Note that shell_complete is not fully supported and will be removed in future versions401 # TODO: Remove shell_complete in a future version (after 0.16.0)402 shell_complete: Callable[398- [click.Context, click.Parameter, str],399- list["click.shell_completion.CompletionItem"] | list[str],403+ [_click.Context, _click.Parameter, str],404+ list["CompletionItem"] | list[str],405 ]406 | None = None,407 autocompletion: Callable[..., Any] | None = None,408 default_factory: Callable[[], Any] | None = None,409 # Custom type410 parser: Callable[[str], Any] | None = None,406- click_type: click.ParamType | None = None,411+ click_type: types.ParamType | None = None,412 # Option413 show_default: bool | str = True,414 prompt: bool | str = False,415 confirmation_prompt: bool = False,111 unmodified lines527 envvar: str | list[str] | None = None,528 # Note that shell_complete is not fully supported and will be removed in future versions529 # TODO: Remove shell_complete in a future version (after 0.16.0)530 shell_complete: Callable[526- [click.Context, click.Parameter, str],527- list["click.shell_completion.CompletionItem"] | list[str],531+ [_click.Context, _click.Parameter, str],532+ list["CompletionItem"] | list[str],533 ]534 | None = None,535 autocompletion: Callable[..., Any] | None = None,536 default_factory: Callable[[], Any] | None = None,537 # Custom type538 parser: Callable[[str], Any] | None = None,534- click_type: click.ParamType | None = None,539+ click_type: types.ParamType | None = None,540 # TyperArgument541 show_default: bool | str = True,542 show_choices: bool = True,543 show_envvar: bool = True,100 unmodified lines644 self.pretty_exceptions_show_locals = pretty_exceptions_show_locals645 self.pretty_exceptions_short = pretty_exceptions_short646 647 643-class TyperPath(click.Path):644- # Overwrite Click's behaviour to be compatible with Typer's autocompletion system648+class TyperPath(types.ParamType):649+ # Based originally on code from Click 8.3.1650+ # Partly rewritten and added an override for shell_complete651+652+ envvar_list_splitter: ClassVar[str] = os.path.pathsep653+654+ def __init__(655+ self,656+ exists: bool = False,657+ file_okay: bool = True,658+ dir_okay: bool = True,659+ writable: bool = False,660+ readable: bool = True,661+ resolve_path: bool = False,662+ allow_dash: bool = False,663+ path_type: type[Any] | None = None,664+ ):665+ self.exists = exists666+ self.file_okay = file_okay667+ self.dir_okay = dir_okay668+ self.readable = readable669+ self.writable = writable670+ self.resolve_path = resolve_path671+ self.allow_dash = allow_dash672+ self.type = path_type673+674+ if self.file_okay and not self.dir_okay:675+ self.name = "file"676+ elif self.dir_okay and not self.file_okay:677+ self.name = "directory"678+ else:679+ self.name = "path"680+681+ def coerce_path_result(682+ self, value: str | os.PathLike[str]683+ ) -> str | bytes | os.PathLike[str]:684+ if self.type is not None and not isinstance(value, self.type):685+ if (686+ self.type is str687+ ): # pragma: no cover # TODO: perhaps this branch can't be hit and should be removed688+ return os.fsdecode(value)689+ elif self.type is bytes:690+ return os.fsencode(value)691+ else:692+ return cast("os.PathLike[str]", self.type(value))693+694+ return value695+696+ def convert( # ty: ignore[invalid-method-override]697+ self,698+ value: str | os.PathLike[str],699+ param: _click.Parameter | None,700+ ctx: Context | None, # type: ignore[override]701+ ) -> str | bytes | os.PathLike[str]:702+ rv = value703+704+ is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")705+706+ if not is_dash:707+ if self.resolve_path:708+ rv = os.path.realpath(rv)709+710+ try:711+ st = os.stat(rv)712+ except OSError:713+ if not self.exists:714+ return self.coerce_path_result(rv)715+ self.fail(716+ f"{self.name.title()} {_click.utils.format_filename(value)!r} does not exist.",717+ param,718+ ctx,719+ )720+721+ name = self.name.title()722+ loc = repr(_click.utils.format_filename(value))723+ if not self.file_okay and stat.S_ISREG(st.st_mode):724+ self.fail(f"{name} {loc} is a file.", param, ctx)725+726+ if not self.dir_okay and stat.S_ISDIR(st.st_mode):727+ self.fail(f"{name} {loc} is a directory.", param, ctx)728+729+ if self.readable and not os.access(rv, os.R_OK):730+ self.fail(f"{name} {loc} is not readable.", param, ctx)731+732+ if self.writable and not os.access(rv, os.W_OK):733+ self.fail(f"{name} {loc} is not writable.", param, ctx)734+735+ return self.coerce_path_result(rv)736+737 def shell_complete(646- self, ctx: click.Context, param: click.Parameter, incomplete: str647- ) -> list[click.shell_completion.CompletionItem]:738+ self, ctx: _click.Context, param: _click.Parameter, incomplete: str739+ ) -> list[CompletionItem]:740 """Return an empty list so that the autocompletion functionality741 will work properly from the commandline.742 """743 return []modified:typer/params.py+20 added-18 removed
1 from collections.abc import Callable2 from typing import TYPE_CHECKING, Annotated, Any, overload3 4-import click4 from annotated_doc import Doc5 6+from . import _click7+from ._click import types8+from ._click.shell_completion import CompletionItem9 from .models import ArgumentInfo, OptionInfo10 11 if TYPE_CHECKING: # pragma: no cover10- import click.shell_completion12+ pass13 14 15 # Overload for Option created with custom type 'parser'16 @overload8 unmodified lines25 envvar: str | list[str] | None = None,26 # Note that shell_complete is not fully supported and will be removed in future versions27 # TODO: Remove shell_complete in a future version (after 0.16.0)28 shell_complete: Callable[27- [click.Context, click.Parameter, str],28- list["click.shell_completion.CompletionItem"] | list[str],29+ [_click.Context, _click.Parameter, str],30+ list["CompletionItem"] | list[str],31 ]32 | None = None,33 autocompletion: Callable[..., Any] | None = None,34 default_factory: Callable[[], Any] | None = None,55 unmodified lines90 envvar: str | list[str] | None = None,91 # Note that shell_complete is not fully supported and will be removed in future versions92 # TODO: Remove shell_complete in a future version (after 0.16.0)93 shell_complete: Callable[92- [click.Context, click.Parameter, str],93- list["click.shell_completion.CompletionItem"] | list[str],94+ [_click.Context, _click.Parameter, str],95+ list["CompletionItem"] | list[str],96 ]97 | None = None,98 autocompletion: Callable[..., Any] | None = None,99 default_factory: Callable[[], Any] | None = None,100 # Custom type99- click_type: click.ParamType | None = None,101+ click_type: types.ParamType | None = None,102 # Option103 show_default: bool | str = True,104 prompt: bool | str = False,105 confirmation_prompt: bool = False,160 unmodified lines266 ] = None,267 # TODO: Remove shell_complete in a future version (after 0.16.0)268 shell_complete: Annotated[269 Callable[268- [click.Context, click.Parameter, str],269- list["click.shell_completion.CompletionItem"] | list[str],270+ [_click.Context, _click.Parameter, str],271+ list["CompletionItem"] | list[str],272 ]273 | None,274 Doc(275 """68 unmodified lines344 """345 ),346 ] = None,347 click_type: Annotated[346- click.ParamType | None,348+ types.ParamType | None,349 Doc(350 """351 Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.352 662 unmodified lines1015 envvar: str | list[str] | None = None,1016 # Note that shell_complete is not fully supported and will be removed in future versions1017 # TODO: Remove shell_complete in a future version (after 0.16.0)1018 shell_complete: Callable[1017- [click.Context, click.Parameter, str],1018- list["click.shell_completion.CompletionItem"] | list[str],1019+ [_click.Context, _click.Parameter, str],1020+ list["CompletionItem"] | list[str],1021 ]1022 | None = None,1023 autocompletion: Callable[..., Any] | None = None,1024 default_factory: Callable[[], Any] | None = None,46 unmodified lines1071 envvar: str | list[str] | None = None,1072 # Note that shell_complete is not fully supported and will be removed in future versions1073 # TODO: Remove shell_complete in a future version (after 0.16.0)1074 shell_complete: Callable[1073- [click.Context, click.Parameter, str],1074- list["click.shell_completion.CompletionItem"] | list[str],1075+ [_click.Context, _click.Parameter, str],1076+ list["CompletionItem"] | list[str],1077 ]1078 | None = None,1079 autocompletion: Callable[..., Any] | None = None,1080 default_factory: Callable[[], Any] | None = None,1081 # Custom type1080- click_type: click.ParamType | None = None,1082+ click_type: types.ParamType | None = None,1083 # TyperArgument1084 show_default: bool | str = True,1085 show_choices: bool = True,1086 show_envvar: bool = True,133 unmodified lines1220 ] = None,1221 # TODO: Remove shell_complete in a future version (after 0.16.0)1222 shell_complete: Annotated[1223 Callable[1222- [click.Context, click.Parameter, str],1223- list["click.shell_completion.CompletionItem"] | list[str],1224+ [_click.Context, _click.Parameter, str],1225+ list["CompletionItem"] | list[str],1226 ]1227 | None,1228 Doc(1229 """68 unmodified lines1298 """1299 ),1300 ] = None,1301 click_type: Annotated[1300- click.ParamType | None,1302+ types.ParamType | None,1303 Doc(1304 """1305 Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.1306 527 unmodified linesmodified:typer/rich_utils.py+24 added-21 removed
6 unmodified lines7 from gettext import gettext as _8 from os import getenv9 from typing import Any, Literal10 11-import click11 from rich import box12 from rich.align import Align13 from rich.columns import Columns14 from rich.console import Console, RenderableType, group8 unmodified lines23 from rich.theme import Theme24 from rich.traceback import Traceback25 from typer.models import DeveloperExceptionConfig26 27+from . import _click28+from ._click import types29+from .core import TyperArgument, TyperGroup, TyperOption30+31 # Default styles32 STYLE_OPTION = "bold cyan"33 STYLE_SWITCH = "bold green"34 STYLE_NEGATIVE_OPTION = "bold magenta"151 unmodified lines186 187 @group()188 def _get_help_text(189 *,187- obj: click.Command | click.Group,190+ obj: _click.Command | TyperGroup,191 markup_mode: MarkupModeStrict,192 ) -> Iterable[Markdown | Text]:193 """Build primary help text for a click command or group.194 38 unmodified lines233 234 235 def _get_parameter_help(236 *,234- param: click.Option | click.Argument | click.Parameter,235- ctx: click.Context,237+ param: TyperOption | TyperArgument | _click.Parameter,238+ ctx: _click.Context,239 markup_mode: MarkupModeStrict,240 ) -> Columns:241 """Build primary help text for a click option or argument.242 107 unmodified lines350 351 def _print_options_panel(352 *,353 name: str,351- params: list[click.Option] | list[click.Argument],352- ctx: click.Context,354+ params: list[TyperOption] | list[TyperArgument],355+ ctx: _click.Context,356 markup_mode: MarkupModeStrict,357 console: Console,358 ) -> None:359 options_rows: list[list[RenderableType]] = []19 unmodified lines379 metavar = Text(style=STYLE_METAVAR, overflow="fold")380 metavar_str = param.make_metavar(ctx=ctx)381 # Do it ourselves if this is a positional argument382 if (380- isinstance(param, click.Argument)383+ isinstance(param, TyperArgument)384 and param.name385 and metavar_str == param.name.upper()386 ):387 metavar_str = param.type.name.upper()5 unmodified lines393 # Range - from394 # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501395 # skip count with default range type396 if (394- isinstance(param.type, click.types._NumberRangeBase)395- and isinstance(param, click.Option)397+ isinstance(param.type, types._NumberRangeBase)398+ and isinstance(param, TyperOption)399 and not (param.count and param.type.min == 0 and param.type.max is None)400 ):401 range_str = param.type._describe_range()402 if range_str:58 unmodified lines461 462 def _print_commands_panel(463 *,464 name: str,462- commands: list[click.Command],465+ commands: list[_click.Command],466 markup_mode: MarkupModeStrict,467 console: Console,468 cmd_len: int,469 ) -> None:66 unmodified lines536 537 538 def rich_format_help(539 *,537- obj: click.Command | click.Group,538- ctx: click.Context,540+ obj: _click.Command | TyperGroup,541+ ctx: _click.Context,542 markup_mode: MarkupModeStrict,543 ) -> None:544 """Print nicely formatted help text using rich.545 24 unmodified lines570 ),571 (0, 1, 1, 1),572 )573 )571- panel_to_arguments: defaultdict[str, list[click.Argument]] = defaultdict(list)572- panel_to_options: defaultdict[str, list[click.Option]] = defaultdict(list)574+ panel_to_arguments: defaultdict[str, list[TyperArgument]] = defaultdict(list)575+ panel_to_options: defaultdict[str, list[TyperOption]] = defaultdict(list)576 for param in obj.get_params(ctx):577 # Skip if option is hidden578 if getattr(param, "hidden", False):579 continue577- if isinstance(param, click.Argument):580+ if isinstance(param, TyperArgument):581 panel_name = (582 getattr(param, _RICH_HELP_PANEL_NAME, None) or ARGUMENTS_PANEL_TITLE583 )584 panel_to_arguments[panel_name].append(param)582- elif isinstance(param, click.Option):585+ elif isinstance(param, TyperOption):586 panel_name = (587 getattr(param, _RICH_HELP_PANEL_NAME, None) or OPTIONS_PANEL_TITLE588 )589 panel_to_options[panel_name].append(param)35 unmodified lines625 markup_mode=markup_mode,626 console=console,627 )628 626- if isinstance(obj, click.Group):627- panel_to_commands: defaultdict[str, list[click.Command]] = defaultdict(list)629+ if isinstance(obj, TyperGroup):630+ panel_to_commands: defaultdict[str, list[_click.Command]] = defaultdict(list)631 for command_name in obj.list_commands(ctx):632 command = obj.get_command(ctx, command_name)633 if command and not command.hidden:634 panel_name = (41 unmodified lines676 epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode)677 console.print(Padding(Align(epilogue_text, pad=False), 1))678 679 677-def rich_format_error(self: click.ClickException) -> None:680+def rich_format_error(self: _click.ClickException) -> None:681 """Print richly formatted click errors.682 683 Called by custom exception handler to print richly formatted click errors.681- Mimics original click.ClickException.echo() function but with rich formatting.684+ Mimics original _click.ClickException.echo() function but with rich formatting.685 """686 # Don't do anything when it's a NoArgsIsHelpError (without importing it, cf. #1278)687 if self.__class__.__name__ == "NoArgsIsHelpError":688 return689 690 console = _get_rich_console(stderr=True)688- ctx: click.Context | None = getattr(self, "ctx", None)691+ ctx: _click.Context | None = getattr(self, "ctx", None)692 if ctx is not None:693 console.print(ctx.get_usage())694 695 if ctx is not None and ctx.command.get_help_option(ctx) is not None:63 unmodified linesmodified:typer/testing.py+3 added-2 removed
1 from collections.abc import Mapping, Sequence2 from typing import IO, Any3 4-from click.testing import CliRunner as ClickCliRunner # noqa5-from click.testing import Result4 from typer.main import Typer5 from typer.main import get_command as _get_command6 7+from ._click.testing import CliRunner as ClickCliRunner # noqa8+from ._click.testing import Result9 10+11 class CliRunner(ClickCliRunner):12 def invoke( # type: ignore13 self,14 app: Typer,17 unmodified linesmodified:CITATION.cff+2 added-1 removed
16 unmodified lines17 abstract: >-18 Typer, build great CLIs. Easy to code. Based on Python type hints.19 keywords:20 - typer21- - click21+ - cli22+ - python23 license: MITmodified:mkdocs.yml+1 added
144 unmodified lines145 - tutorial/package.md146 - tutorial/exceptions.md147 - tutorial/one-file-per-command.md148 - tutorial/typer-command.md149+ - tutorial/click.md150 - "":151 - reference/index.md152 - reference/typer.md153 - reference/run_launch.md79 unmodified linesmodified:pyproject.toml+2 added-2 removed
31 unmodified lines32 "Programming Language :: Python :: 3.13",33 "Programming Language :: Python :: 3.14",34 ]35 dependencies = [36- "click >= 8.2.1, < 8.4",36 "shellingham >=1.3.0",37 "rich >=13.8.0",38 "annotated-doc >=0.0.2",39+ "colorama; platform_system == 'Windows'",40 ]41 readme = "README.md"42 43 [project.urls]144 unmodified lines188 # No need to worry about rich imports in docs189 "docs_src/*" = ["TID"]190 191 [tool.ruff.lint.isort]192-known-third-party = ["typer", "click"]192+known-third-party = ["typer"]193 # For docs_src/subcommands/tutorial003/194 known-first-party = ["reigns", "towns", "lands", "items", "users"]195 196 [tool.ruff.lint.pyupgrade]34 unmodified linesmodified:README.md+11 added-2 removed
350 unmodified lines351 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.352 353 ## Dependencies354 355-**Typer** stands on the shoulders of giants. It has three required dependencies:355+**Typer** requires only a few dependencies (most are tiny):356 357-* [Click](https://click.palletsprojects.com/): a popular tool for building CLIs in Python. Typer is based on it.357 * [`rich`](https://rich.readthedocs.io/en/stable/index.html): to show nicely formatted errors automatically.358 * [`shellingham`](https://github.com/sarugaku/shellingham): to automatically detect the current shell when installing completion.359+* [`annotated-doc`](https://github.com/fastapi/annotated-doc): to generate documentation from Python type annotations.360+* [`colorama`](https://github.com/tartley/colorama) (only on Windows): for producing colored terminal text on Windows.361 362+### Click code363+364+Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.365+366+Since version 0.26.0, Typer has vendored Click (included Click's source code internally, instead of installing it as a third party package) and has unified the code interactions between Typer and the embedded Click source code for easier maintainability in the future.367+368+Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.369+370 ### `typer-slim`371 372 There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.373 7 unmodified linesmodified:uv.lock+2 added-2 removed
1785 unmodified lines1786 name = "typer"1787 source = { editable = "." }1788 dependencies = [1789 { name = "annotated-doc" },1790- { name = "click" },1790+ { name = "colorama", marker = "sys_platform == 'win32'" },1791 { name = "rich" },1792 { name = "shellingham" },1793 ]1794 54 unmodified lines1849 1850 [package.metadata]1851 requires-dist = [1852 { name = "annotated-doc", specifier = ">=0.0.2" },1853- { name = "click", specifier = ">=8.2.1,<8.4" },1853+ { name = "colorama", marker = "sys_platform == 'win32'" },1854 { name = "rich", specifier = ">=13.8.0" },1855 { name = "shellingham", specifier = ">=1.3.0" },1856 ]1857 173 unmodified lines