Skip to content
Myr

➖ 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

74 files+10174 added−355 removed

added:docs/tutorial/click.md+69 added
modified:docs/tutorial/install.md+1 added-1 removed
modified:docs/tutorial/package.md+2 added-4 removed
58 unmodified lines
59// It creates a virtual environment for your project60Using CPython 3.14.0 interpreter at: /location/of/python/61Creating virtual environment at: .venv6263Resolved 10 packages in 21ms63Resolved 9 packages in 21ms64 Built rick-portal-gun @ file:/home/rick-portal-gun65Prepared 1 package in 19ms66Installed 10 packages in 34ms67 + click==8.3.166Installed 9 packages in 34ms67 + colorama==0.4.668 + markdown-it-py==4.0.069 + mdurl==0.1.270 + pygments==2.19.2
495 unmodified lines
566Collecting rick-portal-gun567 Downloading rick_portal_gun-0.1.0-py3-none-any.whl.metadata (435 bytes)568Requirement 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)569Requirement 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)571Requirement 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)570Requirement 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)571Requirement 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)572Requirement 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)573Requirement 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 lines
modified:docs/tutorial/printing.md+1 added-1 removed
194 unmodified lines
195And for the cases where you want to display data more beautifully, or more advanced content, you should use **Rich** instead.196197### Why `typer.echo`198199`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.200201But 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.202203If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.
69 unmodified lines
modified:docs/alternatives.md+3 added-3 removed
modified:docs/features.md-8 removed
61 unmodified lines
62* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.6364///6566/// tip6768**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.6970Then 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.7172///7366## Tested6768* 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 line
modified:docs/index.md+11 added-2 removed
358 unmodified lines
359For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.360361## Dependencies362363**Typer** stands on the shoulders of giants. It has three required dependencies:363**Typer** requires only a few dependencies (most are tiny):364365* [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.369370### Click code371372Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.373374Since 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.375376Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.377378### `typer-slim`379380There 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 lines
modified:tests/assets/completion_argument.py+2 added-2 removed
1import click1import typer2from typer import _click34app = typer.Typer()567def shell_complete(ctx: click.Context, param: click.Parameter, incomplete: str):7def 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 lines
modified:tests/test_cli/test_help.py+121 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67runner = CliRunner()8910def test_script_help():11 result = subprocess.run(12 [13 sys.executable,
26 unmodified lines
40 capture_output=True,41 encoding="utf-8",42 )43 assert "Could not import as Python file" in result.stderr444546def test_short_help() -> None:47 app = typer.Typer(48 rich_markup_mode=None,49 context_settings={"max_content_width": 50},50 )5152 @app.command(help=" \n\t ")53 def empty() -> None:54 pass # pragma: no cover5556 @app.command(help="\b first sentence.")57 def marker() -> None:58 pass # pragma: no cover5960 # Forcing truncation61 @app.command(help=f"{'x' * 30} {'y' * 5} z trailing")62 def long() -> None:63 pass # pragma: no cover6465 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.output727374def test_help_wrapping() -> None:75 app = typer.Typer(76 rich_markup_mode=None,77 context_settings={"max_content_width": 50},78 )7980 @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 cover9495 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.output104105106def test_help_wrapping_long_name() -> None:107 app = typer.Typer(rich_markup_mode=None)108109 @app.command()110 def cmd(value: str) -> None:111 pass # pragma: no cover112113 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 == 0120121 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(" ")126127128def test_format_long_help_option() -> None:129 app = typer.Typer(rich_markup_mode=None)130131 @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 cover140141 result = runner.invoke(app, ["cmd", "--help"], terminal_width=80)142 assert result.exit_code == 0143144 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
1import subprocess2import sys34import typer5from typer.testing import CliRunner67runner = CliRunner()8910def 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.stderr313233def 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.stderr515253def test_ignore_unknown_short_option() -> None:54 app = typer.Typer(55 context_settings={"ignore_unknown_options": True, "allow_extra_args": True}56 )5758 @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)6465 result = runner.invoke(app, ["-azq"])66 assert result.exit_code == 067 assert "['-zq']" in result.output
added:tests/test_cli/test_program_name.py+13 added
1from typer import _click234def test_detect_program_name_submodule_path() -> None:5 class MainModule:6 __package__ = "example"78 program_name = _click.utils._detect_program_name(9 path="/tmp/cli.py",10 _main=MainModule(),11 )1213 assert program_name == "python -m example.cli"
added:tests/test_completion/choice_case_insensitive_example.py+19 added
1from enum import Enum23import typer45app = typer.Typer()678class User(str, Enum):9 rick = "rick"10 morty = "morty"111213@app.command()14def main(name: User = typer.Option(User.rick, "--name", case_sensitive=False)):15 print(name.value)161718if __name__ == "__main__":19 app()
added:tests/test_completion/choice_example.py+19 added
1from enum import Enum23import typer45app = typer.Typer()678class User(str, Enum):9 rick = "rick"10 morty = "morty"111213@app.command()14def main(name: User = typer.Option(User.rick, "--name")):15 print(name.value)161718if __name__ == "__main__":19 app()
added:tests/test_completion/completion_option_then_argument.py+23 added
1import typer23app = typer.Typer()456def complete_name(ctx, args, incomplete):7 return ["opt-choice"] # pragma: no cover8910def complete_target(ctx, args, incomplete):11 return ["arg-choice"]121314@app.command()15def 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 cover202122if __name__ == "__main__":23 app()
added:tests/test_completion/file_example.py+12 added
1import typer23app = typer.Typer()456@app.command()7def main(config: typer.FileText = typer.Option(...)):8 print(config.read())91011if __name__ == "__main__":12 app()
added:tests/test_completion/test_completion_choice_no_case.py+32 added
1import os2import subprocess3import sys45from . import choice_case_insensitive_example as mod678def 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.stdout161718def 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.stdout
added:tests/test_completion/test_completion_choice.py+32 added
1import os2import subprocess3import sys45from . import choice_example as mod678def 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.stdout161718def 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.stdout
added:tests/test_completion/test_completion_file.py+39 added
1import os2import subprocess3import sys45from . import file_example as mod678def 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.stdout242526def 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.stdout
modified:tests/test_completion/test_completion_option_colon.py+33 added
175 unmodified lines
176 assert "latest alpine image" not in result.stdout177 assert "nvidia/cuda:10.0-devel-ubuntu18.04" not in result.stdout178179180def 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.stdout195196197def 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() == ""211212213def test_completion_colon_pwsh_all():214 result = subprocess.run(215 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],216 capture_output=True,
108 unmodified lines
modified:tests/test_completion/test_completion.py+27 added
1 unmodified line
2import subprocess3import sys4from pathlib import Path56from typer._click.shell_completion import CompletionItem78from docs_src.typer_app import tutorial001_py310 as mod910from ..utils import needs_bash, needs_linux, requires_completion_permission11from . import completion_option_then_argument as mod_option_arg121314@needs_bash15@needs_linux
150 unmodified lines
166 assert (167 "Register-ArgumentCompleter -Native -CommandName tutorial001_py310.py -ScriptBlock $scriptblock"168 in result.stdout169 )170171172def 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.stdout187188189def test_completion_item_getattr() -> None:190 item = CompletionItem("demo", source="envvar")191192 assert item.source == "envvar"193 assert item.missing is None
modified:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001.py+7 added
2 unmodified lines
3import sys4from types import ModuleType56import pytest7import typer8from typer.testing import CliRunner910runner = CliRunner()11
10 unmodified lines
22 mod = importlib.import_module(module_name)23 return mod242526def 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"303132def test_help(mod: ModuleType):33 result = runner.invoke(mod.app, ["--help"])34 assert result.exit_code == 035 assert "--force" in result.output
28 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial001.py+17 added
1import subprocess2import sys3from datetime import datetime45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.datetime import tutorial001_py310 as mod910runner = CliRunner()11app = mod.app121314def 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"181920def 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.output
5 unmodified lines
29 assert "Interesting day to be born: 1956-01-31 10:00:00" in result.output30 assert "Birth hour: 10" in result.output313233def 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.output404142def test_invalid():43 result = runner.invoke(app, ["july-19-1989"])44 assert result.exit_code != 045 assert (
16 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_index/test_tutorial001.py+11 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.index import tutorial001_py310 as mod89runner = CliRunner()10app = mod.app111213def 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"212223def test_help():24 result = runner.invoke(app, ["--help"])25 assert result.exit_code == 026 assert "--age" in result.output
30 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001.py+13 added
22 unmodified lines
23 mod = importlib.import_module(module_name)24 return mod252627def test_type_repr(mod: ModuleType):28 command = typer.main.get_command(mod.app)2930 id_param = next(param for param in command.params if param.name == "id")31 assert repr(id_param.type) == "<IntRange 0<=x<=1000>"3233 age_param = next(param for param in command.params if param.name == "age")34 assert repr(age_param.type) == "<IntRange x>=18>"3536 score_param = next(param for param in command.params if param.name == "score")37 assert repr(score_param.type) == "<FloatRange x<=100>"383940def test_help(mod: ModuleType):41 result = runner.invoke(mod.app, ["--help"])42 assert result.exit_code == 043 assert "--age" in result.output
61 unmodified lines
modified:tests/test_tutorial/test_parameter_types/test_uuid/test_tutorial001.py+16 added
1import subprocess2import sys3import uuid45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.uuid import tutorial001_py310 as mod910runner = CliRunner()11app = mod.app121314def 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"181920def 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.output252627def 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.output333435def test_invalid_uuid():36 result = runner.invoke(app, ["7479706572-72756c6573"])37 assert result.exit_code != 038 assert (
12 unmodified lines
added:tests/atomic_write_example.py+63 added
1import time23import typer45app = typer.Typer()678@app.command()9def 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")202122@app.command()23def 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")282930@app.command()31def 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")394041@app.command()42def invalid_atomic_append(43 config: typer.FileText = typer.Option(..., mode="a", atomic=True, lazy=False),44) -> None:45 typer.echo(config.name) # pragma: no cover464748@app.command()49def invalid_atomic_exclusive(50 config: typer.FileText = typer.Option(..., mode="x", atomic=True, lazy=False),51) -> None:52 typer.echo(config.name) # pragma: no cover535455@app.command()56def invalid_atomic_read(57 config: typer.FileText = typer.Option(..., mode="r", atomic=True, lazy=False),58) -> None:59 typer.echo(config.name) # pragma: no cover606162if __name__ == "__main__":63 app()
modified:tests/test_annotated.py+12 added
1import sys2from pathlib import Path3from typing import Annotated45import pytest6import typer7from typer.testing import CliRunner89runner = CliRunner()
85 unmodified lines
95 assert isinstance(my_path, CustomPath)9697 result = runner.invoke(app, "/some/quirky/path/implementation")98 assert result.exit_code == 099100101def test_annotated_option_invalid():102 app = typer.Typer()103104 @app.command()105 def cmd(value: Annotated[str, typer.Option(..., "foo-bar")]):106 print(value) # pragma: no cover107108 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
1import subprocess2import sys3from pathlib import Path45import pytest67from . import atomic_write_example as mod8910def 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")1415 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 None3031 # 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_content3536 # 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 )444546def test_atomic_binary_write(tmp_path: Path) -> None:47 output_file = tmp_path / "atomic-binary.bin"4849 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 )6263 assert result.returncode == 0, result.stderr64 assert "written binary atomically" in result.stdout65 assert output_file.read_bytes() == b"\x00\x01binary-atomic\n"666768def test_atomic_api(tmp_path: Path) -> None:69 output_file = tmp_path / "atomic-api.txt"7071 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 )8485 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"909192@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)100def 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")105106 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 )119120 assert result.returncode != 0121 combined_output = f"{result.stdout}\n{result.stderr}"122 assert expected_message in combined_output
added:tests/test_core.py+379 added
1from typing import Annotated23import pytest4import typer5import typer._completion_shared6import typer.completion7from typer import _click8from typer.core import TyperArgument, TyperCommand, TyperGroup, TyperOption, _split_opt9from typer.testing import CliRunner1011runner = CliRunner()121314def test_human_readable_name() -> None:15 app = typer.Typer()1617 @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 cover2425 command = typer.main.get_command(app)26 params = {param.name: param for param in command.params}2728 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"313233def test_parameter_metavar() -> None:34 app = typer.Typer(rich_markup_mode=None)3536 @app.command()37 def cmd(name: Annotated[str, typer.Option(metavar="CUSTOM")]) -> None:38 pass # pragma: no cover3940 result = runner.invoke(app, ["--help"])41 assert result.exit_code == 042 assert "--name CUSTOM" in result.output434445def test_parameter_nargs_gt_1() -> None:46 param = TyperArgument(param_decls=["value"], type=str, nargs=2)47 ctx = _click.Context(TyperCommand(name="cmd"))4849 assert param.type_cast_value(ctx, ("one", "two")) == ("one", "two")5051 with pytest.raises(52 _click.exceptions.BadParameter, match="Takes 2 values but 1 given."53 ):54 param.type_cast_value(ctx, ("one",))555657def 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 == []6364 # 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)6768 # len(param_decl) > 1: raises69 with pytest.raises(TypeError, match="take exactly one parameter declaration"):70 TyperArgument(param_decls=["first", "second"])7172 # duplicated identifier in option declarations: raises73 with pytest.raises(TypeError, match="Name 'name' defined twice"):74 TyperOption(param_decls=["name", "name"], required=False)7576 # 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)7980 # 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 None8384 # 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)8788 # 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 == 09899100def 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 hint109110111def test_group_init() -> None:112 group_no_commands = TyperGroup(name="root", commands=None)113 assert group_no_commands.commands == {}114115 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}119120121@pytest.mark.parametrize("with_result_callback", [False, True])122def test_group_result_callback(with_result_callback: bool) -> None:123 called = {"child": False, "result_callback": False}124125 def child_callback() -> None:126 called["child"] = True127 return None128129 def result_callback(value, **kwargs): # type: ignore[no-untyped-def]130 called["result_callback"] = True131 return value132133 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"])140141 result = group.invoke(ctx)142143 assert result is None144 assert called["child"] is True145 assert called["result_callback"] is with_result_callback146 assert ctx.invoked_subcommand == "child"147148149def test_group_add_command() -> None:150 group = TyperGroup(name="root")151 unnamed_command = TyperCommand(name=None)152153 with pytest.raises(TypeError, match="Command has no name."):154 group.add_command(unnamed_command)155156157def 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)161162 cmd_name, cmd, remaining = group._click_resolve_command(ctx, ["CHILD"])163164 assert cmd_name == "child"165 assert cmd is child166 assert remaining == []167168169@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)177def 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")191192 ctx = _click.Context(TyperCommand(name="cmd"), auto_envvar_prefix=auto_prefix)193 assert option.resolve_envvar_value(ctx) == expected194195196def 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"))207208 assert option.resolve_envvar_value(ctx) is None209210211def test_context_auto_envvar() -> None:212 app = typer.Typer(context_settings={"auto_envvar_prefix": "APP"})213 sub_app = typer.Typer()214215 @sub_app.command()216 def clone(ctx: typer.Context) -> None:217 print(ctx.auto_envvar_prefix)218219 app.add_typer(sub_app, name="beth")220221 result = runner.invoke(app, ["beth", "clone"])222 assert result.exit_code == 0223 assert "APP_BETH_CLONE" in result.stdout224225226def test_context_with_resource() -> None:227 events: list[str] = []228229 class DemoResource:230 def __enter__(self) -> str:231 events.append("enter")232 return "pickle-rick"233234 def __exit__(self, *args: object) -> None:235 events.append("exit")236237 app = typer.Typer()238239 @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")245246 result = runner.invoke(app)247248 assert result.exit_code == 0249 assert "I'm a pickle" in result.stdout250 assert events == ["enter", "exit"]251252253def test_context_find_root() -> None:254 app = typer.Typer()255 sub_app = typer.Typer()256257 @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")263264 app.add_typer(sub_app, name="sub")265266 result = runner.invoke(app, ["sub", "child"])267 assert result.exit_code == 0268 assert "ok" in result.stdout269270271def test_context_find_object() -> None:272 class Marker:273 pass274275 marker = Marker()276 app = typer.Typer()277278 @app.callback()279 def callback(ctx: typer.Context) -> None:280 ctx.obj = marker281282 @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")287288 result = runner.invoke(app, ["child"])289 assert result.exit_code == 0290 assert "ok" in result.stdout291292293def test_context_lookup_default_callable() -> None:294 app = typer.Typer()295296 @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")303304 result = runner.invoke(app)305 assert result.exit_code == 0306 assert "ok" in result.stdout307308309def test_context_abort() -> None:310 app = typer.Typer()311312 @app.command()313 def cmd(ctx: typer.Context) -> None:314 ctx.abort()315316 result = runner.invoke(app, standalone_mode=False)317 assert result.exit_code == 1318 assert isinstance(result.exception, _click.core.Abort)319320321def test_command_help_disabled() -> None:322 app = typer.Typer()323324 @app.command(add_help_option=False)325 def cmd() -> None:326 pass # pragma: no cover327328 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"332333334def test_command_help_deprecated() -> None:335 app = typer.Typer(rich_markup_mode=None, epilog="Built with love")336337 @app.command(short_help="Shorty", help="Regular help text.", deprecated=True)338 def one() -> None:339 pass # pragma: no cover340341 @app.command()342 def two() -> None:343 pass # pragma: no cover344345 result = runner.invoke(app, ["one", "--help"])346 assert result.exit_code == 0347 assert "Regular help text. (DEPRECATED)" in result.output348349 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(" ", "")353354355@pytest.mark.parametrize(356 ("value", "expected_prefix", "expected_opt"),357 [358 ("--verbose", "--", "verbose"),359 ("//verbose", "//", "verbose"),360 ("-verbose", "-", "verbose"),361 ("verbose", "", "verbose"),362 ],363)364def 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_opt368369370def test_nargs_default_map():371 app = typer.Typer()372373 @app.command()374 def main(names: list[str] = typer.Option(None)):375 print(names) # pragma: no cover376377 result = runner.invoke(app, [], default_map={"names": "not-a-list"})378 assert result.exit_code == 2379 assert "Invalid value" in result.output
modified:tests/test_launch.py+84 added-8 removed
1import io2import subprocess3from unittest.mock import patch45import pytest6import typer77from tests.utils import needs_windows8from tests.utils import needs_linux, needs_macos, needs_windows910url = "http://example.com"1112
38 unmodified lines
5152 mock_webbrowser_open.assert_called_once_with(url)535454def 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.fixture56def allow_dev_null(monkeypatch):57 real_open = open5858 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 cover6364 monkeypatch.setattr("builtins.open", fake_open)656667@needs_macos68def test_open_url_macos(monkeypatch, allow_dev_null):69 recorded: list[list[str]] = []7071 class Proc:72 def wait(self) -> int:73 return 427475 def fake_popen(args, **kwargs):76 recorded.append(list(args))77 return Proc()7879 monkeypatch.setattr(subprocess, "Popen", fake_popen)8081 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"848586@needs_windows87def test_launch_files_windows(monkeypatch):88 calls: list[list[str]] = []8990 def fake_call(args):91 calls.append(list(args))92 return 09394 monkeypatch.setattr(subprocess, "call", fake_call)9596 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"]100101 monkeypatch.setattr(subprocess, "call", lambda a: (_ for _ in ()).throw(OSError()))102 assert typer.launch("D:/no/such/file.txt", wait=False, locate=False) == 127103104105@needs_linux106def test_open_url_linux_wait(monkeypatch):107 class Proc:108 def __init__(self, code: int = 0) -> None:109 self._code = code110111 def wait(self) -> int:112 return self._code113114 monkeypatch.setattr(subprocess, "Popen", lambda *a, **k: Proc(7))115116 assert typer.launch("/file", wait=True, locate=False) == 7117118119@needs_linux120def test_open_url_linux_locate(monkeypatch):121 recorded: list[list[str]] = []122123 class Proc:124 def wait(self) -> int:125 return 0 # pragma: no cover126127 def fake_popen(args, **kwargs):128 recorded.append(list(args))129 return Proc()130131 monkeypatch.setattr(subprocess, "Popen", fake_popen)132133 assert typer.launch("/tmp/sub/file.txt", wait=False, locate=True) == 0134 assert recorded[-1] == ["xdg-open", "/tmp/sub"]135136137@needs_windows138def 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 lines
modified:tests/test_others.py+150 added-28 removed
4 unmodified lines
5from pathlib import Path6from typing import Annotated7from unittest import mock89import click9import pytest10import typer11import typer._completion_shared12import typer.completion14from typer.core import _split_opt13from typer import _click14from typer.main import solve_typer_info_defaults, solve_typer_info_help15from typer.models import ParameterInfo, TyperInfo16from typer.testing import CliRunner17
17 unmodified lines
35def test_too_many_parsers():36 def custom_parser(value: str) -> int:37 return int(value) # pragma: no cover3840 class CustomClickParser(click.ParamType):39 class CustomClickParser(_click.types.ParamType):40 name = "custom_parser"4142 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 cover4950 expected_error = (
8 unmodified lines
59def test_valid_parser_permutations():60 def custom_parser(value: str) -> int:61 return int(value) # pragma: no cover6264 class CustomClickParser(click.ParamType):63 class CustomClickParser(_click.types.ParamType):64 name = "custom_parser"6566 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 cover7374 ParameterInfo()
27 unmodified lines
102 @app.command()103 def main(name: str = typer.Option(..., callback=name_callback)):104 pass # pragma: no cover105107 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 lines
125 assert "info name is: main" in result.stdout126 assert "value is: Camila" in result.stdout127128129@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)136def test_bad_parameter_callback(137 param_hint: str | None, option_decls: tuple[str, ...], expected_message: str138) -> None:139 app = typer.Typer()140141 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)144145 @app.command()146 def main(name: str = typer.Option(..., *option_decls, callback=my_bad)) -> None:147 typer.echo(name) # pragma: no cover148149 result = runner.invoke(app, ["--name", "Camila"])150 assert result.exit_code == 2151 assert expected_message in result.stderr152 assert "custom validation failed" in result.stderr153154155def test_bad_parameter_main() -> None:156 app = typer.Typer()157158 @app.command()159 def main() -> None:160 raise typer.BadParameter("custom validation failed")161162 result = runner.invoke(app, [])163 assert result.exit_code == 2164 assert "Invalid value: custom validation failed" in result.stderr165166167@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)177def test_missing_parameter_msg(kw: dict[str, object], msg: str) -> None:178 app = typer.Typer(rich_markup_mode=None)179180 @app.command()181 def main() -> None:182 raise typer._click.exceptions.MissingParameter(**kw)183184 result = runner.invoke(app, [])185 assert result.exit_code == 2186 assert msg in result.stderr187188189def 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 )194195 app = typer.Typer(rich_markup_mode=None)196197 @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 cover205206 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"215216217def 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)220221 app = typer.Typer()222223 @app.command()224 def main(mode: str = typer.Option(..., "--mode", callback=my_cb)) -> None:225 typer.echo(mode) # pragma: no cover226227 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"230231232def test_click_exception_show_default_file() -> None:233 app = typer.Typer(rich_markup_mode=None)234235 @app.command()236 def main() -> None:237 raise typer._click.ClickException("custom click failure")238239 result = runner.invoke(app, [])240 assert result.exit_code == 1241 assert "custom click" in result.stderr242 assert "failure" in result.stderr243244245def test_no_args_is_help_show() -> None:246 app = typer.Typer(rich_markup_mode=None)247248 @app.callback(invoke_without_command=True, no_args_is_help=True)249 def main() -> None:250 return None # pragma: no cover251252 result = runner.invoke(app, [])253 assert result.exit_code == 2254 assert "Usage:" in result.stderr255 assert "Show this message and exit." in result.stderr256257258def test_callback_3_untyped_parameters():259 app = typer.Typer()260261 def name_callback(ctx, param, value):
34 unmodified lines
296 result = runner.invoke(app, [])297 assert "Hello World" in result.stdout298299300def test_multiple_bool_flags() -> None:301 app = typer.Typer()302303 @app.command()304 def main(choices: list[bool] = typer.Option([], "--accept/--reject")) -> None:305 print(choices)306307 result = runner.invoke(app, ["--accept", "--reject", "--accept"])308 assert result.exit_code == 0309 assert "[True, False, True]" in result.stdout310311312def test_empty_list_default_generator():313 def empty_list() -> list[str]:314 return []315
89 unmodified lines
405 @app.command()406 def main(name: str = typer.Option(..., autocompletion=name_callback)):407 pass # pragma: no cover408269 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"412413
28 unmodified lines
442 result = runner.invoke(app, ["main", "-h"])443 assert "Show this message and exit." in result.stdout444445306def test_split_opt():307 prefix, opt = _split_opt("--verbose")308 assert prefix == "--"309 assert opt == "verbose"310311 prefix, opt = _split_opt("//verbose")312 assert prefix == "//"313 assert opt == "verbose"314315 prefix, opt = _split_opt("-verbose")316 assert prefix == "-"317 assert opt == "verbose"318319 prefix, opt = _split_opt("verbose")320 assert prefix == ""321 assert opt == "verbose"322323446def test_options_metadata_typer_default():447 app = typer.Typer(options_metavar="[options]")448449 @app.command()
12 unmodified lines
added:tests/test_progress_bar.py+397 added
1"""2Tests for the Progress bar functionality.3Created after vendoring Click to ensure test coverage is back up to 100%.4"""56import io7import shutil89import pytest10import typer11from typer import progressbar12from typer._click import _termui_impl13from typer.testing import CliRunner1415runner = CliRunner()161718def _fake_clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:19 clock = [0.0]20 monkeypatch.setattr(_termui_impl.time, "time", lambda: clock[0])21 return clock222324def _pbar(**kw):25 return progressbar(file=kw.pop("file", io.StringIO()), **kw)262728@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)36def test_progressbar(iterable, length, hidden, label, expected_count):37 app = typer.Typer()3839 @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}")5051 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)555657@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)84def 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)8990 app = typer.Typer()9192 @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())106107 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.stdout113114115def 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.0119120 app = typer.Typer()121122 @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())139140 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.stdout144145146def test_progressbar_autowidth(monkeypatch):147 monkeypatch.setattr(_termui_impl, "isatty", lambda f: True)148 call = [0]149 real_get_terminal_size = shutil.get_terminal_size150151 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})()158159 monkeypatch.setattr(shutil, "get_terminal_size", fake_get_terminal_size)160161 state: dict[str, object] = {}162163 app = typer.Typer()164165 @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")175176 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 out183184185def 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)189190 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)197198199def test_progress_bar_time(monkeypatch):200 clock = _fake_clock(monkeypatch)201 state: dict[str, object] = {}202 clock[0] = 1_000.0203204 app = typer.Typer()205206 @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")224225 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]234235236def test_progress_bar_time_zero_steps(monkeypatch):237 clock = _fake_clock(monkeypatch)238 state: dict[str, object] = {}239 clock[0] = 2_000.0240241 app = typer.Typer()242243 @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")252253 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)258259260def test_progress_bar_eta(monkeypatch):261 state: dict[str, object] = {}262263 app = typer.Typer()264265 @app.command()266 def main():267 state["eta0"] = _pbar(iterable=[1, 2], length=None).eta268269 done = _pbar(iterable=None, length=5)270 done.pos, done.finished = 2, True271 state["eta_done"] = done.eta272273 fresh = _pbar(iterable=None, length=5)274 state["eta_known_fresh"] = fresh.eta_known275 state["fmt_eta_fresh"] = fresh.format_eta()276277 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_iteration285286 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 )303304 state["cases"] = cases_out305306 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")315316 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]323324 (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_000327328 assert state["fmt_before_finish"] != ""329 assert state["fmt_after_finish"] == ""330331332@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)340def 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.0352353 state: dict[str, object] = {}354355 class _IterableWithoutLength:356 def __iter__(self):357 return iter((1, 2, 3))358359 app = typer.Typer()360361 @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 None371372 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")391392 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_bar
added:tests/test_termui.py+458 added
1"""2Tests for the termui, echo, and CliRunner isolation functionality.3Created after vendoring Click to ensure test coverage is back up to 100%.4"""56import io7import os8from contextlib import contextmanager9from typing import Literal1011import pytest12import typer13from typer._click import _termui_impl, termui14from typer.testing import CliRunner1516from tests.utils import needs_windows, skip_if_windows171819def test_raw_terminal(monkeypatch):20 runner = CliRunner()21 app = typer.Typer()22 state = {"entered": 0, "exited": 0}2324 @contextmanager25 def fake_raw_terminal():26 state["entered"] += 127 try:28 yield 4229 finally:30 state["exited"] += 13132 monkeypatch.setattr(_termui_impl, "raw_terminal", fake_raw_terminal)3334 @app.command()35 def main():36 with termui.raw_terminal() as fd:37 typer.echo(f"fd={fd}")3839 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"] == 1444546def test_getchar(monkeypatch):47 # Cached path: call the existing _getchar directly.48 cached_state = {"echo": None}4950 def cached_getchar(echo: bool) -> str:51 cached_state["echo"] = echo52 return "x"5354 monkeypatch.setattr(termui, "_getchar", cached_getchar)55 assert termui.getchar(echo=True) == "x"56 assert cached_state["echo"] is True5758 # Lazy-load path: _getchar is None, so import/cache _termui_impl.getchar.59 lazy_state = {"calls": 0}6061 def lazy_getchar(echo: bool) -> str:62 lazy_state["calls"] += 163 return "y" if not echo else "z"6465 monkeypatch.setattr(termui, "_getchar", None)66 monkeypatch.setattr(_termui_impl, "getchar", lazy_getchar)6768 assert termui.getchar(echo=False) == "y"69 assert termui._getchar is lazy_getchar70 assert termui.getchar(echo=True) == "z"71 assert lazy_state["calls"] == 2727374def test_clirunner_getchar(monkeypatch) -> None:75 runner = CliRunner()76 app = typer.Typer()7778 @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}")8384 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"]888990def 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")9596 @app.command()97 def main() -> None:98 typer.echo(f"inside={os.environ.get(env_key)}")99100 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"104105106@pytest.mark.parametrize(107 ("runner_exc", "invoke_exc"),108 [109 (False, None),110 (True, False),111 ],112)113def 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()118119 @app.command()120 def main() -> None:121 raise RuntimeError("boom")122123 with pytest.raises(RuntimeError, match="boom"):124 runner.invoke(app, [], catch_exceptions=invoke_exc)125126127@pytest.mark.parametrize(128 ("exit_value", "expected_exit_code", "expected_stdout"),129 [130 (None, 0, ""),131 ("bad-exit", 1, "bad-exit\n"),132 ],133)134def 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()141142 @app.command()143 def main() -> None:144 raise SystemExit(exit_value)145146 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 None153154155@needs_windows156def 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 == -1161162163@needs_windows164def 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"169170 seq_null = iter(["\x00", "K"])171 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_null))172 assert _termui_impl.getchar(echo=False) == "\x00K"173174 seq_e0 = iter(["\xe0", "H"])175 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: next(seq_e0))176 assert _termui_impl.getchar(echo=False) == "\xe0H"177178 seq_echo = iter(["\x00", "M"])179 monkeypatch.setattr(_termui_impl.msvcrt, "getwche", lambda: next(seq_echo))180 assert _termui_impl.getchar(echo=True) == "\x00M"181182 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"185186 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x03")187 with pytest.raises(KeyboardInterrupt):188 _termui_impl.getchar(echo=False)189190 monkeypatch.setattr(_termui_impl.msvcrt, "getwch", lambda: "\x1a")191 with pytest.raises(EOFError):192 _termui_impl.getchar(echo=False)193194195@skip_if_windows196@pytest.mark.parametrize("use_stdin_tty", [True, False])197def test_termui_impl_posix_raw_terminal(monkeypatch, use_stdin_tty: bool):198 state: dict[str, object] = {}199 flushed: list[None] = []200 fake_tty = None201202 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 )217218 class FakeTTY:219 def __init__(self) -> None:220 self.closed = False221222 def fileno(self) -> int:223 return expected_fd224225 def close(self) -> None:226 self.closed = True227228 fake_tty = FakeTTY()229 real_open = open230231 def fake_open(path, *args, **kwargs):232 if path == "/dev/tty":233 return fake_tty234 return real_open(path, *args, **kwargs) # pragma: no cover235236 monkeypatch.setattr("builtins.open", fake_open)237238 def tcgetattr(fd: int) -> str:239 state["tcgetattr_fd"] = fd240 return old_termios241242 def setraw(fd: int) -> None:243 state["setraw_fd"] = fd244245 def tcsetattr(fd: int, when: int, old: str) -> None:246 state["tcsetattr"] = (fd, when, old)247248 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 )254255 with _termui_impl.raw_terminal() as fd:256 assert fd == expected_fd257258 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 True268269270@skip_if_windows271def test_termui_impl_posix_getchar(monkeypatch):272 @contextmanager273 def fake_raw():274 yield 7275276 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))282283 assert _termui_impl.getchar(echo=True) == "q"284 assert written == ["q"]285286287@skip_if_windows288def test_termui_impl_posix_getchar_eof(monkeypatch):289 @contextmanager290 def fake_raw():291 yield 5292293 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)297298 with pytest.raises(EOFError):299 _termui_impl.getchar(echo=False)300301302def test_prompt():303 runner = CliRunner()304 app = typer.Typer()305 fake_file = io.StringIO("data")306 fake_file.name = "demo.txt"307308 @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 )325326 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.stdout334335336def test_hidden_prompt_func(monkeypatch):337 monkeypatch.setattr("getpass.getpass", lambda prompt: "secret")338 assert termui.hidden_prompt_func("Password: ") == "secret"339340341def test_echo_stdout_missing(monkeypatch: pytest.MonkeyPatch) -> None:342 monkeypatch.setattr("sys.stdout", None)343 typer.echo("ignored")344345346def test_echo_stringifies() -> None:347 stream = io.StringIO()348 typer.echo(123, file=stream, nl=False)349 assert stream.getvalue() == "123"350351352def 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"357358359def test_echo_empty_output() -> None:360 class FlushTrackingTextStream(io.StringIO):361 def __init__(self) -> None:362 super().__init__()363 self.flush_count = 0364365 def flush(self) -> None:366 self.flush_count += 1367 super().flush()368369 def write(self, s: str) -> int:370 raise AssertionError("Empty output") # pragma: no cover371372 stream = FlushTrackingTextStream()373 typer.echo("", file=stream, nl=False)374 assert stream.flush_count == 1375376377@needs_windows378def test_echo_windows_color_none(379 monkeypatch: pytest.MonkeyPatch,380) -> None:381 class TtyStream(io.StringIO):382 def isatty(self) -> bool:383 return True384385 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"389390391@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)404def test_style(flag, true_code, false_code):405 runner = CliRunner()406 app = typer.Typer()407408 @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)413414 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_line421422 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_line426427428def test_style_color():429 fg_int = typer.style("x", fg=123)430 assert "\x1b[38;5;123m" in fg_int431432 bg_list = typer.style("x", bg=[1, 2, 3])433 assert "\x1b[48;2;1;2;3m" in bg_list434435 with pytest.raises(TypeError, match="Unknown color"):436 typer.style("x", fg="not-a-color")437438 with pytest.raises(TypeError, match="Unknown color"):439 typer.style("x", bg="not-a-color")440441442def test_termui_launch(monkeypatch):443 captured = {}444445 def fake_open_url(url, wait=False, locate=False):446 captured["url"] = url447 captured["wait"] = wait448 captured["locate"] = locate449 return 7450451 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
1import os2from enum import Enum3from pathlib import Path4from typing import Any55import click6import pytest7import typer8from typer import _click, models9from typer.testing import CliRunner1011from tests.utils import needs_linux, needs_windows1213runner = CliRunner()141516def test_optional():
118 unmodified lines
135 result = runner.invoke(app, ["one", "two"])136 assert result.exit_code == 0137138139def test_tuple_wrong_arity():140 app = typer.Typer()141142 @app.command()143 def tuple_arity(value: tuple[str, str] = typer.Option(...)):144 print(value) # pragma: no cover145146 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.output149150151def test_custom_parse():152 app = typer.Typer()153154 @app.command()
5 unmodified lines
160 result = runner.invoke(app, ["0x56"])161 assert result.exit_code == 0162163164def test_custom_parse_value_error():165 app = typer.Typer()166167 @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 cover172173 result = runner.invoke(app, ["not-a-hex"])174 assert result.exit_code == 2175 assert "Invalid value" in result.output176177178def test_custom_click_type():150 class BaseNumberParamType(click.ParamType):179 class BaseNumberParamType(_click.types.ParamType):180 name = "base_integer"181182 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)189190 app = typer.Typer()
5 unmodified lines
196 assert hex_value == 0x56197198 result = runner.invoke(app, ["0x56"])199 assert result.exit_code == 0200201202def test_int_range_open_bound_clamp():203 app = typer.Typer()204205 @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)213214 result = runner.invoke(app, ["1"])215 assert result.exit_code == 0216 assert "2" in result.output217218219def test_bool_convert_invalid():220 app = typer.Typer()221222 @app.command()223 def main(value: bool):224 print(value) # pragma: no cover225226 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.output231232233@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)242def 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()250251 @app.command()252 def show(name: str = typer.Option(...)):253 print(name)254255 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"258259 monkeypatch.setattr(_click.types, "_get_argv_encoding", lambda: arg_enc)260 monkeypatch.setattr(_click.types.sys, "getfilesystemencoding", lambda: system_enc)261262 result = runner.invoke(app, [], default_map={"name": raw_value})263 assert result.exit_code == 0264 assert expected_output in result.output265266267@pytest.mark.parametrize("path_type", [str, bytes, Path])268def test_path_coerced(path_type) -> None:269 # Ensure coerce_path_result works correctly270 app = typer.Typer()271272 @app.command()273 def show(path: Any = typer.Option(..., path_type=path_type)):274 print(path)275276 result = runner.invoke(app, ["--path", "dir/my_awesome_file.txt"])277 assert result.exit_code == 0278 assert "my_awesome_file" in result.output279280281@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)290def 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()299300 @app.command()301 def show(path: Path = typer.Option(..., **option_kwargs)):302 print(path) # pragma: no cover303304 if deny_mode is not None:305 original_access = os.access306307 def fake_access(path: str, mode: int) -> bool:308 if mode == deny_mode:309 return False310 return original_access(path, mode) # pragma: no cover311312 monkeypatch.setattr(models.os, "access", fake_access)313314 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)])320321 assert result.exit_code != 0322 assert expected_error in result.output323324325def test_convert_type():326 from typer._click.types import convert_type327328 # 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.STRING332333 # 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 ]340341 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 ]347348 # numbers349 assert convert_type(int) is _click.types.INT350 assert convert_type(float) is _click.types.FLOAT351 assert convert_type(bool) is _click.types.BOOL352353 param_type = _click.types.IntRange(min=0, max=10)354 assert convert_type(param_type) is param_type355356 guessed_int = convert_type(None, default=42)357 assert guessed_int is _click.types.INT358359 # custom type360 class CustomType:361 pass362363 guessed_unknown = convert_type(None, default=CustomType())364 assert guessed_unknown is _click.types.STRING365366 func_type = convert_type(CustomType)367 assert isinstance(func_type, _click.types.FuncParamType)368 assert func_type.name == "CustomType"369370371@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)379def 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 locale388389 monkeypatch.setattr(locale, "getpreferredencoding", lambda: "latin-1")390 else:391392 class FakeStdin:393 def __init__(self, encoding: str | None) -> None:394 self.encoding = encoding395396 monkeypatch.setattr(sys, "stdin", FakeStdin(stdin_encoding))397 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: filesystem_encoding)398399 converted = _click.types.STRING.convert(b"\xff", None, None)400 assert converted == "ÿ"
added:tests/test_types_file.py+395 added
1import subprocess2import sys3from io import BytesIO, StringIO, TextIOWrapper4from pathlib import Path56import pytest7import typer8from typer._click._compat import get_best_encoding, should_strip_ansi9from typer._click.testing import make_input_stream10from typer._click.utils import PacifyFlushWrapper11from typer.testing import CliRunner1213from tests.utils import needs_linux, needs_windows1415app = typer.Typer()161718@app.command()19def read_text(file_in: typer.FileText = typer.Option(..., lazy=True)):20 data = file_in.read()21 typer.echo(f"text-len={len(data)}")222324@app.command()25def 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")282930@app.command()31def 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")343536@app.command()37def 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()}")495051@app.command()52def write_binary(file_out: typer.FileBinaryWrite = typer.Option(...)):53 file_out.write(b"binary-written\n")545556@app.command()57def write_binary_stderr():58 stream = typer.get_binary_stream("stderr")59 stream.write(b"binary-stderr\n")60 stream.flush()616263@app.command()64def read_binary(file_in: typer.FileBinaryRead = typer.Option(...)):65 data = file_in.read()66 typer.echo(f"binary-len={len(data)}")676869runner = CliRunner()707172def 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.output767778def 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.output8485 # 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"9394 # 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.output109110 # 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.output115116117def 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"125126127def 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_stream131132 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.buffer135136137def 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"141142 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.output147148149def 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"161162163@pytest.mark.parametrize(164 ("errors_arg", "expected_errors"),165 [166 (None, "replace"),167 ("strict", "strict"),168 ],169)170def test_get_text_stream_errors(171 monkeypatch,172 errors_arg: str | None,173 expected_errors: str,174) -> None:175 class BinaryStdout(BytesIO):176 pass177178 binary_stdout = BinaryStdout()179 monkeypatch.setattr(sys, "stdout", binary_stdout)180181 text_stream = typer.get_text_stream("stdout", encoding=None, errors=errors_arg)182 text_stream.write("stream-text")183 text_stream.flush()184185 assert text_stream.errors == expected_errors186 assert text_stream.writable() is True187 assert binary_stdout.getvalue() == b"stream-text"188189190def test_get_best_encoding() -> None:191 """Test that ASCII is being transformed into UTF-8"""192193 class AsciiStream:194 encoding = "ascii"195196 class Utf8Stream:197 encoding = "utf-8"198199 class UnknownStream:200 encoding = "unknown"201202 assert get_best_encoding(AsciiStream()) == "utf-8"203 assert get_best_encoding(Utf8Stream()) == "utf-8"204 assert get_best_encoding(UnknownStream()) == "unknown"205206207def test_pacify_flush_wrapper() -> None:208 class Wrapped:209 def __init__(self) -> None:210 self.name = "wrapped-stream"211212 def flush(self) -> None:213 return None # pragma: no cover214215 wrapped = PacifyFlushWrapper(Wrapped())216 assert wrapped.name == "wrapped-stream"217218219def test_text_stream_isatty(monkeypatch) -> None:220 class BinaryStdout(BytesIO):221 def isatty(self) -> bool:222 return True223224 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 True228229230def test_text_stream_buffer_read1(monkeypatch) -> None:231 class BinaryStdinNoRead1:232 def __init__(self, data: bytes) -> None:233 self._data = data234 self._pos = 0235236 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 chunk242243 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"247248249def 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)254255 assert typer.get_binary_stream("stdin") is binary_stdin256 assert typer.get_binary_stream("stdout") is binary_stdout257258259def test_binary_stream_raises(monkeypatch) -> None:260 class TextOnlyStdin:261 def read(self, n: int = -1) -> str:262 return "hello"263264 monkeypatch.setattr(sys, "stdin", TextOnlyStdin())265 with pytest.raises(RuntimeError, match="Was not able to determine binary stream"):266 typer.get_binary_stream("stdin")267268269def test_stream_unknown() -> None:270 with pytest.raises(TypeError, match="Unknown standard stream 'Plumbus'"):271 typer.get_binary_stream("Plumbus") # type: ignore[arg-type]272273 with pytest.raises(TypeError, match="Unknown standard stream 'Fleeb'"):274 typer.get_text_stream("Fleeb") # type: ignore[arg-type]275276277def test_format_filename() -> None:278 filename = b"folder/subdir/demo.txt"279 assert typer.format_filename(filename, shorten=True) == "demo.txt"280281282def test_file_error(monkeypatch, tmp_path: Path) -> None:283 file_path = tmp_path / "cannot-open.txt"284285 def fake_open(path, *args, **kwargs):286 if Path(path) == file_path:287 raise OSError()288289 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.output295296297@needs_windows298def 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")303304 assert typer.get_app_dir("My App", roaming=True) == r"C:\Users\Tester\My App"305306307@needs_linux308def test_app_dir_force_posix(monkeypatch: pytest.MonkeyPatch) -> None:309 monkeypatch.setattr("os.path.expanduser", lambda _path: "/home/tester/.my-app")310311 assert typer.get_app_dir("My App", force_posix=True) == "/home/tester/.my-app"312313314def 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"319320 def read(self, n: int = -1) -> str:321 raise OSError("text stream is not readable directly")322323 class TextStdoutWithBinaryBuffer:324 def __init__(self) -> None:325 self.buffer = BytesIO()326 self.encoding = "latin-1"327328 def write(self, s: str) -> int:329 raise OSError("text stream is not writable directly")330331 stdin = TextStdinWithBinaryBuffer(b"hello")332 stdout = TextStdoutWithBinaryBuffer()333334 monkeypatch.setattr(sys, "stdin", stdin)335 monkeypatch.setattr(sys, "stdout", stdout)336337 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)339340 assert text_stdin.read() == "hello"341 text_stdout.write("ok")342 text_stdout.flush()343 assert stdout.buffer.getvalue() == b"ok"344345346def 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"353354355def test_text_stream_stdout_no_binary(356 monkeypatch,357) -> None:358 class TextStdoutNoBinaryFallback:359 encoding = "utf-8"360 errors = "strict"361362 def write(self, s: str) -> int:363 if isinstance(s, bytes):364 raise TypeError("bytes not supported")365 return len(s)366367 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 stdout371372373def test_jupyter_wrapped_stream(monkeypatch) -> None:374 class JupyterLikeStdout(BytesIO):375 __module__ = "ipykernel.iostream"376377 def isatty(self) -> bool:378 return False379380 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 False384385386def test_should_strip_ansi(monkeypatch) -> None:387 class NonTtyStdin(BytesIO):388 def isatty(self) -> bool:389 return False390391 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 True
modified:tests/test_types.py+92 added-5 removed
1from enum import Enum23import pytest4import typer5from typer import _click6from typer.testing import CliRunner78app = typer.Typer(context_settings={"token_normalize_func": str.lower})9
3 unmodified lines
13 morty = "Morty"141516@app.command()15def hello(name: User = User.rick) -> None:17def hello_option(name: User = User.rick) -> None:18 print(f"Hello {name.value}!")192021@app.command()22def hello_argument(name: User) -> None:23 print(f"Hello {name.value}!")242526@app.command()27def hello_no_choices(28 name: User = typer.Option(..., "--name", show_choices=False),29):30 print(f"Hello {name.value}!")313233@app.command()34def hello_all(names: list[str] = typer.Argument(["World"], envvar="NAMES")) -> None:35 for name in names:36 print(f"Hello {name}!")373839@app.command()40def split_variadic_and_pair(items: list[str], pair: tuple[str, str]) -> None:41 print(f"items={items}")42 print(f"pair={pair}")434445runner = CliRunner()464748def 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.output5428 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.output5832 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.output6263 result = runner.invoke(app, ["hello-no-choices", "--name", "RICK"])64 assert result.exit_code == 065 assert "Hello Rick!" in result.output6667 result = runner.invoke(app, ["hello-argument", "RICK"])68 assert result.exit_code == 069 assert "Hello Rick!" in result.output707172def 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([")777879def test_enum_choice_help() -> None:80 result = runner.invoke(app, ["hello-argument", "--help"])81 assert result.exit_code == 082 assert "{rick|morty}" in result.output8384 result = runner.invoke(app, ["hello-option", "--help"])85 assert result.exit_code == 086 assert "[rick|morty]" in result.output8788 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.output929394def 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.output101102103def 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.output110111112def 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.output117118119def 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"""2Tests for the Windows console functionality.3Created after vendoring Click to ensure test coverage is back up to 100%.4"""56import ctypes7import io8import sys910import pytest11import typer12from typer.testing import CliRunner1314from .utils import needs_windows1516pytestmark = needs_windows171819if sys.platform == "win32":20 from typer._click import _compat, _winconsole212223def _identity_buffer(obj, writable=False): # noqa: ARG00124 return obj252627def _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 None3637 return patched_windows_stream383940def _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 14748 return fake_write_console495051def test_winconsole_stdin(monkeypatch):52 runner = CliRunner()53 app = typer.Typer()5455 @app.command()56 def read_name(config: typer.FileText = typer.Option(...)) -> None:57 name = config.readline().strip()58 typer.echo(f"Hello {name}")5960 utf16_data = bytearray("Rick\r\n".encode("utf-16-le"))61 state = {"pos": 0, "read_calls": 0}6263 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 17273 return 1 # pragma: no cover7475 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 )8384 result = runner.invoke(app, ["--config", "-"])85 assert result.exit_code == 0, result.output86 assert "Hello Rick" in result.stdout87 assert state["read_calls"] > 0888990def test_winconsole_stdout(monkeypatch):91 runner = CliRunner()92 app = typer.Typer()93 state = {"write_calls": 0, "written": bytearray()}9495 @app.command()96 def write_message(out: typer.FileTextWrite = typer.Option(...)) -> None:97 out.write("Hello Summer\n")9899 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 )107108 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 decoded114115116def test_winconsole_stderr(monkeypatch):117 runner = CliRunner()118 app = typer.Typer()119 state = {"write_calls": 0, "written": bytearray(), "stderr_wrap_calls": 0}120121 @app.command()122 def main() -> None:123 typer.echo("Ran out of adventure time!", err=True)124125 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 )133134 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 decoded140141142@pytest.mark.parametrize(143 ("writable", "source", "expected_flags"),144 [145 (True, bytearray(b"python"), 1), # PyBUF_WRITABLE146 (False, b"python", 0), # PyBUF_SIMPLE147 ],148)149def 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))156157 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)162163 def fake_buffer_release(buf_ref): # noqa: ARG001164 state["released"] += 1165166 monkeypatch.setattr(_winconsole, "PyObject_GetBuffer", fake_object_get_buffer)167 monkeypatch.setattr(_winconsole, "PyBuffer_Release", fake_buffer_release)168169 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"] == 1179180181def test_isatty():182 assert _winconsole._WindowsConsoleRawIOBase(None).isatty() is True183 assert _winconsole._WindowsConsoleReader(0).isatty() is True184 assert _winconsole._WindowsConsoleReader(1).isatty() is True185186187def test_console_stream():188 class NamedBytesIO(io.BytesIO):189 name = "fake-buffer"190191 def isatty(self):192 return False193194 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)201202 # test writelines203 stream.writelines(["hello", " ", "world"])204 stream._text_stream.flush()205 assert stream._text_stream.buffer.getvalue().decode("utf-8") == "hello world"206207 # Cover bytes write path.208 assert stream.write(b"!") == 1209 assert stream.buffer.getvalue().endswith(b"!")210211212@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)220def test_error_message(error, msg):221 writer = _winconsole._WindowsConsoleWriter222 assert writer._get_error_message(error) == msg223224225def test_is_console():226 assert _winconsole._is_console(object()) is False227228229def 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())232233 class FakeStream:234 def __init__(self, fd, buffer=None):235 self._fd = fd236 self.buffer = buffer237238 def fileno(self):239 return self._fd240241 wrapped = {"called": False, "buffer": None}242243 def fake_factory(buffer):244 wrapped["called"] = True245 wrapped["buffer"] = buffer246 return "wrapped", buffer247248 monkeypatch.setattr(_winconsole, "_stream_factories", {7: fake_factory})249250 # 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 None253254 # Factory exists, but stream has no usable .buffer.255 assert get_stream(FakeStream(7, None), "utf-16-le", "strict") is None256257 # 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_buffer263264265def test_windows_console_reader(monkeypatch):266 reader = _winconsole._WindowsConsoleReader(42)267268 # Empty input buffer returns early269 assert reader.readinto(bytearray()) == 0270271 # Require an even number of bytes272 with pytest.raises(ValueError):273 reader.readinto(bytearray(3))274275 def writable_buffer(obj, writable=False): # noqa: ARG001276 return (ctypes.c_char * len(obj)).from_buffer(obj)277278 monkeypatch.setattr(_winconsole, "get_buffer", writable_buffer)279280 def patch_console(read_console, error):281 monkeypatch.setattr(_winconsole, "ReadConsoleW", read_console)282 monkeypatch.setattr(_winconsole, "GetLastError", lambda: error)283284 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 rv292293 return read_console294295 # 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)) == 4298299 # 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)) == 0305306 # An aborted read should sleep briefly while waiting for KeyboardInterrupt307 sleep_state = {"calls": 0}308309 def fake_sleep(seconds):310 sleep_state["calls"] += 1311 assert seconds == 0.1312313 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"] == 1322323 # 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 lines
89needs_linux = pytest.mark.skipif(10 not sys.platform.startswith("linux"), reason="Test requires Linux"11)12needs_macos = pytest.mark.skipif(13 not sys.platform.startswith("darwin"), reason="Test requires macOS"14)15needs_windows = pytest.mark.skipif(16 not sys.platform.startswith("win"), reason="Test requires Windows"17)18skip_if_windows = pytest.mark.skipif(19 sys.platform == "win32",20 reason="Test should not be run on Windows",21)2223needs_rich = pytest.mark.skipif(not HAS_RICH, reason="Test requires Rich")2425shell = _get_shell_name()
27 unmodified lines
added:typer/_click/__init__.py+11 added
1"""2Code taken and adapted from Click: https://github.com/pallets/click/releases/tag/8.3.13"""45from .core import Command as Command6from .core import Context as Context7from .core import Parameter as Parameter8from .exceptions import ClickException as ClickException9from .formatting import HelpFormatter as HelpFormatter10from .termui import launch as launch11from .utils import echo as echo
added:typer/_click/_compat.py+569 added
1import codecs2import io3import os4import re5import sys6from collections.abc import Callable, Mapping, MutableMapping7from types import TracebackType8from typing import (9 IO,10 Any,11 BinaryIO,12 TextIO,13 cast,14)15from weakref import WeakKeyDictionary1617CYGWIN = sys.platform.startswith("cygwin")18WIN = sys.platform.startswith("win")19auto_wrap_for_ansi: Callable[[TextIO], TextIO] | None = None20_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")212223def _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 )363738def 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 False444546def 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 rv525354class _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)6465 def __del__(self) -> None:66 try:67 self.detach()68 except Exception: # pragma: no cover69 pass7071 def isatty(self) -> bool:72 # https://bitbucket.org/pypy/pypy/issue/180373 return self._stream.isatty()747576class _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 """8182 def __init__(83 self,84 stream: BinaryIO,85 ):86 self._stream = stream8788 def __getattr__(self, name: str) -> Any:89 return getattr(self._stream, name)9091 def read1(self, size: int) -> bytes:92 f = getattr(self._stream, "read1", None)9394 if f is not None:95 return cast(bytes, f(size))9697 return self._stream.read(size)9899 def readable(self) -> bool:100 return True101102 def writable(self) -> bool:103 return True104105 def seekable(self) -> bool:106 x = getattr(self._stream, "seekable", None)107 if x is not None:108 return cast(bool, x())109 return False110111112def _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.119120121def _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 True132133134def _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)141142 buf = getattr(stream, "buffer", None)143144 # 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)148149 return None150151152def _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)159160 buf = getattr(stream, "buffer", None)161162 # 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)166167 return None168169170def _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")177178179def _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)186187188def _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)197198199def _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_stream216217 # Otherwise, get the underlying binary reader.218 possible_binary_reader = find_binary(text_stream)219220 # 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_stream224225 binary_reader = possible_binary_reader226227 # Default errors to replace instead of strict in order to get228 # something that works.229 if errors is None:230 errors = "replace"231232 # 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 )239240241def _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 )253254255def _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 )267268269def 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 reader274275276def 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 writer281282283def 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 writer288289290def 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)295296297def 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)302303304def 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)309310311def _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)320321 return open(file, mode, encoding=encoding, errors=errors)322323324def 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)333334 # 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), False343344 # Non-atomic writes directly go out through the regular open functions.345 if not atomic:346 return _wrap_io_open(filename, mode, encoding, errors), True347348 # 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.")360361 # 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 random367368 try:369 perm: int | None = os.stat(filename).st_mode370 except OSError: # pragma: no cover371 perm = None372373 flags = os.O_RDWR | os.O_CREAT | os.O_EXCL374375 if binary:376 flags |= getattr(os, "O_BINARY", 0)377378 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 raise395396 if perm is not None:397 os.chmod(tmp_filename, perm) # in case perm includes bits in umask398399 f = _wrap_io_open(fd, mode, encoding, errors)400 af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))401 return cast(IO[Any], af), True402403404class _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 = False410411 @property412 def name(self) -> str:413 return self._real_filename414415 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 = True421422 def __getattr__(self, name: str) -> Any:423 return getattr(self._f, name)424425 def __enter__(self) -> "_AtomicFile":426 return self427428 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)435436 def __repr__(self) -> str:437 return repr(self._f)438439440def strip_ansi(value: str) -> str:441 return _ansi_re.sub("", value)442443444def _is_jupyter_kernel_output(stream: IO[Any]) -> bool:445 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):446 stream = stream._stream447448 return stream.__class__.__module__.startswith("ipykernel.")449450451def 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 color457458459# 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 Linux462if sys.platform.startswith("win") and WIN:463 from ._winconsole import _get_windows_console_stream464465 def _get_argv_encoding() -> str:466 import locale467468 return locale.getpreferredencoding()469470 _ansi_stream_wrappers: MutableMapping[TextIO, TextIO] = WeakKeyDictionary()471472 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 = None480481 if cached is not None:482 return cached483484 import colorama485486 strip = should_strip_ansi(stream, color)487 ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)488 rv = cast(TextIO, ansi_wrapper.stream)489 _write = rv.write490491 def _safe_write(s: str) -> int:492 try:493 return _write(s)494 except BaseException: # pragma: no cover495 ansi_wrapper.reset_all()496 raise497498 rv.write = _safe_write # type: ignore[method-assign] # ty: ignore[invalid-assignment]499500 try:501 _ansi_stream_wrappers[stream] = rv502 except Exception: # pragma: no cover503 pass504505 return rv506507else:508509 def _get_argv_encoding() -> str:510 return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()511512 def _get_windows_console_stream(513 f: TextIO, encoding: str | None, errors: str | None514 ) -> TextIO | None:515 return None516517518def term_len(x: str) -> int:519 return len(strip_ansi(x))520521522def isatty(stream: IO[Any]) -> bool:523 try:524 return stream.isatty()525 except Exception: # pragma: no cover526 return False527528529def _make_cached_stream_func(530 src_func: Callable[[], TextIO],531 wrapper_func: Callable[[], TextIO],532) -> Callable[[], TextIO]:533 cache: MutableMapping[TextIO, TextIO] = WeakKeyDictionary()534535 def func() -> TextIO:536 stream = src_func()537538 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 rv550551 return func552553554_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)557558559binary_streams: Mapping[str, Callable[[], BinaryIO]] = {560 "stdin": get_binary_stdin,561 "stdout": get_binary_stdout,562 "stderr": get_binary_stderr,563}564565text_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"""2To keep the import times down, some infrequently used termui functionality3is placed here and only imported as needed.4"""56import contextlib7import math8import os9import sys10import time11from collections.abc import Callable, Iterable, Iterator12from io import StringIO13from types import TracebackType14from typing import Generic, TextIO, TypeVar, cast1516from ._compat import (17 CYGWIN,18 WIN,19 _default_text_stdout,20 get_best_encoding,21 isatty,22 term_len,23)24from .utils import echo2526V = TypeVar("V")2728if os.name == "nt":29 BEFORE_BAR = "\r"30 AFTER_BAR = "\n"31else:32 BEFORE_BAR = "\r\033[?25l"33 AFTER_BAR = "\033[?25h\n"343536class 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 ""6667 if file is None:68 file = _default_text_stdout()6970 # 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()7475 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 == 08182 if length is None:83 from operator import length_hint8485 length = length_hint(iterable, -1)8687 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 = None107108 def __enter__(self) -> "ProgressBar[V]":109 self.entered = True110 self.render_progress()111 return self112113 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()120121 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()126127 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))134135 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()140141 @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)146147 @property148 def time_per_iteration(self) -> float:149 if not self.avg:150 return 0.0151 return sum(self.avg) / float(len(self.avg))152153 @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.0158159 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 ""173174 def format_pos(self) -> str:175 pos = str(self.pos)176 if self.length is not None:177 pos += f"/{self.length}"178 return pos179180 def format_pct(self) -> str:181 return f"{int(self.pct * 100): 4}%"[1:]182183 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 bar201202 def format_progress_line(self) -> str:203 show_percent = self.show_percent204205 info_bits = []206 if self.length is not None and show_percent is None:207 show_percent = not self.show_pos208209 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)219220 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()228229 def render_progress(self) -> None:230 if self.hidden:231 return232233 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 return239240 buf = []241 # Update width in case the terminal has been resized242 if self.autowidth:243 import shutil244245 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_width254255 clear_width = self.width256 if self.max_width is not None:257 clear_width = self.max_width258259 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_len264265 buf.append(line)266 buf.append(" " * (clear_width - line_len))267 line = "".join(buf)268 # Render the line only if it changed.269270 if line != self._last_line:271 self._last_line = line272 echo(line, file=self.file, color=self.color, nl=False)273 self.file.flush()274275 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 = True279280 if (time.time() - self.last_eta) < 1.0:281 return282283 self.last_eta = time.time()284285 # 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.start292293 self.avg = self.avg[-6:] + [step]294295 self.eta_known = self.length is not None296297 def update(self, n_steps: int) -> None:298 """Update the progress bar by advancing a specified number of steps."""299 self._completed_intervals += n_steps300301 if self._completed_intervals >= self.update_min_steps:302 self.make_step(self._completed_intervals)303 self.render_progress()304 self._completed_intervals = 0305306 def finish(self) -> None:307 self.eta_known = False308 self.current_item = None309 self.finished = True310311 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.")325326 if not self._is_atty:327 yield from self.iter328 else:329 for rv in self.iter:330 self.current_item = rv331332 # 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()337338 yield rv339 self.update(1)340341 self.finish()342 self.render_progress()343344345def open_url(url: str, wait: bool = False, locate: bool = False) -> int:346 import subprocess347348 def _unquote_file(url: str) -> str:349 from urllib.parse import unquote350351 if url.startswith("file://"):352 url = unquote(url[7:])353354 return url355356 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 127397398 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 webbrowser411412 webbrowser.open(url)413 return 0414 return 1415416417def _translate_ch_to_exc(ch: str) -> None:418 if ch == "\x03":419 raise KeyboardInterrupt()420421 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D422 raise EOFError()423424 if ch == "\x1a" and WIN: # Windows, Ctrl+Z425 raise EOFError()426427 return None428429430if sys.platform == "win32":431 import msvcrt432433 @contextlib.contextmanager434 def raw_terminal() -> Iterator[int]:435 yield -1436437 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`.467468 if echo:469 func = cast(Callable[[], str], msvcrt.getwche)470 else:471 func = cast(Callable[[], str], msvcrt.getwch)472473 rv = func()474475 if rv in ("\x00", "\xe0"):476 # \x00 and \xe0 are control characters that indicate special key,477 # see above.478 rv += func()479480 _translate_ch_to_exc(rv)481 return rv482483else:484 import termios485 import tty486487 @contextlib.contextmanager488 def raw_terminal() -> Iterator[int]:489 f: TextIO | None490 fd: int491492 if not isatty(sys.stdin):493 f = open("/dev/tty")494 fd = f.fileno()495 else:496 fd = sys.stdin.fileno()497 f = None498499 try:500 old_settings = termios.tcgetattr(fd)501502 try:503 tty.setraw(fd)504 yield fd505 finally:506 termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)507 sys.stdout.flush()508509 if f is not None:510 f.close()511 except termios.error: # pragma: no cover512 pass513514 def getchar(echo: bool) -> str:515 with raw_terminal() as fd:516 ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")517518 if echo and isatty(sys.stdout): # pragma: no cover519 sys.stdout.write(ch)520521 _translate_ch_to_exc(ch)522 return ch
added:typer/_click/_textwrap.py+46 added
1import textwrap2from collections.abc import Iterator3from contextlib import contextmanager456class 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)1516 last = reversed_chunks[-1]17 cut = last[:space_left]18 res = last[space_left:]19 cur_line.append(cut)20 reversed_chunks[-1] = res2122 @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 += indent2829 try:30 yield31 finally:32 self.initial_indent = old_initial_indent33 self.subsequent_indent = old_subsequent_indent3435 def indent_only(self, text: str) -> str:36 rv = []3738 for idx, line in enumerate(text.splitlines()):39 indent = self.initial_indent4041 if idx > 0:42 indent = self.subsequent_indent4344 rv.append(f"{indent}{line}")4546 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.9import io10import sys11import time12from collections.abc import Callable, Iterable, Mapping13from 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)26from ctypes.wintypes import DWORD, HANDLE, LPCWSTR, LPWSTR27from typing import (28 TYPE_CHECKING,29 Any,30 AnyStr,31 BinaryIO,32 Literal,33 TextIO,34 cast,35)3637from ._compat import _NonClosingTextIOWrapper3839assert sys.platform == "win32"40import msvcrt # noqa: E40241from ctypes import WINFUNCTYPE, windll # noqa: E4024243c_ssize_p = POINTER(c_ssize_t)4445kernel32 = windll.kernel3246GetStdHandle = kernel32.GetStdHandle47ReadConsoleW = kernel32.ReadConsoleW48WriteConsoleW = kernel32.WriteConsoleW49GetConsoleMode = kernel32.GetConsoleMode50GetLastError = kernel32.GetLastError51GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))52CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(53 ("CommandLineToArgvW", windll.shell32)54)55LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))5657STDIN_HANDLE = GetStdHandle(-10)58STDOUT_HANDLE = GetStdHandle(-11)59STDERR_HANDLE = GetStdHandle(-12)6061PyBUF_SIMPLE = 062PyBUF_WRITABLE = 16364ERROR_SUCCESS = 065ERROR_NOT_ENOUGH_MEMORY = 866ERROR_OPERATION_ABORTED = 9956768STDIN_FILENO = 069STDOUT_FILENO = 170STDERR_FILENO = 27172EOF = b"\x1a"73MAX_BYTES_WRITTEN = 327677475if 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 Buffer8283try:84 from ctypes import pythonapi85except ImportError: # pragma: no cover86 # On PyPy we cannot get buffers so our ability to operate here is87 # severely limited.88 get_buffer = None89else:9091 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 ]105106 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer107 PyBuffer_Release = pythonapi.PyBuffer_Release108109 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)113114 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))120121122class _WindowsConsoleRawIOBase(io.RawIOBase):123 def __init__(self, handle: int | None) -> None:124 self.handle = handle125126 def isatty(self) -> Literal[True]:127 super().isatty()128 return True129130131class _WindowsConsoleReader(_WindowsConsoleRawIOBase):132 def readable(self) -> Literal[True]:133 return True134135 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 )143144 buffer = get_buffer(b, writable=True)145 code_units_to_be_read = bytes_to_be_read // 2146 code_units_read = c_ulong()147148 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()}")160161 if buffer[0] == EOF:162 return 0163 return 2 * code_units_read.value164165166class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):167 def writable(self) -> Literal[True]:168 return True169170 @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}"177178 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()183184 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.value192193 if bytes_written == 0 and bytes_to_be_written > 0:194 raise OSError(self._get_error_message(GetLastError())) # pragma: no cover195 return bytes_written196197198class ConsoleStream:199 def __init__(self, text_stream: TextIO, byte_stream: BinaryIO) -> None:200 self._text_stream = text_stream201 self.buffer = byte_stream202203 @property204 def name(self) -> str:205 return self.buffer.name206207 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)215216 def writelines(self, lines: Iterable[AnyStr]) -> None:217 for line in lines:218 self.write(line)219220 def __getattr__(self, name: str) -> Any:221 return getattr(self._text_stream, name)222223 def isatty(self) -> bool:224 return self.buffer.isatty()225226 def __repr__(self) -> str:227 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"228229230def _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))238239240def _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))248249250def _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))258259260_stream_factories: Mapping[int, Callable[[BinaryIO], TextIO]] = {261 0: _get_text_stdin,262 1: _get_text_stdout,263 2: _get_text_stderr,264}265266267def _is_console(f: TextIO) -> bool:268 if not hasattr(f, "fileno"):269 return False270271 try:272 fileno = f.fileno()273 except (OSError, io.UnsupportedOperation):274 return False275276 handle = msvcrt.get_osfhandle(fileno)277 return bool(GetConsoleMode(handle, byref(DWORD())))278279280def _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 None290291 func = _stream_factories.get(f.fileno())292 if func is None:293 return None294295 b = getattr(f, "buffer", None)296297 if b is None:298 return None299300 return func(b)
added:typer/_click/core.py+1111 added
1import enum2import inspect3import os4from abc import ABC, abstractmethod5from collections.abc import Callable, Iterator, Mapping, MutableMapping, Sequence6from contextlib import AbstractContextManager, ExitStack, contextmanager7from types import TracebackType8from typing import (9 TYPE_CHECKING,10 Any,11 Literal,12 NoReturn,13 TypeVar,14 Union,15 cast,16 overload,17)1819from . import types20from .exceptions import (21 Abort,22 BadParameter,23 Exit,24 MissingParameter,25 NoArgsIsHelpError,26 UsageError,27)28from .formatting import HelpFormatter29from .globals import pop_context, push_context30from .parser import _OptionParser31from .termui import style32from .utils import echo, make_default_short_help3334if TYPE_CHECKING:35 from ..core import TyperOption36 from .shell_completion import CompletionItem3738F = TypeVar("F", bound="Callable[..., Any]")39V = TypeVar("V")404142def _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 TyperGroup5051 multi = cast(TyperGroup, ctx.command)5253 for name in multi.list_commands(ctx):54 if name.startswith(incomplete):55 command = multi.get_command(ctx, name)5657 if command is not None and not command.hidden:58 yield name, command596061@contextmanager62def 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 raise787980def 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.8586 The declared parameters are re-shuffled depending on the order in which87 they were invoked, as well as the eagerness of each parameters.8889 The invocation order takes precedence over the declaration order. I.e. the90 order in which the user provided them to the CLI is respected.9192 This behavior and its effect on callback evaluation is detailed at:93 https://click.palletsprojects.com/en/stable/advanced/#callback-evaluation-order94 """9596 def sort_key(item: Parameter) -> tuple[bool, float]:97 try:98 idx: float = invocation_order.index(item)99 except ValueError:100 idx = float("inf")101102 return not item.is_eager, idx103104 return sorted(declaration_order, key=sort_key)105106107class ParameterSource(enum.Enum):108 """This is an `Enum` that indicates the source of a109 parameter's value.110 """111112 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."""122123124class 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.128129 The context is useful as it can pass internal objects around and can130 control special execution features such as reading data from131 environment variables.132133 A context can be used as context manager in which case it will call134 `close` on teardown.135 """136137 formatter_class: type[HelpFormatter] = HelpFormatter138139 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()169170 if obj is None and parent is not None:171 obj = parent.obj172173 self.obj: Any = obj174 self._meta: dict[str, Any] = getattr(parent, "meta", {})175176 # 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)184185 self.default_map: MutableMapping[str, Any] | None = default_map186187 # This flag indicates if a subcommand is going to be executed.188 self.invoked_subcommand: str | None = None189190 if terminal_width is None and parent is not None:191 terminal_width = parent.terminal_width192193 # The width of the terminal (None is autodetection).194 self.terminal_width: int | None = terminal_width195196 if max_content_width is None and parent is not None:197 max_content_width = parent.max_content_width198199 self.max_content_width: int | None = max_content_width200201 if allow_extra_args is None:202 allow_extra_args = command.allow_extra_args203204 self.allow_extra_args = allow_extra_args205206 if allow_interspersed_args is None:207 allow_interspersed_args = command.allow_interspersed_args208209 self.allow_interspersed_args: bool = allow_interspersed_args210211 if ignore_unknown_options is None:212 ignore_unknown_options = command.ignore_unknown_options213214 self.ignore_unknown_options: bool = ignore_unknown_options215216 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"]221222 self.help_option_names: list[str] = help_option_names223224 if token_normalize_func is None and parent is not None:225 token_normalize_func = parent.token_normalize_func226227 # An optional normalization function for tokens. (options, choices, commands etc.)228 self.token_normalize_func: Callable[[str], str] | None = token_normalize_func229230 # Indicates if resilient parsing is enabled.231 self.resilient_parsing: bool = resilient_parsing232233 # 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()247248 if auto_envvar_prefix is not None:249 auto_envvar_prefix = auto_envvar_prefix.replace("-", "_")250251 self.auto_envvar_prefix: str | None = auto_envvar_prefix252253 if color is None and parent is not None:254 color = parent.color255256 # Controls if styling output is wanted or not.257 self.color: bool | None = color258259 if show_default is None and parent is not None:260 show_default = parent.show_default261262 # Show option default values when formatting help text.263 self.show_default: bool | None = show_default264265 self._close_callbacks: list[Callable[[], Any]] = []266 self._depth = 0267 self._parameter_source: dict[str, ParameterSource] = {}268 self._exit_stack = ExitStack()269270 def __enter__(self) -> "Context":271 self._depth += 1272 push_context(self)273 return self274275 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()286287 return exit_result288289 @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.296297 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 -= 1308309 @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.315316 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._meta323324 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 )331332 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.336337 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.341342 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)347348 def call_on_close(self, f: Callable[..., Any]) -> Callable[..., Any]:349 """Register a function to be called when the context tears down.350351 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)357358 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)363364 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()377378 return exit_result379380 @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]391392 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))395396 rv = f"{' '.join(parent_command_path)} {rv}"397 return rv.lstrip()398399 def find_root(self) -> "Context":400 """Finds the outermost context."""401 node = self402 while node.parent is not None:403 node = node.parent404 return node405406 def find_object(self, object_type: type[V]) -> V | None:407 """Finds the closest object of a given type."""408 node: Context | None = self409410 while node is not None:411 if isinstance(node.obj, object_type):412 return node.obj413414 node = node.parent415416 return None417418 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 rv426427 @overload428 def lookup_default(self, name: str, call: Literal[True] = True) -> Any | None: ...429430 @overload431 def lookup_default(432 self, name: str, call: Literal[False] = ...433 ) -> Any | Callable[[], Any] | None: ...434435 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)439440 if call and callable(value):441 return value()442443 return value444445 return None446447 def fail(self, message: str) -> NoReturn:448 """Aborts the execution of the program with a specific error449 message.450 """451 raise UsageError(message, self)452453 def abort(self) -> NoReturn:454 """Aborts the script."""455 raise Abort()456457 def exit(self, code: int = 0) -> NoReturn:458 """Exits the application with a given exit code."""459 self.close()460 raise Exit(code)461462 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)467468 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)473474 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:477478 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 = self486487 with augment_usage_errors(self):488 with ctx:489 return callback(*args, **kwargs)490491 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] = source496497 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.500501 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)507508509class 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 """514515 context_class: type[Context] = Context516 allow_extra_args = False517 allow_interspersed_args = True518 ignore_unknown_options = False519520 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 = name536537 if context_settings is None:538 context_settings = {}539540 self.context_settings: MutableMapping[str, Any] = context_settings541542 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 = deprecated553554 def __repr__(self) -> str:555 return f"<{self.__class__.__name__} {self.name}>"556557 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")562563 def get_params(self, ctx: Context) -> list["Parameter"]:564 params = self.params565 help_option = self.get_help_option(ctx)566567 if help_option is not None:568 params = [*params, help_option]569570 return params571572 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))576577 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 []582583 for param in self.get_params(ctx):584 rv.extend(param.get_usage_pieces(ctx))585586 return rv587588 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)595596 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)599600 if not help_option_names or not self.add_help_option:601 return None602603 # 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_option610611 # Apply help_option decorator and pop resulting option612 help_option(help_option_names)(self)613 self._help_option = cast("TyperOption", self.params.pop())614615 return self._help_option616617 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 parser623624 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")629630 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 = ""640641 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}"648649 return text.strip()650651 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)657658 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 = ""665666 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}"673674 if text:675 formatter.write_paragraph()676677 with formatter.indentation():678 formatter.write_text(text)679680 @abstractmethod681 def format_options(self, ctx: Context, formatter: HelpFormatter) -> None:682 pass # pragma: no cover683684 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()689690 with formatter.indentation():691 formatter.write_text(epilog)692693 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.703704 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] = value710711 ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)712713 with ctx.scope(cleanup=False):714 self.parse_args(ctx, args)715 return ctx716717 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 cover720721 parser = self.make_parser(ctx)722 opts, args, param_order = parser.parse_args(args=args)723724 for param in iter_params_for_processing(param_order, self.get_params(ctx)):725 _, args = param.handle_parse_result(ctx, opts, args)726727 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))})")729730 ctx.args = args731 ctx._opt_prefixes.update(parser._opt_prefixes)732 return args733734 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)744745 if self.callback is not None:746 return ctx.invoke(self.callback, **ctx.params)747748 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.751752 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 CompletionItem757758 results: list[CompletionItem] = []759760 if incomplete and not incomplete[0].isalnum():761 # avoid circular imports762 from ..core import TyperOption763764 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 continue775776 results.extend(777 CompletionItem(name, help=param.help)778 for name in [*param.opts, *param.secondary_opts]779 if name.startswith(incomplete)780 )781782 return results783784 @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 cover795796 @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 cover804805 def __call__(self, *args: Any, **kwargs: Any) -> Any:806 """Alias for self.main"""807 return self.main(*args, **kwargs)808809810class Parameter(ABC):811 r"""A parameter to a command comes in two versions: they are either812 `Option`\s or `Argument`\s.813814 Some settings are supported by both options and arguments.815 """816817 param_type_name = "parameter"818819 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)844845 # 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 = 1852853 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_complete863864 def __repr__(self) -> str:865 return f"<{self.__class__.__name__} {self.name}>"866867 @abstractmethod868 def _parse_decls(869 self, decls: Sequence[str], expose_value: bool870 ) -> tuple[str | None, list[str], list[str]]:871 pass # pragma: no cover872873 @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.name880881 def make_metavar(self, ctx: Context) -> str:882 if self.metavar is not None:883 return self.metavar884885 metavar = self.type.get_metavar(param=self, ctx=ctx)886887 if metavar is None:888 metavar = self.type.name.upper()889890 if self.nargs != 1:891 metavar += "..."892893 return metavar894895 @overload896 def get_default(self, ctx: Context, call: Literal[True] = True) -> Any | None: ...897898 @overload899 def get_default(900 self, ctx: Context, call: bool = ...901 ) -> Any | Callable[[], Any] | None: ...902903 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: ignore908909 if value is None:910 value = self.default911912 if call and callable(value):913 value = value()914915 return value916917 @abstractmethod918 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:919 pass # pragma: no cover920921 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.COMMANDLINE926927 if value is None:928 value = self.value_from_envvar(ctx)929 source = ParameterSource.ENVIRONMENT930931 if value is None:932 value = ctx.lookup_default(self.name) # type: ignore933 source = ParameterSource.DEFAULT_MAP934935 if value is None:936 value = self.get_default(ctx)937 source = ParameterSource.DEFAULT938939 return value, source940941 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 None947948 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)953954 # Define the conversion function based on nargs and type.955 if self.nargs == 1 or self.type.is_composite:956957 def convert(value: Any) -> Any:958 return self.type(value, param=self, ctx=ctx)959960 elif self.nargs == -1:961962 def convert(value: Any) -> Any: # tuple[t.Any, ...]963 return tuple(self.type(x, self, ctx) for x in check_iter(value))964965 # TODO: evaluate whether we need to keep this in Typer966 else: # nargs > 1967968 def convert(value: Any) -> Any: # tuple[t.Any, ...]969 value = tuple(check_iter(value))970971 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 )977978 return tuple(self.type(x, self, ctx) for x in value)979980 if self.multiple:981 return tuple(convert(x) for x in check_iter(value))982983 return convert(value)984985 @abstractmethod986 def value_is_missing(self, value: Any) -> bool:987 pass # pragma: no cover988989 def process_value(self, ctx: Context, value: Any) -> Any:990 """Process the value of this parameter"""991 value = self.type_cast_value(ctx, value)992993 if self.required and self.value_is_missing(value):994 raise MissingParameter(ctx=ctx, param=self)995996 if self.callback is not None:997 value = self.callback(ctx, self, value)998999 return value10001001 def resolve_envvar_value(self, ctx: Context) -> str | None:1002 """Returns the value found in the environment variable(s) attached to this1003 parameter.10041005 Environment variables values are `always returned as strings1006 <https://docs.python.org/3/library/os.html#os.environ>`_.10071008 This method returns ``None`` if:10091010 - 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).10141015 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 None10201021 if isinstance(self.envvar, str):1022 rv = os.environ.get(self.envvar)10231024 if rv:1025 return rv1026 else:1027 for envvar in self.envvar:1028 rv = os.environ.get(envvar)10291030 # 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.10351036 return None10371038 def value_from_envvar(self, ctx: Context) -> str | Sequence[str] | None:1039 """Process the raw environment variable string for this parameter.10401041 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)10461047 if rv is not None and self.nargs != 1:1048 rv = self.type.split_envvar_value(rv)10491050 return rv10511052 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.10561057 Always process the value through the Parameter's `type`, wherever it1058 comes from.10591060 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)10661067 ctx.set_parameter_source(self.name, source) # type: ignore10681069 # 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 = None10761077 if self.expose_value:1078 ctx.params[self.name] = value # type: ignore10791080 return value, args10811082 @abstractmethod1083 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:1084 pass # pragma: no cover10851086 def get_usage_pieces(self, ctx: Context) -> list[str]:1087 return []10881089 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)10951096 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)11031104 if results and isinstance(results[0], str):1105 from .shell_completion import CompletionItem11061107 results = [CompletionItem(c) for c in results]11081109 return cast("list[CompletionItem]", results)11101111 return self.type.shell_complete(ctx, self, incomplete)
added:typer/_click/decorators.py+60 added
1from collections.abc import Callable2from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar34from .core import Command, Context, Parameter5from .utils import echo67if TYPE_CHECKING:8 from ..core import TyperGroup, TyperOption910 GrpType = TypeVar("GrpType", bound=TyperGroup)111213P = ParamSpec("P")1415R = TypeVar("R")16T = TypeVar("T")17_AnyCallable = Callable[..., Any]181920CmdType = TypeVar("CmdType", bound=Command)212223def 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 TyperOption3031 cls = TyperOption3233 def decorator(f: Command) -> Command:34 param = cls(param_decls=param_decls, **attrs)35 f.params.append(param)36 return f3738 return decorator394041def help_option(param_decls: list[str]) -> Callable[[Command], Command]:42 """Help option which prints the help page and exits the program."""4344 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()4950 assert len(param_decls) > 0, "At least one help option should be provided"5152 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
1from collections.abc import Sequence2from typing import IO, TYPE_CHECKING, Any, Union34from ._compat import get_text_stderr5from .globals import resolve_color_default6from .utils import echo, format_filename78if TYPE_CHECKING:9 from .core import Command, Context, Parameter101112def _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)1516 return param_hint171819class ClickException(Exception):20 """An exception that Click can handle and show to the user."""2122 exit_code = 12324 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 = message3031 def format_message(self) -> str:32 return self.message3334 def __str__(self) -> str:35 return self.message3637 def show(self, file: IO[Any] | None = None) -> None:38 if file is None:39 file = get_text_stderr()4041 echo(42 f"Error: {self.format_message()}",43 file=file,44 color=self.show_color,45 )464748class UsageError(ClickException):49 """An internal exception that signals a usage error. This typically50 aborts any further handling.51 """5253 exit_code = 25455 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 None5960 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 )808182class 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 """8889 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_hint99100 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}"107108 hint = _join_param_hints(param_hint)109 return f"Invalid value for {hint}: {self.message}"110111112class MissingParameter(BadParameter):113 """Raised if click required an option or argument but it was not114 provided when invoking the script.115 """116117 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_type127128 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 = None135136 param_hint = _join_param_hints(param_hint)137 param_hint = f" {param_hint}" if param_hint else ""138139 param_type = self.param_type140 if param_type is None and self.param is not None:141 param_type = self.param.param_type_name142143 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_extra153154 msg = f" {msg}" if msg else ""155156 # 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}"165166 return f"{missing}{param_hint}.{msg}"167168 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.message174175176class NoSuchOption(UsageError):177 """Raised if click attempted to handle an option that does not178 exist.179 """180181 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}"190191 super().__init__(message, ctx)192 self.option_name = option_name193 self.possibilities = possibilities194195 def format_message(self) -> str:196 if not self.possibilities:197 return self.message198199 possibility_str = ", ".join(sorted(self.possibilities))200 suggest = (f"(Possible options: {possibility_str})",)201 return f"{self.message} {suggest}"202203204class 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 """209210 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_name215216217class 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 """222223224class NoArgsIsHelpError(UsageError):225 def __init__(self, ctx: "Context") -> None:226 self.ctx: Context227 super().__init__(ctx.get_help(), ctx=ctx)228229 def show(self, file: IO[Any] | None = None) -> None:230 echo(self.format_message(), file=file, err=True, color=self.ctx.color)231232233class FileError(ClickException):234 """Raised if a file cannot be opened."""235236 def __init__(self, filename: str, hint: str | None = None) -> None:237 if hint is None:238 hint = "unknown error"239240 super().__init__(hint)241 self.ui_filename: str = format_filename(filename)242 self.filename = filename243244 def format_message(self) -> str:245 return f"Could not open file {self.ui_filename!r}: {self.message}"246247248class Abort(RuntimeError):249 """An internal signalling exception that signals Click to abort."""250251252class Exit(RuntimeError):253 """An exception that indicates that the application should exit with some254 status code.255 """256257 __slots__ = ("exit_code",)258259 def __init__(self, code: int = 0) -> None:260 self.exit_code: int = code
added:typer/_click/formatting.py+272 added
1from collections.abc import Iterable, Iterator, Sequence2from contextlib import contextmanager34from ._compat import term_len5from .parser import _split_opt67# Can force a width. This is used by the test system8FORCED_WIDTH: int | None = None91011def measure_table(rows: Iterable[tuple[str, str]]) -> tuple[int, ...]:12 widths: dict[int, int] = {}1314 for row in rows:15 for idx, col in enumerate(row):16 widths[idx] = max(widths.get(idx, 0), term_len(col))1718 return tuple(y for x, y in sorted(widths.items()))192021def 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))262728def 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).3940 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 TextWrapper4546 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)5556 p: list[tuple[int, bool, str]] = []57 buf: list[str] = []58 indent = None5960 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[:]6869 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()8081 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))8889 return "\n\n".join(rv)909192class 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.9697 At present, it always writes into memory.98 """99100 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 shutil111112 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] = []118119 def write(self, string: str) -> None:120 """Writes a unicode string into the internal buffer."""121 self.buffer.append(string)122123 def indent(self) -> None:124 """Increases the indentation."""125 self.current_indent += self.indent_increment126127 def dedent(self) -> None:128 """Decreases the indentation."""129 self.current_indent -= self.indent_increment130131 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: "135136 usage_prefix = f"{prefix:>{self.current_indent}}{prog} "137 text_width = self.width - self.current_indent138139 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 )160161 self.write("\n")162163 def write_heading(self, heading: str) -> None:164 """Writes a heading into the buffer."""165 self.write(f"{'':>{self.current_indent}}{heading}:\n")166167 def write_paragraph(self) -> None:168 """Writes a paragraph into the buffer."""169 if self.buffer:170 self.write("\n")171172 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")187188 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")201202 first_col = min(widths[0], col_max) + col_spacing203204 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))214215 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()218219 if lines:220 self.write(f"{lines[0]}\n")221222 for line in lines[1:]:223 self.write(f"{'':>{first_col + self.current_indent}}{line}\n")224 else: # pragma: no cover225 self.write("\n")226227 @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()239240 @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()248249 def getvalue(self) -> str:250 """Returns the buffer contents."""251 return "".join(self.buffer)252253254def 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 = False262263 for opt in options:264 prefix = _split_opt(opt)[0]265266 if prefix == "/":267 any_prefix_is_slash = True268269 rv.append((len(prefix), opt))270271 rv.sort(key=lambda x: x[0])272 return ", ".join(x[1] for x in rv), any_prefix_is_slash
added:typer/_click/globals.py+61 added
1from threading import local2from typing import TYPE_CHECKING, Literal, Union, cast, overload34if TYPE_CHECKING:5 from .core import Context67_local = local()8910@overload11def get_current_context(silent: Literal[False] = False) -> "Context": ...121314@overload15def get_current_context(silent: bool = ...) -> Union["Context", None]: ...161718def 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.2425 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 cover3435 return None363738def push_context(ctx: "Context") -> None:39 """Pushes a new context to the current stack."""40 _local.__dict__.setdefault("stack", []).append(ctx)414243def pop_context() -> None:44 """Removes the top level from the stack."""45 _local.stack.pop()464748def 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 color5556 ctx = get_current_context(silent=True)5758 if ctx is not None:59 return ctx.color6061 return None
added:typer/_click/LICENSE.txt+28 added
1Copyright 2014 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. 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.13143. 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.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
added:typer/_click/parser.py+459 added
1"""2This module started out as largely a copy paste from the stdlib's3optparse module with the features removed that we do not need from4optparse because we implement them in Click on a higher level (for5instance type handling, help formatting and a lot more).67The plan is to remove more and more from here over time.89The reason this is a different module and not optparse from the stdlib10is that there are differences in 2.x and 3.x about the error messages11generated and optparse in the stdlib uses gettext for no good reason12and might cause us issues.1314Click uses parts of optparse written by Gregory P. Ward and maintained15by the Python Software Foundation. This is limited to code in parser.py.1617Copyright 2001-2006 Gregory P. Ward. All rights reserved.18Copyright 2002-2006 Python Software Foundation. All rights reserved.19"""2021# 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 Foundation25from collections import deque26from collections.abc import Sequence27from typing import (28 TYPE_CHECKING,29 Any,30 TypeVar,31 Union,32)3334from .exceptions import BadArgumentUsage, BadOptionUsage, NoSuchOption, UsageError3536if TYPE_CHECKING:37 from typer.core import TyperArgument as CoreArgument38 from typer.core import TyperOption as CoreOption3940 from .core import Context41 from .core import Parameter as CoreParameter4243V = TypeVar("V")444546def _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.5253 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 = None6061 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 None6970 while nargs_spec:71 nargs = _fetch(nargs_spec)72 assert nargs is not None7374 if nargs == 1:75 rv.append(_fetch(args))76 elif nargs > 1:77 x = [_fetch(args) for _ in range(nargs)]7879 # 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()8384 rv.append(tuple(x))85 elif nargs < 0:86 if spos is not None: # pragma: no cover87 raise TypeError("Cannot have two nargs < 0")8889 spos = len(rv)90 rv.append(None)9192 # 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 :])9899 return tuple(rv), list(args)100101102def _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:]109110111def _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)}"116117118class _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()131132 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)142143 self.dest = dest144 self.action = action145 self.nargs = nargs146 self.const = const147 self.obj = obj148149 @property150 def takes_value(self) -> bool:151 return self.action in ("store", "append")152153 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)167168169class _Argument:170 def __init__(self, obj: "CoreArgument", dest: str | None, nargs: int = 1):171 self.dest = dest172 self.nargs = nargs173 self.obj = obj174175 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 )189190 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 = None194195 state.opts[self.dest] = value # type: ignore196 state.order.append(self.obj)197198199class _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] = []205206207class _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.212213 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 """217218 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 = False230231 if ctx is not None:232 self.allow_interspersed_args = ctx.allow_interspersed_args233 self.ignore_unknown_options = ctx.ignore_unknown_options234235 self._short_opt: dict[str, _Option] = {}236 self._long_opt: dict[str, _Option] = {}237 self._opt_prefixes = {"-", "--"}238 self._args: list[_Argument] = []239240 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``.253254 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] = option264265 def add_argument(266 self, obj: "CoreArgument", dest: str | None, nargs: int = 1267 ) -> None:268 """Adds a positional argument named `dest` to the parser.269270 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))274275 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.order292293 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 )297298 for idx, arg in enumerate(self._args):299 arg.process(pargs[idx], state)300301 state.largs = args302 state.rargs = []303304 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 return319320 # 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!339340 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_matches345346 possibilities = get_close_matches(opt, self._long_opt)347 raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)348349 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)357358 value = self._get_value_from_state(opt, option, state)359360 elif explicit_value is not None: # pragma: no cover361 raise BadOptionUsage(opt, f"Option {opt!r} does not take a value.")362363 else:364 value = None365366 option.process(value, state)367368 def _match_short_opt(self, arg: str, state: _ParsingState) -> None:369 stop = False370 i = 1371 prefix = arg[0]372 unknown_options = []373374 for ch in arg[1:]:375 opt = _normalize_opt(f"{prefix}{ch}", self.ctx)376 option = self._short_opt.get(opt)377 i += 1378379 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 = True390391 value = self._get_value_from_state(opt, option, state)392393 else:394 value = None395396 option.process(value, state)397398 if stop:399 break400401 # 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)}")407408 def _get_value_from_state(409 self, option_name: str, option: _Option, state: _ParsingState410 ) -> str | Sequence[str]:411 nargs = option.nargs412413 value: str | Sequence[str]414415 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]426427 return value428429 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)439440 # 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 return455456 if not self.ignore_unknown_options:457 raise458459 state.largs.append(arg)
added:typer/_click/py.typed
added:typer/_click/shell_completion.py+306 added
1import re2from abc import ABC, abstractmethod3from collections.abc import MutableMapping4from typing import Any, ClassVar, TypeVar56from .core import Command, Context, Parameter, ParameterSource789class 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.1415 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 """1920 __slots__ = ("value", "type", "help", "_info")2122 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 = kwargs3334 def __getattr__(self, name: str) -> Any:35 return self._info.get(name)363738class 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 """4344 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 """4950 source_template: ClassVar[str]51 """Completion script template formatted by `source`. This must52 be provided by subclasses.53 """5455 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_var6667 @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"7475 @abstractmethod76 def source_vars(self) -> dict[str, Any]:77 """Vars for formatting `source_template`."""78 pass # pragma: no cover7980 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()8687 @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 cover9495 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)103104 @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 cover110111 def complete(self) -> str:112 """Produce the completion data to send back to the shell.113114 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)122123124ShellCompleteType = TypeVar("ShellCompleteType", bound="type[ShellComplete]")125126127_available_shells: dict[str, type[ShellComplete]] = {}128129130def 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] = cls136137 return cls138139140def 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)146147148def 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 shlex154155 lex = shlex.shlex(string, posix=True)156 lex.whitespace_split = True157 lex.commenters = ""158 out = []159160 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)168169 return out170171172def _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 TyperArgument178179 if not isinstance(param, TyperArgument):180 return False181182 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 )194195196def _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 False200201 c = value[0]202 return c in ctx._opt_prefixes203204205def _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 TyperOption209210 if not isinstance(param, TyperOption):211 return False212213 if param.is_flag or param.count:214 return False215216 last_option = None217218 for index, arg in enumerate(reversed(args)):219 if index + 1 > param.nargs:220 break221222 if _start_of_option(ctx, arg):223 last_option = arg224 break225226 return last_option is not None and last_option in param.opts227228229def _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 TyperGroup241242 ctx_args["resilient_parsing"] = True243 with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx:244 args = ctx._protected_args + ctx.args245246 while args:247 command = ctx.command248249 if isinstance(command, TyperGroup):250 # if not command.chain:251 name, cmd, args = command.resolve_command(ctx, args)252253 if cmd is None:254 return ctx255256 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 break263264 return ctx265266267def _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)282283 # 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, incomplete289290 params = ctx.command.get_params(ctx)291292 # 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, incomplete297298 # 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, incomplete303304 # There were no unparsed arguments, the command may be a group that305 # will provide command name completions.306 return ctx.command, incomplete
added:typer/_click/termui.py+430 added
1import io2from collections.abc import Callable, Iterable3from contextlib import AbstractContextManager4from typing import IO, TYPE_CHECKING, Any, AnyStr, TextIO, TypeVar, overload56from .exceptions import Abort, UsageError7from .globals import resolve_color_default8from .types import ParamType, convert_type9from .utils import LazyFile, echo1011if TYPE_CHECKING:12 from ._termui_impl import ProgressBar1314V = TypeVar("V")1516# The prompt functions to use. The doc tools currently override these17# functions to customize how they work.18visible_prompt_func: Callable[[str], str] = input1920_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"404142def hidden_prompt_func(prompt: str) -> str:43 import getpass4445 return getpass.getpass(prompt)464748def _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 TyperChoice5859 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}"656667def _format_default(default: Any) -> Any:68 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):69 return default.name7071 return default727374def 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.8889 If the user aborts the input by sending an interrupt signal, this90 function will catch it and raise an `Abort` exception.91 """9293 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 None109110 if value_proc is None:111 value_proc = convert_type(type, default)112113 prompt = _build_prompt(114 text, prompt_suffix, show_default, default, show_choices, type115 )116117 if confirmation_prompt:118 if confirmation_prompt is True:119 confirmation_prompt = "Repeat for confirmation"120121 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)122123 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)149150151def 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).160161 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 )170171 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 rv194195196@overload197def 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]": ...214215216@overload217def 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]": ...235236237def 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.262263 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.268269 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.274275 No printing must happen or the progress bar will be unintentionally276 destroyed.277 """278 from ._termui_impl import ProgressBar279280 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 )299300301def _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}"304305 if isinstance(color, (tuple, list)):306 r, g, b = color307 return f"{38 + offset};2;{r:d};{g:d};{b:d}"308309 return str(_ansi_colors[color] + offset)310311312def 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)333334 bits = []335336 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 None341342 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 None347348 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)368369370def 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)381382 return echo(message, file=file, nl=nl, err=err, color=color)383384385def 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_url393394 return open_url(url, wait=wait, locate=locate)395396397# If this is provided, getchar() calls into this instead. This is used398# for unittesting purposes.399_getchar: Callable[[bool], str] | None = None400401402def 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.409410 Note that this will always read from the terminal, even if something411 is piped into the standard input.412413 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 _getchar418419 if _getchar is None:420 from ._termui_impl import getchar as f421422 _getchar = f423424 return _getchar(echo)425426427def raw_terminal() -> AbstractContextManager[int]:428 from ._termui_impl import raw_terminal as f429430 return f()
added:typer/_click/testing.py+366 added
1import contextlib2import io3import os4import shlex5import sys6from collections.abc import Iterator, Mapping, Sequence7from types import TracebackType8from typing import IO, TYPE_CHECKING, Any, BinaryIO, cast910from . import _compat, formatting, termui, utils11from ._compat import _find_binary_reader12from .core import Command1314if TYPE_CHECKING:15 from _typeshed import ReadableBuffer161718class BytesIOCopy(io.BytesIO):19 """Patch ``io.BytesIO`` to let the written stream be copied to another."""2021 def __init__(self, copy_to: io.BytesIO) -> None:22 super().__init__()23 self.copy_to = copy_to2425 def flush(self) -> None:26 super().flush()27 self.copy_to.flush()2829 def write(self, b: "ReadableBuffer") -> int:30 self.copy_to.write(b)31 return super().write(b)323334class StreamMixer:35 """Mixes `<stdout>` and `<stderr>` streams.3637 The result is available in the ``output`` attribute.38 """3940 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)4445 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()545556class _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 = mode6162 @property63 def name(self) -> str:64 return self._name # pragma: no cover6566 @property67 def mode(self) -> str:68 return self._mode # pragma: no cover697071def 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))7576 if rv is not None:77 return rv7879 raise TypeError(80 "Could not find binary reader for input stream."81 ) # pragma: no cover8283 if input is None:84 input = b""85 elif isinstance(input, str):86 input = input.encode(charset)8788 return io.BytesIO(input)899091class Result:92 """Holds the captured result of an invoked CLI script."""9394 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_info114115 @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 )121122 @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 )128129 @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 )135136 def __repr__(self) -> str:137 exc_str = repr(self.exception) if self.exception else "okay"138 return f"<{type(self).__name__} {exc_str}>"139140141class 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 """147148 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_exceptions157158 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"164165 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 rv173174 @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)188189 old_stdin = sys.stdin190 old_stdout = sys.stdout191 old_stderr = sys.stderr192 old_forced_width = formatting.FORCED_WIDTH193 formatting.FORCED_WIDTH = 80194195 env = self.make_env(env)196197 stream_mixer = StreamMixer()198199 sys.stdin = text_input = _NamedTextIOWrapper(200 bytes_input, encoding=self.charset, name="<stdin>", mode="r"201 )202203 sys.stdout = _NamedTextIOWrapper(204 stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"205 )206207 sys.stderr = _NamedTextIOWrapper(208 stream_mixer.stderr,209 encoding=self.charset,210 name="<stderr>",211 mode="w",212 errors="backslashreplace",213 )214215 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 val224225 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 e232233 def _getchar(echo: bool) -> str:234 char = sys.stdin.read(1)235236 if echo:237 sys.stdout.write(char)238239 sys.stdout.flush()240 return char241242 default_color = color243244 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 color250251 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]261262 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_width292293 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_exceptions311312 with self.isolation(input=input, env=env, color=color) as outstreams:313 return_value = None314 exception: BaseException | None = None315 exit_code = 0316317 if isinstance(args, str):318 args = shlex.split(args)319320 try:321 prog_name = extra.pop("prog_name")322 except KeyError:323 prog_name = self.get_default_prog_name(cli)324325 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)330331 if e_code is None:332 e_code = 0333334 if e_code != 0:335 exception = e336337 if not isinstance(e_code, int):338 sys.stdout.write(str(e_code))339 sys.stdout.write("\n")340 e_code = 1341342 exit_code = e_code343344 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()356357 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
1import os2import sys3from collections.abc import Callable, Sequence4from datetime import datetime5from 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)1819from ._compat import _get_argv_encoding, open_stream20from .exceptions import BadParameter21from .utils import LazyFile, format_filename, safecall2223if TYPE_CHECKING:24 from .core import Context, Parameter25 from .shell_completion import CompletionItem2627ParamTypeValue = TypeVar("ParamTypeValue")282930class ParamType:31 """Represents the type of a parameter. Validates and converts values32 from the command line or Python into the correct type.3334 To implement a custom type, subclass and implement at least the35 following:3637 - 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 """4748 is_composite: ClassVar[bool] = False49 arity: ClassVar[int] = 150 name: str5152 # 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] = None5960 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)6869 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 cover7273 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 cover8081 def convert(82 self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]83 ) -> Any:84 pass # pragma: no cover8586 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.8990 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)9596 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)104105 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 []114115116class CompositeParamType(ParamType):117 is_composite = True118119 @property120 def arity(self) -> int: # type: ignore121 raise NotImplementedError() # pragma: no cover122123124class FuncParamType(ParamType):125 def __init__(self, func: Callable[[Any], Any]) -> None:126 self.name: str = getattr(func, "__name__", "function")127 self.func = func128129 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")140141 self.fail(value, param, ctx)142143144class StringParamType(ParamType):145 name = "text"146147 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)165166 def __repr__(self) -> str:167 return "STRING"168169170class DateTime(ParamType):171 """The DateTime type converts date strings into `datetime` objects.172173 The format strings which are checked are configurable, but default to some174 common (non-timezone aware) ISO 8601 formats.175176 When specifying *DateTime* formats, you should only pass a list or a tuple.177 Other iterables, like generators, may lead to surprising results.178179 The format strings are processed using ``datetime.strptime``, and this180 consequently defines the format strings which are allowed.181182 Parsing is tried using each format, in order, and the first format which183 parses successfully is used.184 """185186 name = "datetime"187188 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 ]194195 def get_metavar(self, param: "Parameter", ctx: "Context") -> str | None:196 return f"[{'|'.join(self.formats)}]"197198 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 None203204 def convert(205 self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]206 ) -> Any:207 if isinstance(value, datetime):208 return value209210 for format in self.formats:211 converted = self._try_to_convert_date(value, format)212213 if converted is not None:214 return converted215216 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 )222223 def __repr__(self) -> str:224 return "DateTime"225226227class _NumberParamTypeBase(ParamType):228 _number_class: ClassVar[type[Any]]229230 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 )241242243class _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 = clamp257258 def convert(259 self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]260 ) -> Any:261 import operator262263 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)270271 if self.clamp:272 if lt_min:273 return self._clamp(self.min, 1, self.min_open) # type: ignore[arg-type]274275 if gt_max:276 return self._clamp(self.max, -1, self.max_open) # type: ignore[arg-type]277278 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 )284285 return rv286287 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 cover292293 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}"298299 if self.max is None:300 op = ">" if self.min_open else ">="301 return f"x{op}{self.min}"302303 lop = "<" if self.min_open else "<="304 rop = "<" if self.max_open else "<="305 return f"{self.min}{lop}x{rop}{self.max}"306307 def __repr__(self) -> str:308 clamp = " clamped" if self.clamp else ""309 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"310311312class IntParamType(_NumberParamTypeBase):313 name = "integer"314 _number_class = int315316 def __repr__(self) -> str:317 return "INT"318319320class IntRange(_NumberRangeBase, IntParamType):321 """Restrict an `INT` value to a range of accepted values. See322323 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.326327 If ``clamp`` is enabled, a value outside the range is clamped to the328 boundary instead of failing.329 """330331 name = "integer range"332333 def _clamp( # type: ignore334 self, bound: int, dir: Literal[1, -1], open: bool335 ) -> int:336 if not open:337 return bound338339 return bound + dir340341342class FloatParamType(_NumberParamTypeBase):343 name = "float"344 _number_class = float345346 def __repr__(self) -> str:347 return "FLOAT"348349350class FloatRange(_NumberRangeBase, FloatParamType):351 """Restrict a `FLOAT` value to a range of accepted352 values. See `ranges`.353354 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.357358 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 """362363 name = "float range"364365 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 )376377 if (min_open or max_open) and clamp:378 raise TypeError("Clamping is not supported for open bounds.")379380 def _clamp(self, bound: float, dir: Literal[1, -1], open: bool) -> float:381 if not open:382 return bound383384 # 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 cover390391392class BoolParamType(ParamType):393 name = "boolean"394395 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.412413 Mapping is inspired by `configparser.ConfigParser.BOOLEAN_STATES`414 and extends it.415 """416417 @staticmethod418 def str_to_bool(value: str | bool) -> bool | None:419 """Convert a string to a boolean value.420421 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.425426 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())431432 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 normalized444445 def __repr__(self) -> str:446 return "BOOL"447448449class UUIDParameterType(ParamType):450 name = "uuid"451452 def convert(453 self, value: Any, param: Union["Parameter", None], ctx: Union["Context", None]454 ) -> Any:455 import uuid456457 if isinstance(value, uuid.UUID):458 return value459460 value = value.strip()461462 try:463 return uuid.UUID(value)464 except ValueError:465 self.fail(f"{value!r} is not a valid UUID.", param, ctx)466467 def __repr__(self) -> str:468 return "UUID"469470471class 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).475476 Files can be opened for reading or writing. The special value ``-``477 indicates stdin or stdout depending on the mode.478479 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.482483 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.489490 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 """495496 name = "filename"497 envvar_list_splitter: ClassVar[str] = os.path.pathsep498499 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 = atomic512513 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 False521522 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 value530531 value = cast("str | os.PathLike[str]", value)532533 try:534 lazy = self.resolve_lazy_flag(value)535536 if lazy:537 lf = LazyFile(538 value, self.mode, self.encoding, self.errors, atomic=self.atomic539 )540541 if ctx is not None:542 ctx.call_on_close(lf.close_intelligently)543544 return cast("IO[Any]", lf)545546 f, should_close = open_stream(547 value, self.mode, self.encoding, self.errors, atomic=self.atomic548 )549550 # 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))560561 return f562 except OSError as e: # pragma: no cover563 self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)564565 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 CompletionItem572573 return [CompletionItem(incomplete, type="file")]574575576def _is_file_like(value: Any) -> TypeGuard[IO[Any]]:577 return hasattr(value, "read") or hasattr(value, "write")578579580class 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.586587 For more information see `tuple-type`.588589 This can be selected by using a Python tuple literal as a type.590 """591592 def __init__(self, types: Sequence[type[Any] | ParamType]) -> None:593 self.types: Sequence[ParamType] = [convert_type(ty) for ty in types]594595 @property596 def name(self) -> str: # type: ignore[override]597 return f"<{' '.join(ty.name for ty in self.types)}>"598599 @property600 def arity(self) -> int: # type: ignore601 return len(self.types)602603 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)608609 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 )615616 return tuple(617 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)618 )619620621def 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 = False627628 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]634635 # 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)644645 guessed_type = True646647 if isinstance(ty, tuple):648 return Tuple(ty)649650 if isinstance(ty, ParamType):651 return ty652653 if ty is str or ty is None:654 return STRING655656 if ty is int:657 return INT658659 if ty is float:660 return FLOAT661662 if ty is bool:663 return BOOL664665 if guessed_type:666 return STRING667668 return FuncParamType(ty)669670671# A unicode string parameter type which is the implicit default. This672# can also be selected by using ``str`` as type.673STRING = StringParamType()674675# An integer parameter. This can also be selected by using ``int`` as676# type.677INT = IntParamType()678679# A floating point value parameter. This can also be selected by using680# ``float`` as type.681FLOAT = FloatParamType()682683# A boolean parameter. This is the default for boolean flags. This can684# also be selected by using ``bool`` as a type.685BOOL = BoolParamType()686687# A UUID parameter.688UUID = UUIDParameterType()689690691class OptionHelpExtra(TypedDict, total=False):692 envvars: tuple[str, ...]693 default: str694 range: str695 required: str
added:typer/_click/utils.py+470 added
1import os2import re3import sys4from collections.abc import Callable, Iterable, Iterator5from functools import update_wrapper6from types import ModuleType, TracebackType7from typing import (8 IO,9 Any,10 AnyStr,11 BinaryIO,12 Literal,13 ParamSpec,14 TextIO,15 TypeVar,16 cast,17)1819from ._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)31from .globals import resolve_color_default3233P = ParamSpec("P")34R = TypeVar("R")353637def _posixify(name: str) -> str:38 return "-".join(name.split()).lower()394041def safecall(func: Callable[P, R]) -> Callable[P, R | None]:42 """Wraps a function so that it swallows exceptions."""4344 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 cover5051 return update_wrapper(wrapper, func)525354def 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")5859 if paragraph_end != -1:60 help = help[:paragraph_end]6162 # Collapse newlines, tabs, and spaces.63 words = help.split()6465 if not words:66 return ""6768 # The first paragraph started with a "no rewrap" marker, ignore it.69 if words[0] == "\b":70 words = words[1:]7172 total_length = 073 last_index = len(words) - 17475 for i, word in enumerate(words):76 total_length += len(word) + (i > 0)7778 if total_length > max_length: # too long, truncate79 break8081 if word[-1] == ".": # sentence end, truncate without "..."82 return " ".join(words[: i + 1])8384 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 needed8889 # Account for the length of the suffix.90 total_length += len("...")9192 # remove words until the length is short enough93 while i > 0:94 total_length -= len(words[i]) + (i > 0)9596 if total_length <= max_length:97 break9899 i -= 1100101 return " ".join(words[:i]) + "..."102103104class 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 """110111 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: bool126127 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 = True137138 def __getattr__(self, name: str) -> Any:139 return getattr(self.open(), name)140141 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}>"145146 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 FileError159160 raise FileError(self.name, hint=e.strerror) from e161 self._f = rv162 return rv163164 def close(self) -> None:165 """Closes the underlying file, no matter what."""166 if self._f is not None:167 self._f.close()168169 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()175176 def __enter__(self) -> "LazyFile":177 return self178179 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()186187 def __iter__(self) -> Iterator[AnyStr]:188 self.open()189 return iter(self._f) # type: ignore190191192def 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.202203 Compared to `print`, this does the following:204205 - 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()219220 # There are no standard streams attached to write to. For example,221 # pythonw on Windows.222 if file is None:223 return224225 # 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 = message230231 if nl:232 out = out or ""233 if isinstance(out, str):234 out += "\n"235 else:236 out += b"\n"237238 if not out:239 file.flush()240 return241242 # 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)248249 if binary_file is not None:250 file.flush()251 binary_file.write(out)252 binary_file.flush()253 return254255 # 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)259260 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)267268 file.write(out) # type: ignore[arg-type]269 file.flush()270271272def 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()278279280def 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)294295296def 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 ``�``.303304 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``.307308 Many scenarios *are* safe to write surrogates though, due to PEP 538 and309 PEP 540, including:310311 - 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)322323 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 )329330 return filename331332333def 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.336337 To give you an idea, for an app called ``"Foo Bar"``, something like338 the following folders could be returned:339340 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 )369370371class 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 """379380 def __init__(self, wrapped: IO[Any]) -> None:381 self.wrapped = wrapped382383 def flush(self) -> None:384 try:385 self.wrapped.flush()386 except OSError as e: # pragma: no cover387 import errno388389 if e.errno != errno.EPIPE:390 raise391392 def __getattr__(self, attr: str) -> Any:393 return getattr(self.wrapped, attr)394395396def _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.403404 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__"]411412 if not path:413 path = sys.argv[0]414415 # 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)427428 # 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]433434 # A submodule like "example.cli".435 if name != "__main__":436 py_module = f"{py_module}.{name}"437438 return f"python -m {py_module.lstrip('.')}"439440441def _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 glob450451 out = []452453 for arg in args:454 if user:455 arg = os.path.expanduser(arg)456457 if env:458 arg = os.path.expandvars(arg)459460 try:461 matches = glob(arg, recursive=glob_recursive)462 except re.error: # pragma: no cover463 matches = []464465 if not matches:466 out.append(arg)467 else:468 out.extend(matches)469470 return out
modified:typer/.agents/skills/typer/SKILL.md+1 added-1 removed
257 unmodified lines
258```259260## Click261262Originally, Typer was built on Click. However, going forward Typer will vendor Click. As such, Click extensions should not be used anymore.262Originally, Typer was built on Click. However, since version 0.26.0, Typer has vendored Click. As such, Click extensions should not be used anymore.263264Other 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`.265266Code bases using these should be refactored to use pure Typer functionality.
modified:typer/__init__.py+14 added-21 removed
2 unmodified lines
3__version__ = "0.25.1"45from shutil import get_terminal_size as get_terminal_size67from click.exceptions import Abort as Abort8from click.exceptions import BadParameter as BadParameter9from click.exceptions import Exit as Exit10from click.termui import clear as clear11from click.termui import confirm as confirm12from click.termui import echo_via_pager as echo_via_pager13from click.termui import edit as edit14from click.termui import getchar as getchar15from click.termui import pause as pause16from click.termui import progressbar as progressbar17from click.termui import prompt as prompt18from click.termui import secho as secho19from click.termui import style as style20from click.termui import unstyle as unstyle21from click.utils import echo as echo22from click.utils import format_filename as format_filename23from click.utils import get_app_dir as get_app_dir24from click.utils import get_binary_stream as get_binary_stream25from click.utils import get_text_stream as get_text_stream26from click.utils import open_file as open_file277from . import colors as colors8from ._click.exceptions import Abort as Abort9from ._click.exceptions import BadParameter as BadParameter10from ._click.exceptions import Exit as Exit11from ._click.termui import confirm as confirm12from ._click.termui import getchar as getchar13from ._click.termui import progressbar as progressbar14from ._click.termui import prompt as prompt15from ._click.termui import secho as secho16from ._click.termui import style as style17from ._click.utils import echo as echo18from ._click.utils import format_filename as format_filename19from ._click.utils import get_app_dir as get_app_dir20from ._click.utils import get_binary_stream as get_binary_stream21from ._click.utils import get_text_stream as get_text_stream22from .main import Typer as Typer23from .main import launch as launch24from .main import run as run25from .models import CallbackParam as CallbackParam
7 unmodified lines
modified:typer/_completion_classes.py+50 added-20 removed
2 unmodified lines
3import re4import sys5from typing import Any67import click8import click.parser9import click.shell_completion10from click.shell_completion import split_arg_string as click_split_arg_string117from . import _click8from ._click.shell_completion import CompletionItem, ShellComplete, add_completion_class9from ._click.shell_completion import split_arg_string as click_split_arg_string10from ._completion_shared import (11 COMPLETION_SCRIPT_BASH,12 COMPLETION_SCRIPT_FISH,13 COMPLETION_SCRIPT_POWER_SHELL,
10 unmodified lines
2425 return rich_utils.rich_render_text(text)262730class BashComplete(click.shell_completion.BashComplete):28class BashComplete(ShellComplete):29 name = Shells.bash.value30 source_template = COMPLETION_SCRIPT_BASH3132 def source_vars(self) -> dict[str, Any]:
14 unmodified lines
47 incomplete = ""4849 return args, incomplete5053 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 lines
59 completions = self.get_completions(args, incomplete)60 out = [self.format_completion(item) for item in completions]61 return "\n".join(out)6263 @staticmethod64 def _check_version() -> None:65 import shutil66 import subprocess6768 bash_exe = shutil.which("bash")6970 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())7879 if match is not None:80 major, minor = match.groups()8182 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 cover9293 def source(self) -> str:94 self._check_version()95 return super().source()969766class ZshComplete(click.shell_completion.ZshComplete):98class ZshComplete(ShellComplete):99 name = Shells.zsh.value100 source_template = COMPLETION_SCRIPT_ZSH101102 def source_vars(self) -> dict[str, Any]:
13 unmodified lines
116 else:117 incomplete = ""118 return args, incomplete11988 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 lines
145 else:146 return "_files"147148117class FishComplete(click.shell_completion.FishComplete):149class FishComplete(ShellComplete):150 name = Shells.fish.value151 source_template = COMPLETION_SCRIPT_FISH152153 def source_vars(self) -> dict[str, Any]:
13 unmodified lines
167 else:168 incomplete = ""169 return args, incomplete170139 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 lines
198 sys.exit(1)199 return "" # pragma: no cover200201170class PowerShellComplete(click.shell_completion.ShellComplete):202class PowerShellComplete(ShellComplete):203 name = Shells.powershell.value204 source_template = COMPLETION_SCRIPT_POWER_SHELL205206 def source_vars(self) -> dict[str, Any]:
9 unmodified lines
216 cwords = click_split_arg_string(completion_args)217 args = cwords[1:-1] if incomplete else cwords[1:]218 return args, incomplete219188 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 ' '}"222223224def 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 lines
3import subprocess4from enum import Enum5from pathlib import Path67import click7import shellingham89from . import _click10from ._click.globals import get_current_context111213class Shells(str, Enum):14 bash = "bash"15 zsh = "zsh"16 fish = "fish"
62 unmodified lines
79def 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 lines
173 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 lines
186 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 lines
204 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 lines
232 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)238239240def _get_shell_name() -> str | None:241 """Get the current shell name, if available.
13 unmodified lines
modified:typer/_types.py+103 added-10 removed
1from collections.abc import Iterable, Mapping, Sequence2from enum import Enum2from typing import TypeVar3from typing import Any, Generic, TypeVar44import click5from . import _click6from ._click import types7from ._click.shell_completion import CompletionItem89ParamTypeValue = TypeVar("ParamTypeValue")10119class TyperChoice(click.Choice[ParamTypeValue]):12class TyperChoice(types.ParamType, Generic[ParamTypeValue]):13 # Code adapted from Click 8.3.1, with Typer using enum values in normalize_choice14 name = "choice"1516 def __init__(17 self, choices: Iterable[ParamTypeValue], case_sensitive: bool = True18 ) -> None:19 self.choices: Sequence[ParamTypeValue] = tuple(choices)20 self.case_sensitive = case_sensitive2122 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 }3637 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)4142 if ctx is not None and ctx.token_normalize_func is not None:43 normed_value = ctx.token_normalize_func(normed_value)
1 unmodified line
45 if not self.case_sensitive:46 normed_value = normed_value.casefold()4748 return normed_value4950 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 )6061 # Use curly braces to indicate a required argument.62 if param.required and param.param_type_name == "argument":63 return f"{{{choices_str}}}"6465 # Use square braces to indicate an option or optional argument.66 return f"[{choices_str}]"6768 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}"7475 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)8586 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 )9899 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}."103104 def __repr__(self) -> str:105 return f"Choice({list(self.choices)})"106107 def shell_complete(108 self, ctx: _click.Context, param: _click.Parameter, incomplete: str109 ) -> list[CompletionItem]:110 """Complete choices that start with the incomplete value."""111112 str_choices = map(str, self.choices)113114 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))119120 return [CompletionItem(c) for c in matched]
modified:typer/cli.py+11 added-12 removed
2 unmodified lines
3import sys4from pathlib import Path5from typing import Any67import click7import typer8import typer.core10from click import Command, Group, Option912from . import __version__13from .core import HAS_RICH, MARKUP_MODE_KEY10from . import __version__, _click11from ._click import Command12from .core import HAS_RICH, MARKUP_MODE_KEY, TyperGroup, TyperOption1314default_app_names = ("app", "cli", "main")15default_func_names = ("main", "cli", "app")16
12 unmodified lines
2930state = State()313234def maybe_update_state(ctx: click.Context) -> None:33def 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 lines
51 state.func = func_name525354class 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)5860 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)6264 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)6668 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)7071
64 unmodified lines
136 obj = get_typer_from_module(module)137 return obj138139141def maybe_add_run_to_cli(cli: click.Group) -> None:140def 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 lines
149 click_obj.help = "Run the provided Typer app."150 cli.add_command(click_obj)151152154def print_version(ctx: click.Context, param: Option, value: bool) -> None:153def 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 lines
240 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 lines
modified:typer/completion.py+15 added-16 removed
1 unmodified line
2import sys3from collections.abc import MutableMapping4from typing import Any56import click76from . import _click7from ._click import shell_completion8from ._completion_classes import completion_init9from ._completion_shared import Shells, _get_shell_name, get_completion_script, install10from .models import ParamMeta11from .params import Option
14 unmodified lines
26 install_param, show_param = parameters.values()27 return install_param, show_param282930def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:30def 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)404142def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:42def 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_name
8 unmodified lines
55 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)616263# Create a fake command function to extract the completion parameters
38 unmodified lines
102# 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+105def 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 _click113114 if "_" not in instruction:116 click.echo("Invalid completion instruction.", err=True)115 _click.echo("Invalid completion instruction.", err=True)116 return 1117118 # Click 8 changed the order/style of shell instructions from e.g.119 # source_bash to bash_source
2 unmodified lines
122 # shell, _, instruction = instruction.partition("_")123 instruction, _, shell = instruction.partition("_")124 # Typer override end125127 comp_cls = click.shell_completion.get_completion_class(shell)126 comp_cls = shell_completion.get_completion_class(shell)127128 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 1131132 comp = comp_cls(cli, ctx_args, prog_name, complete_var)133134 if instruction == "source":136 click.echo(comp.source())135 _click.echo(comp.source())136 return 0137138 # 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 end143145 click.echo(f'Completion instruction "{instruction}" not supported.', err=True)144 _click.echo(f'Completion instruction "{instruction}" not supported.', err=True)145 return 1
modified:typer/core.py+481 added-92 removed
1import errno2import inspect3import os4import sys5from collections.abc import Callable, MutableMapping, Sequence5from collections.abc import Callable, Mapping, MutableMapping, Sequence6from difflib import get_close_matches7from enum import Enum8from gettext import gettext as _9from typing import (
2 unmodified lines
12 Union,13 cast,14)1516import click17import click.core18import click.formatting19import click.shell_completion20import click.types21import click.utils2216from . import _click17from ._click import types18from ._click.parser import _OptionParser19from ._click.shell_completion import CompletionItem20from ._typing import Literal21from .utils import parse_boolean_env_var2223MarkupMode = Literal["markdown", "rich", None]
6 unmodified lines
30else:31 DEFAULT_MARKUP_MODE = None323337# Copy from click.parser._split_opt34# Copy from _click.parser._split_opt35def _split_opt(opt: str) -> tuple[str, str]:36 first = opt[:1]37 if first.isalnum():38 return "", opt
2 unmodified lines
41 return first, opt[1:]424344def _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 lines
6162 if autocompletion is not None:6364 def compat_autocompletion(68 ctx: click.Context, param: click.core.Parameter, incomplete: str69 ) -> list["click.shell_completion.CompletionItem"]:70 from click.shell_completion import CompletionItem7165 ctx: _click.Context, param: _click.core.Parameter, incomplete: str66 ) -> list[CompletionItem]:67 out = []6869 for c in autocompletion(ctx, [], incomplete):70 if isinstance(c, tuple):
12 unmodified lines
8384def _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 lines
106 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 lines
130 return default_string131132133def _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 lines
148 return default_value149150151def _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 line
158 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:]167168 # 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)173174 if prog_name is None:180 prog_name = click.utils._detect_program_name()175 prog_name = _click.utils._detect_program_name()176177 # Process shell completion requests and exit early.178 self._main_shell_completion(extra, prog_name, complete_var)179
11 unmodified lines
191 # 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 lines
209 # 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 code
4 unmodified lines
227 # 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_utils237238 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)243244250class TyperArgument(click.core.Argument):245class TyperArgument(_click.core.Parameter):246 param_type_name = "argument"247248 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 lines
261 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 # TyperArgument
26 unmodified lines
297 shell_complete=shell_complete,298 )299 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)300301 @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()307308 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 lines
319 default_value=default_value,320 )321322 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)326323 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 lines
379380 help = f"{help} {extra_str}" if help else f"{extra_str}"381 return name, help382379 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 lines
400401 def value_is_missing(self, value: Any) -> bool:402 return _value_is_missing(self, value)403404 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], []420421 def get_usage_pieces(self, ctx: _click.Context) -> list[str]:422 return [self.make_metavar(ctx)]423424 def get_error_hint(self, ctx: _click.Context) -> str:425 return f"'{self.make_metavar(ctx)}'"426427 def add_to_parser(self, parser: _OptionParser, ctx: _click.Context) -> None:428 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)429430401class TyperOption(click.core.Option):431class TyperOption(_click.Parameter):432 param_type_name = "option"433434 _depr_flag_value: bool | None435436 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 lines
449 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 # Option
12 unmodified lines
471 show_envvar: bool = False,472 # Rich settings473 rich_help_panel: str | None = None,474 ):475 if help:476 help = inspect.cleandoc(help)477478 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 )492493 if prompt is True:494 if self.name is None:495 raise TypeError("'name' is required with 'prompt=True'.")496497 prompt_text: str | None = self.name.replace("_", " ").capitalize()498 elif prompt is False:499 prompt_text = None500 else:501 prompt_text = prompt502503 self.prompt = prompt_text504 self.confirmation_prompt = confirmation_prompt505 self.prompt_required = prompt_required506 self.hide_input = hide_input507 self.hidden = hidden508509 # TODO: revisit all of this flag stuff510 if is_flag and type is None:511 self.type: types.ParamType = types.BoolParamType()512513 self.is_flag: bool = bool(is_flag)514 self.is_bool_flag: bool = bool(515 is_flag and isinstance(self.type, types.BoolParamType)516 )517518 if self.is_flag:519 self._depr_flag_value = True520 else:521 self._depr_flag_value = None522523 # 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)527528 self.allow_from_autoenv = allow_from_autoenv529 self.help = help530 self.show_default = show_default531 self.show_choices = show_choices532 self.show_envvar = show_envvar533534 _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)535 self.rich_help_panel = rich_help_panel536537 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 result542543 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 = []550551 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)575576 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 = None581582 return name, opts, secondary_opts583584 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"591592 if self.is_flag:593 action = f"{action}_const"594595 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 )622623 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 None630631 # Calculate the default before prompting anything to lock in the value before632 # attempting any user interaction.633 default = self.get_default(ctx)634635 # 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)649650 # 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_default655656 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 )668669 def value_from_envvar(self, ctx: _click.Context) -> Any:670 rv = self.resolve_envvar_value(ctx)671672 # Absent environment variable or an empty string is interpreted as unset.673 if rv is None:674 return None675676 def resolve_envvar_value(self, ctx: _click.Context) -> str | None:677 rv = super().resolve_envvar_value(ctx)678679 if rv is not None:680 return rv681682 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)689690 if rv:691 return rv692693 return None694695 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).701702 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)706707 # 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.PROMPT717718 return value, source719720 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 lines
731 default_value=default_value,732 )733734 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)738489 def make_metavar(self, ctx: click.Context) -> str:739 def make_metavar(self, ctx: _click.Context) -> str:740 return super().make_metavar(ctx=ctx)741492 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 lines
750751 def _write_opts(opts: Sequence[str]) -> str:752 nonlocal any_prefix_is_slash753504 rv, any_slashes = click.formatting.join_options(opts)754 rv, any_slashes = _click.formatting.join_options(opts)755756 if any_slashes:757 any_prefix_is_slash = True758
49 unmodified lines
808 # Typer override end809 if default_string:810 extra.append(_("default: {default}").format(default=default_string))811562 if isinstance(self.type, click.types._NumberRangeBase):812 if isinstance(self.type, types._NumberRangeBase):813 range_str = self.type._describe_range()814815 if range_str:816 extra.append(range_str)
20 unmodified lines
837 def value_is_missing(self, value: Any) -> bool:838 return _value_is_missing(self, value)839840591def _value_is_missing(param: click.Parameter, value: Any) -> bool:841def _value_is_missing(param: _click.Parameter, value: Any) -> bool:842 if value is None:843 return True844595 # Click 8.3 and beyond596 # if value is UNSET:597 # return True598845 if (param.nargs != 1 or param.multiple) and value == ():846 return True # pragma: no cover847848 return False849850851def _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 lines
869 formatter.write_dl(opts)870871872def _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 lines
889 rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)890 sys.exit(rv)891892647class TyperCommand(click.core.Command):893class 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 lines
927 self.rich_markup_mode: MarkupMode = rich_markup_mode928 self.rich_help_panel = rich_help_panel929930 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)934935 def _main_shell_completion(
25 unmodified lines
961 rich_markup_mode=self.rich_markup_mode,962 **extra,963 )964719 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 lines
977 markup_mode=self.rich_markup_mode,978 )979980735class TyperGroup(click.core.Group):981class 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 = None986987 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_commands10071008 # 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 }10171018 self.commands = cast(MutableMapping[str, _click.Command], commands)1019 self.no_args_is_help = no_args_is_help1020 self.invoke_without_command = invoke_without_command10211022 if subcommand_metavar is None:1023 subcommand_metavar = "COMMAND [ARGS]..."10241025 self.subcommand_metavar = subcommand_metavar1026 self._result_callback = result_callback10271028 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] = cmd10331034 def get_command(self, ctx: _click.Context, cmd_name: str) -> _click.Command | None:1035 return self.commands.get(cmd_name)10361037 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 rv10411042 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)10481049 commands.append((subcommand, cmd))10501051 # allow for 3 times the default spacing1052 if len(commands):1053 limit = formatter.width - 6 - max(len(cmd[0]) for cmd in commands)10541055 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))10601061 if rows:1062 with formatter.section(_("Commands")):1063 formatter.write_dl(rows)10641065 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)10681069 rest = super().parse_args(ctx, args)10701071 if rest:1072 ctx._protected_args, ctx.args = rest[:1], rest[1:]10731074 return ctx.args10751076 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 value10811082 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."))10921093 # Fetch args back out1094 args = [*ctx._protected_args, *ctx.args]1095 ctx.args = []1096 ctx._protected_args = []10971098 # 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))11081109 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 """11161117 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 results11231124 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 lines
1136 _typer_main_shell_completion(1137 self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var1138 )11391140 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_name11451146 # Get the command1147 cmd = self.get_command(ctx, cmd_name)11481149 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)11521153 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:]11581159 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 lines
1192 rich_markup_mode=self.rich_markup_mode,1193 **extra,1194 )1195805 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 lines
1203 ctx=ctx,1204 markup_mode=self.rich_markup_mode,1205 )1206816 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 lines
14from types import TracebackType15from typing import Annotated, Any16from uuid import UUID1718import click18from annotated_doc import Doc19from typer._types import TyperChoice2021from . import _click22from ._click import types23from ._click.globals import get_current_context24from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values25from .completion import get_completion_inspect_parameters26from .core import (27 DEFAULT_MARKUP_MODE,
46 unmodified lines
74 ):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_utils
25 unmodified lines
108 print(line, file=sys.stderr)109 return110111110def get_install_completion_arguments() -> tuple[click.Parameter, click.Parameter]:112def 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_param
1052 unmodified lines
1169 )1170 return group117111721171def get_command(typer_instance: Typer) -> click.Command:1173def 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_callback
1 unmodified line
1179 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_command
101 unmodified lines
1289) -> 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 lines
1331 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 lines
136213631364def 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 lines
1384 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 lines
14861487def 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 lines
1510 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)15161517 update_wrapper(wrapper, callback)1518 return wrapper151915201521def 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_type15261527 elif parameter_info.parser is not None:1527 return click.types.FuncParamType(parameter_info.parser)1528 return types.FuncParamType(parameter_info.parser)15291530 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_type
9 unmodified lines
1571 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 cover
4 unmodified lines
162116221623def 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 # * required
149 unmodified lines
1779 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 cover178417851786def get_param_callback(1787 *,
7 unmodified lines
1795 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 first
6 unmodified lines
1812 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 )18191824 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 lines
1846 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.name
14 unmodified lines
1869 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 )18761881 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 lines
20052006 return 020072008 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
1import inspect2import io3import os4import stat5from collections.abc import Callable, Sequence6from typing import (7 TYPE_CHECKING,8 Any,9 ClassVar,10 Optional,11 TypeVar,12 cast,13)1411import click12import click.shell_completion15from . import _click16from ._click import types17from ._click.shell_completion import CompletionItem1819if TYPE_CHECKING: # pragma: no cover20 from .core import TyperCommand, TyperGroup21 from .main import Typer
5 unmodified lines
2728Required = ...293026class Context(click.Context):31class 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 lines
157158 pass159160156class CallbackParam(click.Parameter):161class 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 lines
290 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 lines
399 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 lines
527 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 lines
644 self.pretty_exceptions_show_locals = pretty_exceptions_show_locals645 self.pretty_exceptions_short = pretty_exceptions_short646647643class TyperPath(click.Path):644 # Overwrite Click's behaviour to be compatible with Typer's autocompletion system648class TyperPath(types.ParamType):649 # Based originally on code from Click 8.3.1650 # Partly rewritten and added an override for shell_complete651652 envvar_list_splitter: ClassVar[str] = os.path.pathsep653654 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_type673674 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"680681 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))693694 return value695696 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 = value703704 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")705706 if not is_dash:707 if self.resolve_path:708 rv = os.path.realpath(rv)709710 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 )720721 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)725726 if not self.dir_okay and stat.S_ISDIR(st.st_mode):727 self.fail(f"{name} {loc} is a directory.", param, ctx)728729 if self.readable and not os.access(rv, os.R_OK):730 self.fail(f"{name} {loc} is not readable.", param, ctx)731732 if self.writable and not os.access(rv, os.W_OK):733 self.fail(f"{name} {loc} is not writable.", param, ctx)734735 return self.coerce_path_result(rv)736737 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
1from collections.abc import Callable2from typing import TYPE_CHECKING, Annotated, Any, overload34import click4from annotated_doc import Doc56from . import _click7from ._click import types8from ._click.shell_completion import CompletionItem9from .models import ArgumentInfo, OptionInfo1011if TYPE_CHECKING: # pragma: no cover10 import click.shell_completion12 pass131415# Overload for Option created with custom type 'parser'16@overload
8 unmodified lines
25 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 lines
90 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 lines
266 ] = 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 lines
344 """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 lines
1015 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 lines
1071 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 lines
1220 ] = 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 lines
1298 """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 lines
modified:typer/rich_utils.py+24 added-21 removed
6 unmodified lines
7from gettext import gettext as _8from os import getenv9from typing import Any, Literal1011import click11from rich import box12from rich.align import Align13from rich.columns import Columns14from rich.console import Console, RenderableType, group
8 unmodified lines
23from rich.theme import Theme24from rich.traceback import Traceback25from typer.models import DeveloperExceptionConfig2627from . import _click28from ._click import types29from .core import TyperArgument, TyperGroup, TyperOption3031# Default styles32STYLE_OPTION = "bold cyan"33STYLE_SWITCH = "bold green"34STYLE_NEGATIVE_OPTION = "bold magenta"
151 unmodified lines
186187@group()188def _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 lines
233234235def _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 lines
350351def _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 lines
379 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 lines
393 # 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 lines
461462def _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 lines
536537538def 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 lines
570 ),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 lines
625 markup_mode=markup_mode,626 console=console,627 )628626 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 lines
676 epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode)677 console.print(Padding(Align(epilogue_text, pad=False), 1))678679677def rich_format_error(self: click.ClickException) -> None:680def rich_format_error(self: _click.ClickException) -> None:681 """Print richly formatted click errors.682683 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 return689690 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())694695 if ctx is not None and ctx.command.get_help_option(ctx) is not None:
63 unmodified lines
modified:typer/testing.py+3 added-2 removed
1from collections.abc import Mapping, Sequence2from typing import IO, Any34from click.testing import CliRunner as ClickCliRunner # noqa5from click.testing import Result4from typer.main import Typer5from typer.main import get_command as _get_command67from ._click.testing import CliRunner as ClickCliRunner # noqa8from ._click.testing import Result91011class CliRunner(ClickCliRunner):12 def invoke( # type: ignore13 self,14 app: Typer,
17 unmodified lines
modified:CITATION.cff+2 added-1 removed
16 unmodified lines
17abstract: >-18 Typer, build great CLIs. Easy to code. Based on Python type hints.19keywords:20 - typer21 - click21 - cli22 - python23license: MIT
modified:mkdocs.yml+1 added
144 unmodified lines
145 - 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.md
79 unmodified lines
modified:pyproject.toml+2 added-2 removed
31 unmodified lines
32 "Programming Language :: Python :: 3.13",33 "Programming Language :: Python :: 3.14",34]35dependencies = [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]41readme = "README.md"4243[project.urls]
144 unmodified lines
188# No need to worry about rich imports in docs189"docs_src/*" = ["TID"]190191[tool.ruff.lint.isort]192known-third-party = ["typer", "click"]192known-third-party = ["typer"]193# For docs_src/subcommands/tutorial003/194known-first-party = ["reigns", "towns", "lands", "items", "users"]195196[tool.ruff.lint.pyupgrade]
34 unmodified lines
modified:README.md+11 added-2 removed
350 unmodified lines
351For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.352353## Dependencies354355**Typer** stands on the shoulders of giants. It has three required dependencies:355**Typer** requires only a few dependencies (most are tiny):356357* [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.361362### Click code363364Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.365366Since 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.367368Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.369370### `typer-slim`371372There 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 lines
modified:uv.lock+2 added-2 removed
1785 unmodified lines
1786name = "typer"1787source = { editable = "." }1788dependencies = [1789 { name = "annotated-doc" },1790 { name = "click" },1790 { name = "colorama", marker = "sys_platform == 'win32'" },1791 { name = "rich" },1792 { name = "shellingham" },1793]1794
54 unmodified lines
18491850[package.metadata]1851requires-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