diff --git a/.cache/pip/http-v2/a/3/2/f/7/a32f793a951b4bb55e15bb0126f9c9127aab8cec4ba5607016d8841e.body b/.cache/pip/http-v2/a/3/2/f/7/a32f793a951b4bb55e15bb0126f9c9127aab8cec4ba5607016d8841e.body new file mode 100644 index 0000000000000000000000000000000000000000..724816507436e2aa7966d15e9a19a4ea59450471 --- /dev/null +++ b/.cache/pip/http-v2/a/3/2/f/7/a32f793a951b4bb55e15bb0126f9c9127aab8cec4ba5607016d8841e.body @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:149f7d84afca659d1a97e39a4778794a2f83bf344c5ee5134e09995086cc2392 +size 4988768 diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/METADATA b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8fc14ea2b68c0df97b52da5802a44e0083973d26 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/METADATA @@ -0,0 +1,412 @@ +Metadata-Version: 2.4 +Name: typer +Version: 0.24.1 +Summary: Typer, build great CLIs. Easy to code. Based on Python type hints. +Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= +License-Expression: MIT +License-File: LICENSE +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python +Classifier: Topic :: Software Development :: Libraries :: Application Frameworks +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development +Classifier: Typing :: Typed +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Project-URL: Homepage, https://github.com/fastapi/typer +Project-URL: Documentation, https://typer.tiangolo.com +Project-URL: Repository, https://github.com/fastapi/typer +Project-URL: Issues, https://github.com/fastapi/typer/issues +Project-URL: Changelog, https://typer.tiangolo.com/release-notes/ +Requires-Python: >=3.10 +Requires-Dist: click>=8.2.1 +Requires-Dist: shellingham>=1.3.0 +Requires-Dist: rich>=12.3.0 +Requires-Dist: annotated-doc>=0.0.2 +Description-Content-Type: text/markdown + +

+ Typer + +

+

+ Typer, build great CLIs. Easy to code. Based on Python type hints. +

+

+ + Test + + + Publish + + + Coverage + + Package version + +

+ +--- + +**Documentation**: https://typer.tiangolo.com + +**Source Code**: https://github.com/fastapi/typer + +--- + +Typer is a library for building CLI applications that users will **love using** and developers will **love creating**. Based on Python type hints. + +It's also a command line tool to run scripts, automatically converting them to CLI applications. + +The key features are: + +* **Intuitive to write**: Great editor support. Completion everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs. +* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells. +* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs. +* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**. +* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments. +* **Run scripts**: Typer includes a `typer` command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally. + +## 2026 February - Typer developer survey + +Help us define Typer's future by filling the Typer developer survey. ✨ + +## FastAPI of CLIs + +**Typer** is FastAPI's little sibling, it's the FastAPI of CLIs. + +## Installation + +Create and activate a virtual environment and then install **Typer**: + +
+ +```console +$ pip install typer +---> 100% +Successfully installed typer rich shellingham +``` + +
+ +## Example + +### The absolute minimum + +* Create a file `main.py` with: + +```Python +def main(name: str): + print(f"Hello {name}") +``` + +This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application. + +### Run it + +Run your application with the `typer` command: + +
+ +```console +// Run your application +$ typer main.py run + +// You get a nice error, you are missing NAME +Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME +Try 'typer [PATH_OR_MODULE] run --help' for help. +╭─ Error ───────────────────────────────────────────╮ +│ Missing argument 'NAME'. │ +╰───────────────────────────────────────────────────╯ + + +// You get a --help for free +$ typer main.py run --help + +Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME + +Run the provided Typer app. + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] | +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --help Show this message and exit. │ +╰───────────────────────────────────────────────────╯ + +// Now pass the NAME argument +$ typer main.py run Camila + +Hello Camila + +// It works! 🎉 +``` + +
+ +This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts. + +**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command. + +## Use Typer in your code + +Now let's start using Typer in your own code, update `main.py` with: + +```Python +import typer + + +def main(name: str): + print(f"Hello {name}") + + +if __name__ == "__main__": + typer.run(main) +``` + +Now you could run it with Python directly: + +
+ +```console +// Run your application +$ python main.py + +// You get a nice error, you are missing NAME +Usage: main.py [OPTIONS] NAME +Try 'main.py --help' for help. +╭─ Error ───────────────────────────────────────────╮ +│ Missing argument 'NAME'. │ +╰───────────────────────────────────────────────────╯ + + +// You get a --help for free +$ python main.py --help + +Usage: main.py [OPTIONS] NAME + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] | +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --help Show this message and exit. │ +╰───────────────────────────────────────────────────╯ + +// Now pass the NAME argument +$ python main.py Camila + +Hello Camila + +// It works! 🎉 +``` + +
+ +**Note**: you can also call this same script with the `typer` command, but you don't need to. + +## Example upgrade + +This was the simplest example possible. + +Now let's see one a bit more complex. + +### An example with two subcommands + +Modify the file `main.py`. + +Create a `typer.Typer()` app, and create two subcommands with their parameters. + +```Python hl_lines="3 6 11 20" +import typer + +app = typer.Typer() + + +@app.command() +def hello(name: str): + print(f"Hello {name}") + + +@app.command() +def goodbye(name: str, formal: bool = False): + if formal: + print(f"Goodbye Ms. {name}. Have a good day.") + else: + print(f"Bye {name}!") + + +if __name__ == "__main__": + app() +``` + +And that will: + +* Explicitly create a `typer.Typer` app. + * The previous `typer.run` actually creates one implicitly for you. +* Add two subcommands with `@app.command()`. +* Execute the `app()` itself, as if it was a function (instead of `typer.run`). + +### Run the upgraded example + +Check the new help: + +
+ +```console +$ python main.py --help + + Usage: main.py [OPTIONS] COMMAND [ARGS]... + +╭─ Options ─────────────────────────────────────────╮ +│ --install-completion Install completion │ +│ for the current │ +│ shell. │ +│ --show-completion Show completion for │ +│ the current shell, │ +│ to copy it or │ +│ customize the │ +│ installation. │ +│ --help Show this message │ +│ and exit. │ +╰───────────────────────────────────────────────────╯ +╭─ Commands ────────────────────────────────────────╮ +│ goodbye │ +│ hello │ +╰───────────────────────────────────────────────────╯ + +// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion + +// You have 2 subcommands (the 2 functions): goodbye and hello +``` + +
+ +Now check the help for the `hello` command: + +
+ +```console +$ python main.py hello --help + + Usage: main.py hello [OPTIONS] NAME + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] │ +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --help Show this message and exit. │ +╰───────────────────────────────────────────────────╯ +``` + +
+ +And now check the help for the `goodbye` command: + +
+ +```console +$ python main.py goodbye --help + + Usage: main.py goodbye [OPTIONS] NAME + +╭─ Arguments ───────────────────────────────────────╮ +│ * name TEXT [default: None] [required] │ +╰───────────────────────────────────────────────────╯ +╭─ Options ─────────────────────────────────────────╮ +│ --formal --no-formal [default: no-formal] │ +│ --help Show this message │ +│ and exit. │ +╰───────────────────────────────────────────────────╯ + +// Automatic --formal and --no-formal for the bool option 🎉 +``` + +
+ +Now you can try out the new command line application: + +
+ +```console +// Use it with the hello command + +$ python main.py hello Camila + +Hello Camila + +// And with the goodbye command + +$ python main.py goodbye Camila + +Bye Camila! + +// And with --formal + +$ python main.py goodbye --formal Camila + +Goodbye Ms. Camila. Have a good day. +``` + +
+ +**Note**: If your app only has one command, by default the command name is **omitted** in usage: `python main.py Camila`. However, when there are multiple commands, you must **explicitly include the command name**: `python main.py hello Camila`. See [One or Multiple Commands](https://typer.tiangolo.com/tutorial/commands/one-or-multiple/) for more details. + +### Recap + +In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters. + +You do that with standard modern Python types. + +You don't have to learn a new syntax, the methods or classes of a specific library, etc. + +Just standard **Python**. + +For example, for an `int`: + +```Python +total: int +``` + +or for a `bool` flag: + +```Python +force: bool +``` + +And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc. + +**You get**: great editor support, including **completion** and **type checks** everywhere. + +**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the `typer` command. + +For a more complete example including more features, see the Tutorial - User Guide. + +## Dependencies + +**Typer** stands on the shoulders of giants. It has three required dependencies: + +* Click: a popular tool for building CLIs in Python. Typer is based on it. +* rich: to show nicely formatted errors automatically. +* shellingham: to automatically detect the current shell when installing completion. + +### `typer-slim` + +There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command. + +However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer. + +If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`. + +## License + +This project is licensed under the terms of the MIT license. diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/RECORD b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..52219d571f39b0935f47864ba03515bb96fb2f46 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/RECORD @@ -0,0 +1,22 @@ +typer-0.24.1.dist-info/METADATA,sha256=V4OWoWjBhPNcoIaOxhr1cszo69nePKOHMRXERkMscKs,16057 +typer-0.24.1.dist-info/WHEEL,sha256=Wb0ASbVj8JvWHpOiIpPi7ucfIgJeCi__PzivviEAQFc,90 +typer-0.24.1.dist-info/entry_points.txt,sha256=YO13ByiqWeuas9V0JADLUARZFUe_cwU_7wmTNvxBYQ8,57 +typer-0.24.1.dist-info/licenses/LICENSE,sha256=WJks68-N-25AxOIRLtEhJsJDZm3KORKj14t-ysSFnUk,1086 +typer/__init__.py,sha256=WOelHJu4PW0hk9nfjEX0Qxssb58NCh1km_Xq5LY_33s,1596 +typer/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30 +typer/_completion_classes.py,sha256=R9v4D8pJ_-n8fLOuyxrRSu7sP5lpXIy5fsLUW8zwsDU,7039 +typer/_completion_shared.py,sha256=-uhCUIMc2S1ywdB-fBSSccH70mIBEsVTxHomcmy-klE,9129 +typer/_types.py,sha256=0lcBDLcsxqr1sxTsqObj_u0Dfa37lWJYUY4PNkX4QlA,974 +typer/_typing.py,sha256=QOw5o-B2L--C3ly2DQH6aUwag6x5brV5FhVaBZ5gzMg,1727 +typer/cli.py,sha256=icRbazvdRdbYeaidPZOmJDOzrP3RAa7vj2INVV9Zb8Q,10183 +typer/colors.py,sha256=e42j8uB520hLpX5C_0fiR3OOoIFMbhO3ADZvv6hlAV8,430 +typer/completion.py,sha256=FRTR9hP_IPdJp-4GXPOq0btXo5SvgAtLVfS3ZkAMpgQ,4793 +typer/core.py,sha256=O5NywSwHPyYbLhZkPYSfwIj7Za2hPnoPP4xPXRa97a0,27947 +typer/main.py,sha256=xyNex-QfGUi-enu9j9rl-_wofApxs5VwdpCthAUAAkk,69005 +typer/models.py,sha256=OwPG3MAXiUD5ih3p8eNVciXUsL07UIJfNWy3JiNpDfg,19843 +typer/params.py,sha256=AovViRtl-VvUIXnmKKpnxoWK9_gHUbyQgXxxv3h_7lI,59713 +typer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +typer/rich_utils.py,sha256=RTyeoxwz16ZZXYbwoEixB_LSEnqpoStG_TGCRTz6zFQ,25424 +typer/testing.py,sha256=-ovLNjUNNEFCJoau-41iTJIobsjPbqyTrRq7-8ac4z4,871 +typer/utils.py,sha256=wnJ1DWXBFMnxLHaMN_HDYntxLRby0K-rux63aokHInI,7599 +typer-0.24.1.dist-info/RECORD,, diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/WHEEL b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..18c430c1f6411c0532096b13de4384ab50a79abd --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: pdm-backend (2.4.7) +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/entry_points.txt b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca44c05a071b87fe02a3724bd895838305fe4e5d --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/entry_points.txt @@ -0,0 +1,5 @@ +[console_scripts] +typer = typer.cli:main + +[gui_scripts] + diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/licenses/LICENSE b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a7694736cf37716aafec14b24aa8d6316ebe07a3 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Sebastián Ramírez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__init__.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0921c06c9c0eddcb32ef016236ea98c2a42375 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__init__.py @@ -0,0 +1,39 @@ +"""Typer, build great CLIs. Easy to code. Based on Python type hints.""" + +__version__ = "0.24.1" + +from shutil import get_terminal_size as get_terminal_size + +from click.exceptions import Abort as Abort +from click.exceptions import BadParameter as BadParameter +from click.exceptions import Exit as Exit +from click.termui import clear as clear +from click.termui import confirm as confirm +from click.termui import echo_via_pager as echo_via_pager +from click.termui import edit as edit +from click.termui import getchar as getchar +from click.termui import pause as pause +from click.termui import progressbar as progressbar +from click.termui import prompt as prompt +from click.termui import secho as secho +from click.termui import style as style +from click.termui import unstyle as unstyle +from click.utils import echo as echo +from click.utils import format_filename as format_filename +from click.utils import get_app_dir as get_app_dir +from click.utils import get_binary_stream as get_binary_stream +from click.utils import get_text_stream as get_text_stream +from click.utils import open_file as open_file + +from . import colors as colors +from .main import Typer as Typer +from .main import launch as launch +from .main import run as run +from .models import CallbackParam as CallbackParam +from .models import Context as Context +from .models import FileBinaryRead as FileBinaryRead +from .models import FileBinaryWrite as FileBinaryWrite +from .models import FileText as FileText +from .models import FileTextWrite as FileTextWrite +from .params import Argument as Argument +from .params import Option as Option diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__main__.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e28416e104515e90fca4b69cc60d0c61fd15d61 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_classes.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..8548fb4d6a3e2e274811b0935276e1c0e6f2a9a0 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_classes.py @@ -0,0 +1,199 @@ +import importlib.util +import os +import re +import sys +from typing import Any + +import click +import click.parser +import click.shell_completion +from click.shell_completion import split_arg_string as click_split_arg_string + +from ._completion_shared import ( + COMPLETION_SCRIPT_BASH, + COMPLETION_SCRIPT_FISH, + COMPLETION_SCRIPT_POWER_SHELL, + COMPLETION_SCRIPT_ZSH, + Shells, +) + + +def _sanitize_help_text(text: str) -> str: + """Sanitizes the help text by removing rich tags""" + if not importlib.util.find_spec("rich"): + return text + from . import rich_utils + + return rich_utils.rich_render_text(text) + + +class BashComplete(click.shell_completion.BashComplete): + name = Shells.bash.value + source_template = COMPLETION_SCRIPT_BASH + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + cwords = click_split_arg_string(os.environ["COMP_WORDS"]) + cword = int(os.environ["COMP_CWORD"]) + args = cwords[1:cword] + + try: + incomplete = cwords[cword] + except IndexError: + incomplete = "" + + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + # TODO: Explore replicating the new behavior from Click, with item types and + # triggering completion for files and directories + # return f"{item.type},{item.value}" + return f"{item.value}" + + def complete(self) -> str: + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + out = [self.format_completion(item) for item in completions] + return "\n".join(out) + + +class ZshComplete(click.shell_completion.ZshComplete): + name = Shells.zsh.value + source_template = COMPLETION_SCRIPT_ZSH + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") + cwords = click_split_arg_string(completion_args) + args = cwords[1:] + if args and not completion_args.endswith(" "): + incomplete = args[-1] + args = args[:-1] + else: + incomplete = "" + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + def escape(s: str) -> str: + return ( + s.replace('"', '""') + .replace("'", "''") + .replace("$", "\\$") + .replace("`", "\\`") + .replace(":", r"\\:") + ) + + # TODO: Explore replicating the new behavior from Click, pay attention to + # the difference with and without escape + # return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}" + if item.help: + return f'"{escape(item.value)}":"{_sanitize_help_text(escape(item.help))}"' + else: + return f'"{escape(item.value)}"' + + def complete(self) -> str: + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + res = [self.format_completion(item) for item in completions] + if res: + args_str = "\n".join(res) + return f"_arguments '*: :(({args_str}))'" + else: + return "_files" + + +class FishComplete(click.shell_completion.FishComplete): + name = Shells.fish.value + source_template = COMPLETION_SCRIPT_FISH + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") + cwords = click_split_arg_string(completion_args) + args = cwords[1:] + if args and not completion_args.endswith(" "): + incomplete = args[-1] + args = args[:-1] + else: + incomplete = "" + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + # TODO: Explore replicating the new behavior from Click, pay attention to + # the difference with and without formatted help + # if item.help: + # return f"{item.type},{item.value}\t{item.help}" + + # return f"{item.type},{item.value} + if item.help: + formatted_help = re.sub(r"\s", " ", item.help) + return f"{item.value}\t{_sanitize_help_text(formatted_help)}" + else: + return f"{item.value}" + + def complete(self) -> str: + complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "") + args, incomplete = self.get_completion_args() + completions = self.get_completions(args, incomplete) + show_args = [self.format_completion(item) for item in completions] + if complete_action == "get-args": + if show_args: + return "\n".join(show_args) + elif complete_action == "is-args": + if show_args: + # Activate complete args (no files) + sys.exit(0) + else: + # Deactivate complete args (allow files) + sys.exit(1) + return "" # pragma: no cover + + +class PowerShellComplete(click.shell_completion.ShellComplete): + name = Shells.powershell.value + source_template = COMPLETION_SCRIPT_POWER_SHELL + + def source_vars(self) -> dict[str, Any]: + return { + "complete_func": self.func_name, + "autocomplete_var": self.complete_var, + "prog_name": self.prog_name, + } + + def get_completion_args(self) -> tuple[list[str], str]: + completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "") + incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "") + cwords = click_split_arg_string(completion_args) + args = cwords[1:-1] if incomplete else cwords[1:] + return args, incomplete + + def format_completion(self, item: click.shell_completion.CompletionItem) -> str: + return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}" + + +def completion_init() -> None: + click.shell_completion.add_completion_class(BashComplete, Shells.bash.value) + click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value) + click.shell_completion.add_completion_class(FishComplete, Shells.fish.value) + click.shell_completion.add_completion_class( + PowerShellComplete, Shells.powershell.value + ) + click.shell_completion.add_completion_class(PowerShellComplete, Shells.pwsh.value) diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_shared.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..5a81dcf68cddda410becd393e5cf0d7e9e83042e --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_shared.py @@ -0,0 +1,252 @@ +import os +import re +import subprocess +from enum import Enum +from pathlib import Path + +import click +import shellingham + + +class Shells(str, Enum): + bash = "bash" + zsh = "zsh" + fish = "fish" + powershell = "powershell" + pwsh = "pwsh" + + +COMPLETION_SCRIPT_BASH = """ +%(complete_func)s() { + local IFS=$'\n' + COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\ + COMP_CWORD=$COMP_CWORD \\ + %(autocomplete_var)s=complete_bash $1 ) ) + return 0 +} + +complete -o default -F %(complete_func)s %(prog_name)s +""" + +COMPLETION_SCRIPT_ZSH = """ +#compdef %(prog_name)s + +%(complete_func)s() { + eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s) +} + +compdef %(complete_func)s %(prog_name)s +""" + +COMPLETION_SCRIPT_FISH = 'complete --command %(prog_name)s --no-files --arguments "(env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=get-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s)" --condition "env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=is-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s"' + +COMPLETION_SCRIPT_POWER_SHELL = """ +Import-Module PSReadLine +Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete +$scriptblock = { + param($wordToComplete, $commandAst, $cursorPosition) + $Env:%(autocomplete_var)s = "complete_powershell" + $Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString() + $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete + %(prog_name)s | ForEach-Object { + $commandArray = $_ -Split ":::" + $command = $commandArray[0] + $helpString = $commandArray[1] + [System.Management.Automation.CompletionResult]::new( + $command, $command, 'ParameterValue', $helpString) + } + $Env:%(autocomplete_var)s = "" + $Env:_TYPER_COMPLETE_ARGS = "" + $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = "" +} +Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock +""" + +_completion_scripts = { + "bash": COMPLETION_SCRIPT_BASH, + "zsh": COMPLETION_SCRIPT_ZSH, + "fish": COMPLETION_SCRIPT_FISH, + "powershell": COMPLETION_SCRIPT_POWER_SHELL, + "pwsh": COMPLETION_SCRIPT_POWER_SHELL, +} + +# TODO: Probably refactor this, copied from Click 7.x +_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]") + + +def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str: + cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_")) + script = _completion_scripts.get(shell) + if script is None: + click.echo(f"Shell {shell} not supported.", err=True) + raise click.exceptions.Exit(1) + return ( + script + % { + "complete_func": f"_{cf_name}_completion", + "prog_name": prog_name, + "autocomplete_var": complete_var, + } + ).strip() + + +def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path: + # Ref: https://github.com/scop/bash-completion#faq + # It seems bash-completion is the official completion system for bash: + # Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html + # But installing in the locations from the docs doesn't seem to have effect + completion_path = Path.home() / ".bash_completions" / f"{prog_name}.sh" + rc_path = Path.home() / ".bashrc" + rc_path.parent.mkdir(parents=True, exist_ok=True) + rc_content = "" + if rc_path.is_file(): + rc_content = rc_path.read_text() + completion_init_lines = [f"source '{completion_path}'"] + for line in completion_init_lines: + if line not in rc_content: # pragma: no cover + rc_content += f"\n{line}" + rc_content += "\n" + rc_path.write_text(rc_content) + # Install completion + completion_path.parent.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + completion_path.write_text(script_content) + return completion_path + + +def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path: + # Setup Zsh and load ~/.zfunc + zshrc_path = Path.home() / ".zshrc" + zshrc_path.parent.mkdir(parents=True, exist_ok=True) + zshrc_content = "" + if zshrc_path.is_file(): + zshrc_content = zshrc_path.read_text() + completion_line = "fpath+=~/.zfunc; autoload -Uz compinit; compinit" + if completion_line not in zshrc_content: + zshrc_content += f"\n{completion_line}\n" + style_line = "zstyle ':completion:*' menu select" + # TODO: consider setting the style only for the current program + # style_line = f"zstyle ':completion:*:*:{prog_name}:*' menu select" + # Install zstyle completion config only if the user doesn't have a customization + if "zstyle" not in zshrc_content: + zshrc_content += f"\n{style_line}\n" + zshrc_content = f"{zshrc_content.strip()}\n" + zshrc_path.write_text(zshrc_content) + # Install completion under ~/.zfunc/ + path_obj = Path.home() / f".zfunc/_{prog_name}" + path_obj.parent.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + path_obj.write_text(script_content) + return path_obj + + +def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path: + path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish" + parent_dir: Path = path_obj.parent + parent_dir.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + path_obj.write_text(f"{script_content}\n") + return path_obj + + +def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path: + subprocess.run( + [ + shell, + "-Command", + "Set-ExecutionPolicy", + "Unrestricted", + "-Scope", + "CurrentUser", + ] + ) + result = subprocess.run( + [shell, "-NoProfile", "-Command", "echo", "$profile"], + check=True, + stdout=subprocess.PIPE, + ) + if result.returncode != 0: # pragma: no cover + click.echo("Couldn't get PowerShell user profile", err=True) + raise click.exceptions.Exit(result.returncode) + path_str = "" + if isinstance(result.stdout, str): # pragma: no cover + path_str = result.stdout + if isinstance(result.stdout, bytes): + for encoding in ["windows-1252", "utf8", "cp850"]: + try: + path_str = result.stdout.decode(encoding) + break + except UnicodeDecodeError: # pragma: no cover + pass + if not path_str: # pragma: no cover + click.echo("Couldn't decode the path automatically", err=True) + raise click.exceptions.Exit(1) + path_obj = Path(path_str.strip()) + parent_dir: Path = path_obj.parent + parent_dir.mkdir(parents=True, exist_ok=True) + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + with path_obj.open(mode="a") as f: + f.write(f"{script_content}\n") + return path_obj + + +def install( + shell: str | None = None, + prog_name: str | None = None, + complete_var: str | None = None, +) -> tuple[str, Path]: + prog_name = prog_name or click.get_current_context().find_root().info_name + assert prog_name + if complete_var is None: + complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper()) + test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION") + if shell is None and not test_disable_detection: + shell = _get_shell_name() + if shell == "bash": + installed_path = install_bash( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + elif shell == "zsh": + installed_path = install_zsh( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + elif shell == "fish": + installed_path = install_fish( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + elif shell in {"powershell", "pwsh"}: + installed_path = install_powershell( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + return shell, installed_path + else: + click.echo(f"Shell {shell} is not supported.") + raise click.exceptions.Exit(1) + + +def _get_shell_name() -> str | None: + """Get the current shell name, if available. + + The name will always be lowercase. If the shell cannot be detected, None is + returned. + """ + name: str | None # N.B. shellingham is untyped + try: + # N.B. detect_shell returns a tuple of (shell name, shell command). + # We only need the name. + name, _cmd = shellingham.detect_shell() # noqa: TID251 + except shellingham.ShellDetectionFailure: # pragma: no cover + name = None + + return name diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_types.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..dc9fc63220d91b5c7ecc16170bb9de7afb135fb4 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_types.py @@ -0,0 +1,27 @@ +from enum import Enum +from typing import TypeVar + +import click + +ParamTypeValue = TypeVar("ParamTypeValue") + + +class TyperChoice(click.Choice[ParamTypeValue]): + def normalize_choice( + self, choice: ParamTypeValue, ctx: click.Context | None + ) -> str: + # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class + # to support enums, but it uses the enum names, while Typer has always used the + # enum values. + # This class overrides that method to maintain the previous behavior. + # In Click: + # normed_value = choice.name if isinstance(choice, Enum) else str(choice) + normed_value = str(choice.value) if isinstance(choice, Enum) else str(choice) + + if ctx is not None and ctx.token_normalize_func is not None: + normed_value = ctx.token_normalize_func(normed_value) + + if not self.case_sensitive: + normed_value = normed_value.casefold() + + return normed_value diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_typing.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..218f674c2220589738656294fdd8ec243965376f --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_typing.py @@ -0,0 +1,73 @@ +# Copied from pydantic 1.9.2 (the latest version to support python 3.6.) +# https://github.com/pydantic/pydantic/blob/v1.9.2/pydantic/typing.py +# Reduced drastically to only include Typer-specific 3.9+ functionality +# mypy: ignore-errors + +import types +from collections.abc import Callable +from typing import ( + Annotated, + Any, + Literal, + Union, + get_args, + get_origin, + get_type_hints, +) + + +def is_union(tp: type[Any] | None) -> bool: + return tp is Union or tp is types.UnionType # noqa: E721 + + +__all__ = ( + "NoneType", + "is_none_type", + "is_callable_type", + "is_literal_type", + "all_literal_values", + "is_union", + "Annotated", + "Literal", + "get_args", + "get_origin", + "get_type_hints", +) + + +NoneType = None.__class__ + + +NONE_TYPES: tuple[Any, Any, Any] = (None, NoneType, Literal[None]) + + +def is_none_type(type_: Any) -> bool: + for none_type in NONE_TYPES: + if type_ is none_type: + return True + return False + + +def is_callable_type(type_: type[Any]) -> bool: + return type_ is Callable or get_origin(type_) is Callable + + +def is_literal_type(type_: type[Any]) -> bool: + return get_origin(type_) is Literal + + +def literal_values(type_: type[Any]) -> tuple[Any, ...]: + return get_args(type_) + + +def all_literal_values(type_: type[Any]) -> tuple[Any, ...]: + """ + This method is used to retrieve all Literal values as + Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586) + e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]` + """ + if not is_literal_type(type_): + return (type_,) + + values = literal_values(type_) + return tuple(x for value in values for x in all_literal_values(value)) diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/cli.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4356f8bdafcd5fc9e8de6c0c95f6f8f4f8bda1 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/cli.py @@ -0,0 +1,317 @@ +import importlib.util +import re +import sys +from pathlib import Path +from typing import Any + +import click +import typer +import typer.core +from click import Command, Group, Option + +from . import __version__ +from .core import HAS_RICH, MARKUP_MODE_KEY + +default_app_names = ("app", "cli", "main") +default_func_names = ("main", "cli", "app") + +app = typer.Typer() +utils_app = typer.Typer(help="Extra utility commands for Typer apps.") +app.add_typer(utils_app, name="utils") + + +class State: + def __init__(self) -> None: + self.app: str | None = None + self.func: str | None = None + self.file: Path | None = None + self.module: str | None = None + + +state = State() + + +def maybe_update_state(ctx: click.Context) -> None: + path_or_module = ctx.params.get("path_or_module") + if path_or_module: + file_path = Path(path_or_module) + if file_path.exists() and file_path.is_file(): + state.file = file_path + else: + if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module): + typer.echo( + f"Not a valid file or Python module: {path_or_module}", err=True + ) + sys.exit(1) + state.module = path_or_module + app_name = ctx.params.get("app") + if app_name: + state.app = app_name + func_name = ctx.params.get("func") + if func_name: + state.func = func_name + + +class TyperCLIGroup(typer.core.TyperGroup): + def list_commands(self, ctx: click.Context) -> list[str]: + self.maybe_add_run(ctx) + return super().list_commands(ctx) + + def get_command(self, ctx: click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override] + self.maybe_add_run(ctx) + return super().get_command(ctx, name) + + def invoke(self, ctx: click.Context) -> Any: + self.maybe_add_run(ctx) + return super().invoke(ctx) + + def maybe_add_run(self, ctx: click.Context) -> None: + maybe_update_state(ctx) + maybe_add_run_to_cli(self) + + +def get_typer_from_module(module: Any) -> typer.Typer | None: + # Try to get defined app + if state.app: + obj = getattr(module, state.app, None) + if not isinstance(obj, typer.Typer): + typer.echo(f"Not a Typer object: --app {state.app}", err=True) + sys.exit(1) + return obj + # Try to get defined function + if state.func: + func_obj = getattr(module, state.func, None) + if not callable(func_obj): + typer.echo(f"Not a function: --func {state.func}", err=True) + raise typer.Exit(1) + sub_app = typer.Typer() + sub_app.command()(func_obj) + return sub_app + # Iterate and get a default object to use as CLI + local_names = dir(module) + local_names_set = set(local_names) + # Try to get a default Typer app + for name in default_app_names: + if name in local_names_set: + obj = getattr(module, name, None) + if isinstance(obj, typer.Typer): + return obj + # Try to get any Typer app + for name in local_names_set - set(default_app_names): + obj = getattr(module, name) + if isinstance(obj, typer.Typer): + return obj + # Try to get a default function + for func_name in default_func_names: + func_obj = getattr(module, func_name, None) + if callable(func_obj): + sub_app = typer.Typer() + sub_app.command()(func_obj) + return sub_app + # Try to get any func app + for func_name in local_names_set - set(default_func_names): + func_obj = getattr(module, func_name) + if callable(func_obj): + sub_app = typer.Typer() + sub_app.command()(func_obj) + return sub_app + return None + + +def get_typer_from_state() -> typer.Typer | None: + spec = None + if state.file: + module_name = state.file.name + spec = importlib.util.spec_from_file_location(module_name, str(state.file)) + elif state.module: + spec = importlib.util.find_spec(state.module) + if spec is None: + if state.file: + typer.echo(f"Could not import as Python file: {state.file}", err=True) + else: + typer.echo(f"Could not import as Python module: {state.module}", err=True) + sys.exit(1) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) # type: ignore + obj = get_typer_from_module(module) + return obj + + +def maybe_add_run_to_cli(cli: click.Group) -> None: + if "run" not in cli.commands: + if state.file or state.module: + obj = get_typer_from_state() + if obj: + obj._add_completion = False + click_obj = typer.main.get_command(obj) + click_obj.name = "run" + if not click_obj.help: + click_obj.help = "Run the provided Typer app." + cli.add_command(click_obj) + + +def print_version(ctx: click.Context, param: Option, value: bool) -> None: + if not value or ctx.resilient_parsing: + return + typer.echo(f"Typer version: {__version__}") + raise typer.Exit() + + +@app.callback(cls=TyperCLIGroup, no_args_is_help=True) +def callback( + ctx: typer.Context, + *, + path_or_module: str = typer.Argument(None), + app: str = typer.Option(None, help="The typer app object/variable to use."), + func: str = typer.Option(None, help="The function to convert to Typer."), + version: bool = typer.Option( + False, + "--version", + help="Print version and exit.", + callback=print_version, + ), +) -> None: + """ + Run Typer scripts with completion, without having to create a package. + + You probably want to install completion for the typer command: + + $ typer --install-completion + + https://typer.tiangolo.com/ + """ + maybe_update_state(ctx) + + +def get_docs_for_click( + *, + obj: Command, + ctx: typer.Context, + indent: int = 0, + name: str = "", + call_prefix: str = "", + title: str | None = None, +) -> str: + docs = "#" * (1 + indent) + command_name = name or obj.name + if call_prefix: + command_name = f"{call_prefix} {command_name}" + if not title: + title = f"`{command_name}`" if command_name else "CLI" + docs += f" {title}\n\n" + rich_markup_mode = None + if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): + rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) + to_parse: bool = bool(HAS_RICH and (rich_markup_mode == "rich")) + if obj.help: + docs += f"{_parse_html(to_parse, obj.help)}\n\n" + usage_pieces = obj.collect_usage_pieces(ctx) + if usage_pieces: + docs += "**Usage**:\n\n" + docs += "```console\n" + docs += "$ " + if command_name: + docs += f"{command_name} " + docs += f"{' '.join(usage_pieces)}\n" + docs += "```\n\n" + args = [] + opts = [] + for param in obj.get_params(ctx): + rv = param.get_help_record(ctx) + if rv is not None: + if param.param_type_name == "argument": + args.append(rv) + elif param.param_type_name == "option": + opts.append(rv) + if args: + docs += "**Arguments**:\n\n" + for arg_name, arg_help in args: + docs += f"* `{arg_name}`" + if arg_help: + docs += f": {_parse_html(to_parse, arg_help)}" + docs += "\n" + docs += "\n" + if opts: + docs += "**Options**:\n\n" + for opt_name, opt_help in opts: + docs += f"* `{opt_name}`" + if opt_help: + docs += f": {_parse_html(to_parse, opt_help)}" + docs += "\n" + docs += "\n" + if obj.epilog: + docs += f"{obj.epilog}\n\n" + if isinstance(obj, Group): + group = obj + commands = group.list_commands(ctx) + if commands: + docs += "**Commands**:\n\n" + for command in commands: + command_obj = group.get_command(ctx, command) + assert command_obj + docs += f"* `{command_obj.name}`" + command_help = command_obj.get_short_help_str() + if command_help: + docs += f": {_parse_html(to_parse, command_help)}" + docs += "\n" + docs += "\n" + for command in commands: + command_obj = group.get_command(ctx, command) + assert command_obj + use_prefix = "" + if command_name: + use_prefix += f"{command_name}" + docs += get_docs_for_click( + obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix + ) + return docs + + +def _parse_html(to_parse: bool, input_text: str) -> str: + if not to_parse: + return input_text + from . import rich_utils + + return rich_utils.rich_to_html(input_text) + + +@utils_app.command() +def docs( + ctx: typer.Context, + name: str = typer.Option("", help="The name of the CLI program to use in docs."), + output: Path | None = typer.Option( + None, + help="An output file to write docs to, like README.md.", + file_okay=True, + dir_okay=False, + ), + title: str | None = typer.Option( + None, + help="The title for the documentation page. If not provided, the name of " + "the program is used.", + ), +) -> None: + """ + Generate Markdown docs for a Typer app. + """ + typer_obj = get_typer_from_state() + if not typer_obj: + typer.echo("No Typer app found", err=True) + raise typer.Abort() + if hasattr(typer_obj, "rich_markup_mode"): + if not hasattr(ctx, "obj") or ctx.obj is None: + ctx.ensure_object(dict) + if isinstance(ctx.obj, dict): + ctx.obj[MARKUP_MODE_KEY] = typer_obj.rich_markup_mode + click_obj = typer.main.get_command(typer_obj) + docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title) + clean_docs = f"{docs.strip()}\n" + if output: + output.write_text(clean_docs) + typer.echo(f"Docs saved to: {output}") + else: + typer.echo(clean_docs) + + +def main() -> Any: + return app() diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/colors.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/colors.py new file mode 100644 index 0000000000000000000000000000000000000000..54e7b166cb1de83321a4965cc4915824b47a7f4f --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/colors.py @@ -0,0 +1,20 @@ +# Variable names to colors, just for completion +BLACK = "black" +RED = "red" +GREEN = "green" +YELLOW = "yellow" +BLUE = "blue" +MAGENTA = "magenta" +CYAN = "cyan" +WHITE = "white" + +RESET = "reset" + +BRIGHT_BLACK = "bright_black" +BRIGHT_RED = "bright_red" +BRIGHT_GREEN = "bright_green" +BRIGHT_YELLOW = "bright_yellow" +BRIGHT_BLUE = "bright_blue" +BRIGHT_MAGENTA = "bright_magenta" +BRIGHT_CYAN = "bright_cyan" +BRIGHT_WHITE = "bright_white" diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/completion.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/completion.py new file mode 100644 index 0000000000000000000000000000000000000000..0d621e411d7bab9a6d4ab14102670adbcabaf962 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/completion.py @@ -0,0 +1,146 @@ +import os +import sys +from collections.abc import MutableMapping +from typing import Any + +import click + +from ._completion_classes import completion_init +from ._completion_shared import Shells, _get_shell_name, get_completion_script, install +from .models import ParamMeta +from .params import Option +from .utils import get_params_from_function + +_click_patched = False + + +def get_completion_inspect_parameters() -> tuple[ParamMeta, ParamMeta]: + completion_init() + test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION") + if not test_disable_detection: + parameters = get_params_from_function(_install_completion_placeholder_function) + else: + parameters = get_params_from_function( + _install_completion_no_auto_placeholder_function + ) + install_param, show_param = parameters.values() + return install_param, show_param + + +def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any: + if not value or ctx.resilient_parsing: + return value # pragma: no cover + if isinstance(value, str): + shell, path = install(shell=value) + else: + shell, path = install() + click.secho(f"{shell} completion installed in {path}", fg="green") + click.echo("Completion will take effect once you restart the terminal") + sys.exit(0) + + +def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any: + if not value or ctx.resilient_parsing: + return value # pragma: no cover + prog_name = ctx.find_root().info_name + assert prog_name + complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper()) + shell = "" + test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION") + if isinstance(value, str): + shell = value + elif not test_disable_detection: + detected_shell = _get_shell_name() + if detected_shell is not None: + shell = detected_shell + script_content = get_completion_script( + prog_name=prog_name, complete_var=complete_var, shell=shell + ) + click.echo(script_content) + sys.exit(0) + + +# Create a fake command function to extract the completion parameters +def _install_completion_placeholder_function( + install_completion: bool = Option( + None, + "--install-completion", + callback=install_callback, + expose_value=False, + help="Install completion for the current shell.", + ), + show_completion: bool = Option( + None, + "--show-completion", + callback=show_callback, + expose_value=False, + help="Show completion for the current shell, to copy it or customize the installation.", + ), +) -> Any: + pass # pragma: no cover + + +def _install_completion_no_auto_placeholder_function( + install_completion: Shells = Option( + None, + callback=install_callback, + expose_value=False, + help="Install completion for the specified shell.", + ), + show_completion: Shells = Option( + None, + callback=show_callback, + expose_value=False, + help="Show completion for the specified shell, to copy it or customize the installation.", + ), +) -> Any: + pass # pragma: no cover + + +# Re-implement Click's shell_complete to add error message with: +# Invalid completion instruction +# To use 7.x instruction style for compatibility +# And to add extra error messages, for compatibility with Typer in previous versions +# This is only called in new Command method, only used by Click 8.x+ +def shell_complete( + cli: click.Command, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str, + instruction: str, +) -> int: + import click + import click.shell_completion + + if "_" not in instruction: + click.echo("Invalid completion instruction.", err=True) + return 1 + + # Click 8 changed the order/style of shell instructions from e.g. + # source_bash to bash_source + # Typer override to preserve the old style for compatibility + # Original in Click 8.x commented: + # shell, _, instruction = instruction.partition("_") + instruction, _, shell = instruction.partition("_") + # Typer override end + + comp_cls = click.shell_completion.get_completion_class(shell) + + if comp_cls is None: + click.echo(f"Shell {shell} not supported.", err=True) + return 1 + + comp = comp_cls(cli, ctx_args, prog_name, complete_var) + + if instruction == "source": + click.echo(comp.source()) + return 0 + + # Typer override to print the completion help msg with Rich + if instruction == "complete": + click.echo(comp.complete()) + return 0 + # Typer override end + + click.echo(f'Completion instruction "{instruction}" not supported.', err=True) + return 1 diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/core.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/core.py new file mode 100644 index 0000000000000000000000000000000000000000..3e72d839893185826dfdc9e9d6d8006a279db48d --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/core.py @@ -0,0 +1,821 @@ +import errno +import inspect +import os +import sys +from collections.abc import Callable, MutableMapping, Sequence +from difflib import get_close_matches +from enum import Enum +from gettext import gettext as _ +from typing import ( + Any, + TextIO, + Union, + cast, +) + +import click +import click.core +import click.formatting +import click.shell_completion +import click.types +import click.utils + +from ._typing import Literal +from .utils import parse_boolean_env_var + +MarkupMode = Literal["markdown", "rich", None] +MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE" + +HAS_RICH = parse_boolean_env_var(os.getenv("TYPER_USE_RICH"), default=True) + +if HAS_RICH: + DEFAULT_MARKUP_MODE: MarkupMode = "rich" +else: + DEFAULT_MARKUP_MODE = None + + +# Copy from click.parser._split_opt +def _split_opt(opt: str) -> tuple[str, str]: + first = opt[:1] + if first.isalnum(): + return "", opt + if opt[1:2] == first: + return opt[:2], opt[2:] + return first, opt[1:] + + +def _typer_param_setup_autocompletion_compat( + self: click.Parameter, + *, + autocompletion: Callable[ + [click.Context, list[str], str], list[tuple[str, str] | str] + ] + | None = None, +) -> None: + if self._custom_shell_complete is not None: + import warnings + + warnings.warn( + "In Typer, only the parameter 'autocompletion' is supported. " + "The support for 'shell_complete' is deprecated and will be removed in upcoming versions. ", + DeprecationWarning, + stacklevel=2, + ) + + if autocompletion is not None: + + def compat_autocompletion( + ctx: click.Context, param: click.core.Parameter, incomplete: str + ) -> list["click.shell_completion.CompletionItem"]: + from click.shell_completion import CompletionItem + + out = [] + + for c in autocompletion(ctx, [], incomplete): + if isinstance(c, tuple): + use_completion = CompletionItem(c[0], help=c[1]) + else: + assert isinstance(c, str) + use_completion = CompletionItem(c) + + if use_completion.value.startswith(incomplete): + out.append(use_completion) + + return out + + self._custom_shell_complete = compat_autocompletion + + +def _get_default_string( + obj: Union["TyperArgument", "TyperOption"], + *, + ctx: click.Context, + show_default_is_str: bool, + default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, +) -> str: + # Extracted from click.core.Option.get_help_record() to be reused by + # rich_utils avoiding RegEx hacks + if show_default_is_str: + default_string = f"({obj.show_default})" + elif isinstance(default_value, (list, tuple)): + default_string = ", ".join( + _get_default_string( + obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d + ) + for d in default_value + ) + elif isinstance(default_value, Enum): + default_string = str(default_value.value) + elif inspect.isfunction(default_value): + default_string = _("(dynamic)") + elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts: + # For boolean flags that have distinct True/False opts, + # use the opt without prefix instead of the value. + # Typer override, original commented + # default_string = click.parser.split_opt( + # (self.opts if self.default else self.secondary_opts)[0] + # )[1] + if obj.default: + if obj.opts: + default_string = _split_opt(obj.opts[0])[1] + else: + default_string = str(default_value) + else: + default_string = _split_opt(obj.secondary_opts[0])[1] + # Typer override end + elif ( + isinstance(obj, TyperOption) + and obj.is_bool_flag + and not obj.secondary_opts + and not default_value + ): + default_string = "" + else: + default_string = str(default_value) + return default_string + + +def _extract_default_help_str( + obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context +) -> Any | Callable[[], Any] | None: + # Extracted from click.core.Option.get_help_record() to be reused by + # rich_utils avoiding RegEx hacks + # Temporarily enable resilient parsing to avoid type casting + # failing for the default. Might be possible to extend this to + # help formatting in general. + resilient = ctx.resilient_parsing + ctx.resilient_parsing = True + + try: + default_value = obj.get_default(ctx, call=False) + finally: + ctx.resilient_parsing = resilient + return default_value + + +def _main( + self: click.Command, + *, + args: Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, + **extra: Any, +) -> Any: + # Typer override, duplicated from click.main() to handle custom rich exceptions + # Verify that the environment is configured correctly, or reject + # further execution to avoid a broken script. + if args is None: + args = sys.argv[1:] + + # Covered in Click tests + if os.name == "nt" and windows_expand_args: # pragma: no cover + args = click.utils._expand_args(args) + else: + args = list(args) + + if prog_name is None: + prog_name = click.utils._detect_program_name() + + # Process shell completion requests and exit early. + self._main_shell_completion(extra, prog_name, complete_var) + + try: + try: + with self.make_context(prog_name, args, **extra) as ctx: + rv = self.invoke(ctx) + if not standalone_mode: + return rv + # it's not safe to `ctx.exit(rv)` here! + # note that `rv` may actually contain data like "1" which + # has obvious effects + # more subtle case: `rv=[None, None]` can come out of + # chained commands which all returned `None` -- so it's not + # even always obvious that `rv` indicates success/failure + # by its truthiness/falsiness + ctx.exit() + except EOFError as e: + click.echo(file=sys.stderr) + raise click.Abort() from e + except KeyboardInterrupt as e: + raise click.exceptions.Exit(130) from e + except click.ClickException as e: + if not standalone_mode: + raise + # Typer override + if HAS_RICH and rich_markup_mode is not None: + from . import rich_utils + + rich_utils.rich_format_error(e) + else: + e.show() + # Typer override end + sys.exit(e.exit_code) + except OSError as e: + if e.errno == errno.EPIPE: + sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout)) + sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr)) + sys.exit(1) + else: + raise + except click.exceptions.Exit as e: + if standalone_mode: + sys.exit(e.exit_code) + else: + # in non-standalone mode, return the exit code + # note that this is only reached if `self.invoke` above raises + # an Exit explicitly -- thus bypassing the check there which + # would return its result + # the results of non-standalone execution may therefore be + # somewhat ambiguous: if there are codepaths which lead to + # `ctx.exit(1)` and to `return 1`, the caller won't be able to + # tell the difference between the two + return e.exit_code + except click.Abort: + if not standalone_mode: + raise + # Typer override + if HAS_RICH and rich_markup_mode is not None: + from . import rich_utils + + rich_utils.rich_abort_error() + else: + click.echo(_("Aborted!"), file=sys.stderr) + # Typer override end + sys.exit(1) + + +class TyperArgument(click.core.Argument): + def __init__( + self, + *, + # Parameter + param_decls: list[str], + type: Any | None = None, + required: bool | None = None, + default: Any | None = None, + callback: Callable[..., Any] | None = None, + nargs: int | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Rich settings + rich_help_panel: str | None = None, + ): + self.help = help + self.show_default = show_default + self.show_choices = show_choices + self.show_envvar = show_envvar + self.hidden = hidden + self.rich_help_panel = rich_help_panel + + super().__init__( + param_decls=param_decls, + type=type, + required=required, + default=default, + callback=callback, + nargs=nargs, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + ) + _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) + + def _get_default_string( + self, + *, + ctx: click.Context, + show_default_is_str: bool, + default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, + ) -> str: + return _get_default_string( + self, + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + + def _extract_default_help_str( + self, *, ctx: click.Context + ) -> Any | Callable[[], Any] | None: + return _extract_default_help_str(self, ctx=ctx) + + def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None: + # Modified version of click.core.Option.get_help_record() + # to support Arguments + if self.hidden: + return None + name = self.make_metavar(ctx=ctx) + help = self.help or "" + extra = [] + if self.show_envvar: + envvar = self.envvar + # allow_from_autoenv is currently not supported in Typer for CLI Arguments + if envvar is not None: + var_str = ( + ", ".join(str(d) for d in envvar) + if isinstance(envvar, (list, tuple)) + else envvar + ) + extra.append(f"env var: {var_str}") + + # Typer override: + # Extracted to _extract_default_help_str() to allow re-using it in rich_utils + default_value = self._extract_default_help_str(ctx=ctx) + # Typer override end + + show_default_is_str = isinstance(self.show_default, str) + + if show_default_is_str or ( + default_value is not None and (self.show_default or ctx.show_default) + ): + # Typer override: + # Extracted to _get_default_string() to allow re-using it in rich_utils + default_string = self._get_default_string( + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + # Typer override end + if default_string: + extra.append(_("default: {default}").format(default=default_string)) + if self.required: + extra.append(_("required")) + if extra: + extra_str = "; ".join(extra) + extra_str = f"[{extra_str}]" + rich_markup_mode = None + if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): + rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) + if HAS_RICH and rich_markup_mode == "rich": + # This is needed for when we want to export to HTML + from . import rich_utils + + extra_str = rich_utils.escape_before_html_export(extra_str) + + help = f"{help} {extra_str}" if help else f"{extra_str}" + return name, help + + def make_metavar(self, ctx: click.Context | None = None) -> str: + # Modified version of click.core.Argument.make_metavar() + # to include Argument name + if self.metavar is not None: + var = self.metavar + if not self.required and not var.startswith("["): + var = f"[{var}]" + return var + var = (self.name or "").upper() + if not self.required: + var = f"[{var}]" + type_var = self.type.get_metavar(self, ctx=ctx) # type: ignore[arg-type] + # type_var = self.type.get_metavar(self, ctx=ctx) + if type_var: + var += f":{type_var}" + if self.nargs != 1: + var += "..." + return var + + def value_is_missing(self, value: Any) -> bool: + return _value_is_missing(self, value) + + +class TyperOption(click.core.Option): + def __init__( + self, + *, + # Parameter + param_decls: list[str], + type: click.types.ParamType | Any | None = None, + required: bool | None = None, + default: Any | None = None, + callback: Callable[..., Any] | None = None, + nargs: int | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + # Option + show_default: bool | str = False, + prompt: bool | str = False, + confirmation_prompt: bool | str = False, + prompt_required: bool = True, + hide_input: bool = False, + is_flag: bool | None = None, + multiple: bool = False, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = False, + # Rich settings + rich_help_panel: str | None = None, + ): + super().__init__( + param_decls=param_decls, + type=type, + required=required, + default=default, + callback=callback, + nargs=nargs, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + show_default=show_default, + prompt=prompt, + confirmation_prompt=confirmation_prompt, + hide_input=hide_input, + is_flag=is_flag, + multiple=multiple, + count=count, + allow_from_autoenv=allow_from_autoenv, + help=help, + hidden=hidden, + show_choices=show_choices, + show_envvar=show_envvar, + prompt_required=prompt_required, + shell_complete=shell_complete, + ) + _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion) + self.rich_help_panel = rich_help_panel + + def _get_default_string( + self, + *, + ctx: click.Context, + show_default_is_str: bool, + default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any, + ) -> str: + return _get_default_string( + self, + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + + def _extract_default_help_str( + self, *, ctx: click.Context + ) -> Any | Callable[[], Any] | None: + return _extract_default_help_str(self, ctx=ctx) + + def make_metavar(self, ctx: click.Context | None = None) -> str: + return super().make_metavar(ctx=ctx) # type: ignore[arg-type] + + def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None: + # Duplicate all of Click's logic only to modify a single line, to allow boolean + # flags with only names for False values as it's currently supported by Typer + # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false + if self.hidden: + return None + + any_prefix_is_slash = False + + def _write_opts(opts: Sequence[str]) -> str: + nonlocal any_prefix_is_slash + + rv, any_slashes = click.formatting.join_options(opts) + + if any_slashes: + any_prefix_is_slash = True + + if not self.is_flag and not self.count: + rv += f" {self.make_metavar(ctx=ctx)}" + + return rv + + rv = [_write_opts(self.opts)] + + if self.secondary_opts: + rv.append(_write_opts(self.secondary_opts)) + + help = self.help or "" + extra = [] + + if self.show_envvar: + envvar = self.envvar + + if envvar is None: + if ( + self.allow_from_autoenv + and ctx.auto_envvar_prefix is not None + and self.name is not None + ): + envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}" + + if envvar is not None: + var_str = ( + envvar + if isinstance(envvar, str) + else ", ".join(str(d) for d in envvar) + ) + extra.append(_("env var: {var}").format(var=var_str)) + + # Typer override: + # Extracted to _extract_default() to allow re-using it in rich_utils + default_value = self._extract_default_help_str(ctx=ctx) + # Typer override end + + show_default_is_str = isinstance(self.show_default, str) + + if show_default_is_str or ( + default_value is not None and (self.show_default or ctx.show_default) + ): + # Typer override: + # Extracted to _get_default_string() to allow re-using it in rich_utils + default_string = self._get_default_string( + ctx=ctx, + show_default_is_str=show_default_is_str, + default_value=default_value, + ) + # Typer override end + if default_string: + extra.append(_("default: {default}").format(default=default_string)) + + if isinstance(self.type, click.types._NumberRangeBase): + range_str = self.type._describe_range() + + if range_str: + extra.append(range_str) + + if self.required: + extra.append(_("required")) + + if extra: + extra_str = "; ".join(extra) + extra_str = f"[{extra_str}]" + rich_markup_mode = None + if hasattr(ctx, "obj") and isinstance(ctx.obj, dict): + rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None) + if HAS_RICH and rich_markup_mode == "rich": + # This is needed for when we want to export to HTML + from . import rich_utils + + extra_str = rich_utils.escape_before_html_export(extra_str) + + help = f"{help} {extra_str}" if help else f"{extra_str}" + + return ("; " if any_prefix_is_slash else " / ").join(rv), help + + def value_is_missing(self, value: Any) -> bool: + return _value_is_missing(self, value) + + +def _value_is_missing(param: click.Parameter, value: Any) -> bool: + if value is None: + return True + + # Click 8.3 and beyond + # if value is UNSET: + # return True + + if (param.nargs != 1 or param.multiple) and value == (): + return True # pragma: no cover + + return False + + +def _typer_format_options( + self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter +) -> None: + args = [] + opts = [] + for param in self.get_params(ctx): + rv = param.get_help_record(ctx) + if rv is not None: + if param.param_type_name == "argument": + args.append(rv) + elif param.param_type_name == "option": + opts.append(rv) + + if args: + with formatter.section(_("Arguments")): + formatter.write_dl(args) + if opts: + with formatter.section(_("Options")): + formatter.write_dl(opts) + + +def _typer_main_shell_completion( + self: click.core.Command, + *, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str | None = None, +) -> None: + if complete_var is None: + complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper() + + instruction = os.environ.get(complete_var) + + if not instruction: + return + + from .completion import shell_complete + + rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction) + sys.exit(rv) + + +class TyperCommand(click.core.Command): + def __init__( + self, + name: str | None, + *, + context_settings: dict[str, Any] | None = None, + callback: Callable[..., Any] | None = None, + params: list[click.Parameter] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str | None = "[OPTIONS]", + add_help_option: bool = True, + no_args_is_help: bool = False, + hidden: bool = False, + deprecated: bool = False, + # Rich settings + rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, + rich_help_panel: str | None = None, + ) -> None: + super().__init__( + name=name, + context_settings=context_settings, + callback=callback, + params=params, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=options_metavar, + add_help_option=add_help_option, + no_args_is_help=no_args_is_help, + hidden=hidden, + deprecated=deprecated, + ) + self.rich_markup_mode: MarkupMode = rich_markup_mode + self.rich_help_panel = rich_help_panel + + def format_options( + self, ctx: click.Context, formatter: click.HelpFormatter + ) -> None: + _typer_format_options(self, ctx=ctx, formatter=formatter) + + def _main_shell_completion( + self, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str | None = None, + ) -> None: + _typer_main_shell_completion( + self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var + ) + + def main( + self, + args: Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + **extra: Any, + ) -> Any: + return _main( + self, + args=args, + prog_name=prog_name, + complete_var=complete_var, + standalone_mode=standalone_mode, + windows_expand_args=windows_expand_args, + rich_markup_mode=self.rich_markup_mode, + **extra, + ) + + def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: + if not HAS_RICH or self.rich_markup_mode is None: + if not hasattr(ctx, "obj") or ctx.obj is None: + ctx.ensure_object(dict) + if isinstance(ctx.obj, dict): + ctx.obj[MARKUP_MODE_KEY] = self.rich_markup_mode + return super().format_help(ctx, formatter) + from . import rich_utils + + return rich_utils.rich_format_help( + obj=self, + ctx=ctx, + markup_mode=self.rich_markup_mode, + ) + + +class TyperGroup(click.core.Group): + def __init__( + self, + *, + name: str | None = None, + commands: dict[str, click.Command] | Sequence[click.Command] | None = None, + # Rich settings + rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE, + rich_help_panel: str | None = None, + suggest_commands: bool = True, + **attrs: Any, + ) -> None: + super().__init__(name=name, commands=commands, **attrs) + self.rich_markup_mode: MarkupMode = rich_markup_mode + self.rich_help_panel = rich_help_panel + self.suggest_commands = suggest_commands + + def format_options( + self, ctx: click.Context, formatter: click.HelpFormatter + ) -> None: + _typer_format_options(self, ctx=ctx, formatter=formatter) + self.format_commands(ctx, formatter) + + def _main_shell_completion( + self, + ctx_args: MutableMapping[str, Any], + prog_name: str, + complete_var: str | None = None, + ) -> None: + _typer_main_shell_completion( + self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var + ) + + def resolve_command( + self, ctx: click.Context, args: list[str] + ) -> tuple[str | None, click.Command | None, list[str]]: + try: + return super().resolve_command(ctx, args) + except click.UsageError as e: + if self.suggest_commands: + available_commands = list(self.commands.keys()) + if available_commands and args: + typo = args[0] + matches = get_close_matches(typo, available_commands) + if matches: + suggestions = ", ".join(f"{m!r}" for m in matches) + message = e.message.rstrip(".") + e.message = f"{message}. Did you mean {suggestions}?" + raise + + def main( + self, + args: Sequence[str] | None = None, + prog_name: str | None = None, + complete_var: str | None = None, + standalone_mode: bool = True, + windows_expand_args: bool = True, + **extra: Any, + ) -> Any: + return _main( + self, + args=args, + prog_name=prog_name, + complete_var=complete_var, + standalone_mode=standalone_mode, + windows_expand_args=windows_expand_args, + rich_markup_mode=self.rich_markup_mode, + **extra, + ) + + def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: + if not HAS_RICH or self.rich_markup_mode is None: + return super().format_help(ctx, formatter) + from . import rich_utils + + return rich_utils.rich_format_help( + obj=self, + ctx=ctx, + markup_mode=self.rich_markup_mode, + ) + + def list_commands(self, ctx: click.Context) -> list[str]: + """Returns a list of subcommand names. + Note that in Click's Group class, these are sorted. + In Typer, we wish to maintain the original order of creation (cf Issue #933)""" + return [n for n, c in self.commands.items()] diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/main.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/main.py new file mode 100644 index 0000000000000000000000000000000000000000..f4f21bb8444a80af5ad8ab82822fc972f0207b9c --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/main.py @@ -0,0 +1,2013 @@ +import inspect +import os +import platform +import shutil +import subprocess +import sys +import traceback +from collections.abc import Callable, Sequence +from datetime import datetime +from enum import Enum +from functools import update_wrapper +from pathlib import Path +from traceback import FrameSummary, StackSummary +from types import TracebackType +from typing import Annotated, Any +from uuid import UUID + +import click +from annotated_doc import Doc +from typer._types import TyperChoice + +from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values +from .completion import get_completion_inspect_parameters +from .core import ( + DEFAULT_MARKUP_MODE, + HAS_RICH, + MarkupMode, + TyperArgument, + TyperCommand, + TyperGroup, + TyperOption, +) +from .models import ( + AnyType, + ArgumentInfo, + CommandFunctionType, + CommandInfo, + Default, + DefaultPlaceholder, + DeveloperExceptionConfig, + FileBinaryRead, + FileBinaryWrite, + FileText, + FileTextWrite, + NoneType, + OptionInfo, + ParameterInfo, + ParamMeta, + Required, + TyperInfo, + TyperPath, +) +from .utils import get_params_from_function + +_original_except_hook = sys.excepthook +_typer_developer_exception_attr_name = "__typer_developer_exception__" + + +def except_hook( + exc_type: type[BaseException], exc_value: BaseException, tb: TracebackType | None +) -> None: + exception_config: DeveloperExceptionConfig | None = getattr( + exc_value, _typer_developer_exception_attr_name, None + ) + standard_traceback = os.getenv( + "TYPER_STANDARD_TRACEBACK", os.getenv("_TYPER_STANDARD_TRACEBACK") + ) + if ( + standard_traceback + or not exception_config + or not exception_config.pretty_exceptions_enable + ): + _original_except_hook(exc_type, exc_value, tb) + return + typer_path = os.path.dirname(__file__) + click_path = os.path.dirname(click.__file__) + internal_dir_names = [typer_path, click_path] + exc = exc_value + if HAS_RICH: + from . import rich_utils + + rich_tb = rich_utils.get_traceback(exc, exception_config, internal_dir_names) + console_stderr = rich_utils._get_rich_console(stderr=True) + console_stderr.print(rich_tb) + return + tb_exc = traceback.TracebackException.from_exception(exc) + stack: list[FrameSummary] = [] + for frame in tb_exc.stack: + if any(frame.filename.startswith(path) for path in internal_dir_names): + if not exception_config.pretty_exceptions_short: + # Hide the line for internal libraries, Typer and Click + stack.append( + traceback.FrameSummary( + filename=frame.filename, + lineno=frame.lineno, + name=frame.name, + line="", + ) + ) + else: + stack.append(frame) + # Type ignore ref: https://github.com/python/typeshed/pull/8244 + final_stack_summary = StackSummary.from_list(stack) + tb_exc.stack = final_stack_summary + for line in tb_exc.format(): + print(line, file=sys.stderr) + return + + +def get_install_completion_arguments() -> tuple[click.Parameter, click.Parameter]: + install_param, show_param = get_completion_inspect_parameters() + click_install_param, _ = get_click_param(install_param) + click_show_param, _ = get_click_param(show_param) + return click_install_param, click_show_param + + +class Typer: + """ + `Typer` main class, the main entrypoint to use Typer. + + Read more in the + [Typer docs for First Steps](https://typer.tiangolo.com/tutorial/typer-app/). + + ## Example + + ```python + import typer + + app = typer.Typer() + ``` + """ + + def __init__( + self, + *, + name: Annotated[ + str | None, + Doc( + """ + The name of this application. + Mostly used to set the name for [subcommands](https://typer.tiangolo.com/tutorial/subcommands/), in which case it can be overridden by `add_typer(name=...)`. + + **Example** + + ```python + import typer + + app = typer.Typer(name="users") + ``` + """ + ), + ] = Default(None), + cls: Annotated[ + type[TyperGroup] | None, + Doc( + """ + The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperGroup`. + + **Example** + + ```python + import typer + + app = typer.Typer(cls=TyperGroup) + ``` + """ + ), + ] = Default(None), + invoke_without_command: Annotated[ + bool, + Doc( + """ + By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided. + + **Example** + + ```python + import typer + + app = typer.Typer(invoke_without_command=True) + ``` + """ + ), + ] = Default(False), + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + + **Example** + + ```python + import typer + + app = typer.Typer(no_args_is_help=True) + ``` + """ + ), + ] = Default(False), + subcommand_metavar: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + How to represent the subcommand argument in help. + """ + ), + ] = Default(None), + chain: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + Allow passing more than one subcommand argument. + """ + ), + ] = Default(False), + result_callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + A function to call after the group's and subcommand's callbacks. + """ + ), + ] = Default(None), + # Command + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + + **Example** + + ```python + import typer + + app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]}) + ``` + """ + ), + ] = Default(None), + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to the main Typer app. Can be overridden with `@app.callback()`. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details. + + **Example** + + ```python + import typer + + def callback(): + print("Running a command") + + app = typer.Typer(callback=callback) + ``` + """ + ), + ] = Default(None), + help: Annotated[ + str | None, + Doc( + """ + Help text for the main Typer app. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + + **Example** + + ```python + import typer + + app = typer.Typer(help="Some help.") + ``` + """ + ), + ] = Default(None), + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + + **Example** + + ```python + import typer + + app = typer.Typer(epilog="May the force be with you") + ``` + """ + ), + ] = Default(None), + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + + **Example** + + ```python + import typer + + app = typer.Typer(help="A lot of explanation about user management", short_help="user management") + ``` + """ + ), + ] = Default(None), + options_metavar: Annotated[ + str, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. + + **Example** + + ```python + import typer + + app = typer.Typer(options_metavar="[OPTS]") + ``` + """ + ), + ] = Default("[OPTIONS]"), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = Default(True), + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + + **Example** + + ```python + import typer + + app = typer.Typer(hidden=True) + ``` + """ + ), + ] = Default(False), + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as being deprecated in the help text. `False` by default. + + **Example** + + ```python + import typer + + app = typer.Typer(deprecated=True) + ``` + """ + ), + ] = Default(False), + add_completion: Annotated[ + bool, + Doc( + """ + Toggle whether or not to add the `--install-completion` and `--show-completion` options to the app. + Set to `True` by default. + + **Example** + + ```python + import typer + + app = typer.Typer(add_completion=False) + ``` + """ + ), + ] = True, + # Rich settings + rich_markup_mode: Annotated[ + MarkupMode, + Doc( + """ + Enable markup text if you have Rich installed. This can be set to `"markdown"`, `"rich"`, or `None`. + By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed. + See [the tutorial on help formatting](https://typer.tiangolo.com/tutorial/commands/help/#rich-markdown-and-markup) for more information. + + **Example** + + ```python + import typer + + app = typer.Typer(rich_markup_mode="rich") + ``` + """ + ), + ] = DEFAULT_MARKUP_MODE, + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + + **Example** + + ```python + import typer + + app = typer.Typer(rich_help_panel="Utils and Configs") + ``` + """ + ), + ] = Default(None), + suggest_commands: Annotated[ + bool, + Doc( + """ + As of version 0.20.0, Typer provides [support for mistyped command names](https://typer.tiangolo.com/tutorial/commands/help/#suggest-commands) by printing helpful suggestions. + You can turn this setting off with `suggest_commands`: + + **Example** + + ```python + import typer + + app = typer.Typer(suggest_commands=False) + ``` + """ + ), + ] = True, + pretty_exceptions_enable: Annotated[ + bool, + Doc( + """ + If you want to disable [pretty exceptions with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich), + you can set `pretty_exceptions_enable` to `False`. When doing so, you will see the usual standard exception trace. + + **Example** + + ```python + import typer + + app = typer.Typer(pretty_exceptions_enable=False) + ``` + """ + ), + ] = True, + pretty_exceptions_show_locals: Annotated[ + bool, + Doc( + """ + If Rich is installed, [error messages](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-and-errors) + will be nicely printed. + + If you set `pretty_exceptions_show_locals=True` it will also include the values of local variables for easy debugging. + + However, if such a variable contains delicate information, you should consider leaving `pretty_exceptions_show_locals=False` + (the default) to `False` to enhance security. + + **Example** + + ```python + import typer + + app = typer.Typer(pretty_exceptions_show_locals=True) + ``` + """ + ), + ] = False, + pretty_exceptions_short: Annotated[ + bool, + Doc( + """ + By default, [pretty exceptions formatted with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich) hide the long stack trace. + If you want to show the full trace instead, you can set the parameter `pretty_exceptions_short` to `False`: + + **Example** + + ```python + import typer + + app = typer.Typer(pretty_exceptions_short=False) + ``` + """ + ), + ] = True, + ): + self._add_completion = add_completion + self.rich_markup_mode: MarkupMode = rich_markup_mode + self.rich_help_panel = rich_help_panel + self.suggest_commands = suggest_commands + self.pretty_exceptions_enable = pretty_exceptions_enable + self.pretty_exceptions_show_locals = pretty_exceptions_show_locals + self.pretty_exceptions_short = pretty_exceptions_short + self.info = TyperInfo( + name=name, + cls=cls, + invoke_without_command=invoke_without_command, + no_args_is_help=no_args_is_help, + subcommand_metavar=subcommand_metavar, + chain=chain, + result_callback=result_callback, + context_settings=context_settings, + callback=callback, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=options_metavar, + add_help_option=add_help_option, + hidden=hidden, + deprecated=deprecated, + ) + self.registered_groups: list[TyperInfo] = [] + self.registered_commands: list[CommandInfo] = [] + self.registered_callback: TyperInfo | None = None + + def callback( + self, + *, + cls: Annotated[ + type[TyperGroup] | None, + Doc( + """ + The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperGroup`. + """ + ), + ] = Default(None), + invoke_without_command: Annotated[ + bool, + Doc( + """ + By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided. + """ + ), + ] = Default(False), + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + """ + ), + ] = Default(False), + subcommand_metavar: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + How to represent the subcommand argument in help. + """ + ), + ] = Default(None), + chain: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + Allow passing more than one subcommand argument. + """ + ), + ] = Default(False), + result_callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + A function to call after the group's and subcommand's callbacks. + """ + ), + ] = Default(None), + # Command + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + """ + ), + ] = Default(None), + help: Annotated[ + str | None, + Doc( + """ + Help text for the command. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + """ + ), + ] = Default(None), + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + """ + ), + ] = Default(None), + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + """ + ), + ] = Default(None), + options_metavar: Annotated[ + str | None, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. When `None`, the default value will be used. + """ + ), + ] = Default(None), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = Default(True), + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + """ + ), + ] = Default(False), + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as deprecated in the help text. `False` by default. + """ + ), + ] = Default(False), + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + """ + ), + ] = Default(None), + ) -> Callable[[CommandFunctionType], CommandFunctionType]: + """ + Using the decorator `@app.callback`, you can declare the CLI parameters for the main CLI application. + + Read more in the + [Typer docs for Callbacks](https://typer.tiangolo.com/tutorial/commands/callback/). + + ## Example + + ```python + import typer + + app = typer.Typer() + state = {"verbose": False} + + @app.callback() + def main(verbose: bool = False): + if verbose: + print("Will write verbose output") + state["verbose"] = True + + @app.command() + def delete(username: str): + # define subcommand + ... + ``` + """ + + def decorator(f: CommandFunctionType) -> CommandFunctionType: + self.registered_callback = TyperInfo( + cls=cls, + invoke_without_command=invoke_without_command, + no_args_is_help=no_args_is_help, + subcommand_metavar=subcommand_metavar, + chain=chain, + result_callback=result_callback, + context_settings=context_settings, + callback=f, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=( + options_metavar or self._info_val_str("options_metavar") + ), + add_help_option=add_help_option, + hidden=hidden, + deprecated=deprecated, + rich_help_panel=rich_help_panel, + ) + return f + + return decorator + + def command( + self, + name: Annotated[ + str | None, + Doc( + """ + The name of this command. + """ + ), + ] = None, + *, + cls: Annotated[ + type[TyperCommand] | None, + Doc( + """ + The class of this command. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperCommand`. + """ + ), + ] = None, + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + """ + ), + ] = None, + help: Annotated[ + str | None, + Doc( + """ + Help text for the command. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + """ + ), + ] = None, + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + """ + ), + ] = None, + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + """ + ), + ] = None, + options_metavar: Annotated[ + str | None, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. When `None`, the default value will be used. + """ + ), + ] = Default(None), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = True, + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + """ + ), + ] = False, + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + """ + ), + ] = False, + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as deprecated in the help outputs. `False` by default. + """ + ), + ] = False, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + """ + ), + ] = Default(None), + ) -> Callable[[CommandFunctionType], CommandFunctionType]: + """ + Using the decorator `@app.command`, you can define a subcommand of the previously defined Typer app. + + Read more in the + [Typer docs for Commands](https://typer.tiangolo.com/tutorial/commands/). + + ## Example + + ```python + import typer + + app = typer.Typer() + + @app.command() + def create(): + print("Creating user: Hiro Hamada") + + @app.command() + def delete(): + print("Deleting user: Hiro Hamada") + ``` + """ + if cls is None: + cls = TyperCommand + + def decorator(f: CommandFunctionType) -> CommandFunctionType: + self.registered_commands.append( + CommandInfo( + name=name, + cls=cls, + context_settings=context_settings, + callback=f, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=( + options_metavar or self._info_val_str("options_metavar") + ), + add_help_option=add_help_option, + no_args_is_help=no_args_is_help, + hidden=hidden, + deprecated=deprecated, + # Rich settings + rich_help_panel=rich_help_panel, + ) + ) + return f + + return decorator + + def add_typer( + self, + typer_instance: "Typer", + *, + name: Annotated[ + str | None, + Doc( + """ + The name of this subcommand. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's name, + and which one takes priority. + """ + ), + ] = Default(None), + cls: Annotated[ + type[TyperGroup] | None, + Doc( + """ + The class of this subcommand. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`. + Otherwise, should be a subtype of `TyperGroup`. + """ + ), + ] = Default(None), + invoke_without_command: Annotated[ + bool, + Doc( + """ + By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided. + """ + ), + ] = Default(False), + no_args_is_help: Annotated[ + bool, + Doc( + """ + If this is set to `True`, running a command without any arguments will automatically show the help page. + """ + ), + ] = Default(False), + subcommand_metavar: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + How to represent the subcommand argument in help. + """ + ), + ] = Default(None), + chain: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + Allow passing more than one subcommand argument. + """ + ), + ] = Default(False), + result_callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + A function to call after the group's and subcommand's callbacks. + """ + ), + ] = Default(None), + # Command + context_settings: Annotated[ + dict[Any, Any] | None, + Doc( + """ + Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/). + Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context). + """ + ), + ] = Default(None), + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to this app. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details. + """ + ), + ] = Default(None), + help: Annotated[ + str | None, + Doc( + """ + Help text for the subcommand. + See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help, + and which one takes priority. + """ + ), + ] = Default(None), + epilog: Annotated[ + str | None, + Doc( + """ + Text that will be printed right after the help text. + """ + ), + ] = Default(None), + short_help: Annotated[ + str | None, + Doc( + """ + A shortened version of the help text that can be used e.g. in the help table listing subcommands. + When not defined, the normal `help` text will be used instead. + """ + ), + ] = Default(None), + options_metavar: Annotated[ + str | None, + Doc( + """ + In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`. + Set `options_metavar` to change this into a different string. When `None`, the default value will be used. + """ + ), + ] = Default(None), + add_help_option: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited + from Click and supported for compatibility. + + --- + + By default each command registers a `--help` option. This can be disabled by this parameter. + """ + ), + ] = Default(True), + hidden: Annotated[ + bool, + Doc( + """ + Hide this command from help outputs. `False` by default. + """ + ), + ] = Default(False), + deprecated: Annotated[ + bool, + Doc( + """ + Mark this command as deprecated in the help outputs. `False` by default. + """ + ), + ] = False, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name of the command when the help is printed with Rich. + """ + ), + ] = Default(None), + ) -> None: + """ + Add subcommands to the main app using `app.add_typer()`. + Subcommands may be defined in separate modules, ensuring clean separation of code by functionality. + + Read more in the + [Typer docs for SubCommands](https://typer.tiangolo.com/tutorial/subcommands/add-typer/). + + ## Example + + ```python + import typer + + from .add import app as add_app + from .delete import app as delete_app + + app = typer.Typer() + + app.add_typer(add_app) + app.add_typer(delete_app) + ``` + """ + self.registered_groups.append( + TyperInfo( + typer_instance, + name=name, + cls=cls, + invoke_without_command=invoke_without_command, + no_args_is_help=no_args_is_help, + subcommand_metavar=subcommand_metavar, + chain=chain, + result_callback=result_callback, + context_settings=context_settings, + callback=callback, + help=help, + epilog=epilog, + short_help=short_help, + options_metavar=( + options_metavar or self._info_val_str("options_metavar") + ), + add_help_option=add_help_option, + hidden=hidden, + deprecated=deprecated, + rich_help_panel=rich_help_panel, + ) + ) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + if sys.excepthook != except_hook: + sys.excepthook = except_hook + try: + return get_command(self)(*args, **kwargs) + except Exception as e: + # Set a custom attribute to tell the hook to show nice exceptions for user + # code. An alternative/first implementation was a custom exception with + # raise custom_exc from e + # but that means the last error shown is the custom exception, not the + # actual error. This trick improves developer experience by showing the + # actual error last. + setattr( + e, + _typer_developer_exception_attr_name, + DeveloperExceptionConfig( + pretty_exceptions_enable=self.pretty_exceptions_enable, + pretty_exceptions_show_locals=self.pretty_exceptions_show_locals, + pretty_exceptions_short=self.pretty_exceptions_short, + ), + ) + raise e + + def _info_val_str(self, name: str) -> str: + val = getattr(self.info, name) + val_str = val.value if isinstance(val, DefaultPlaceholder) else val + assert isinstance(val_str, str) + return val_str + + +def get_group(typer_instance: Typer) -> TyperGroup: + group = get_group_from_info( + TyperInfo(typer_instance), + pretty_exceptions_short=typer_instance.pretty_exceptions_short, + rich_markup_mode=typer_instance.rich_markup_mode, + suggest_commands=typer_instance.suggest_commands, + ) + return group + + +def get_command(typer_instance: Typer) -> click.Command: + if typer_instance._add_completion: + click_install_param, click_show_param = get_install_completion_arguments() + if ( + typer_instance.registered_callback + or typer_instance.info.callback + or typer_instance.registered_groups + or len(typer_instance.registered_commands) > 1 + ): + # Create a Group + click_command: click.Command = get_group(typer_instance) + if typer_instance._add_completion: + click_command.params.append(click_install_param) + click_command.params.append(click_show_param) + return click_command + elif len(typer_instance.registered_commands) == 1: + # Create a single Command + single_command = typer_instance.registered_commands[0] + + if not single_command.context_settings and not isinstance( + typer_instance.info.context_settings, DefaultPlaceholder + ): + single_command.context_settings = typer_instance.info.context_settings + + click_command = get_command_from_info( + single_command, + pretty_exceptions_short=typer_instance.pretty_exceptions_short, + rich_markup_mode=typer_instance.rich_markup_mode, + ) + if typer_instance._add_completion: + click_command.params.append(click_install_param) + click_command.params.append(click_show_param) + return click_command + raise RuntimeError( + "Could not get a command for this Typer instance" + ) # pragma: no cover + + +def solve_typer_info_help(typer_info: TyperInfo) -> str: + # Priority 1: Explicit value was set in app.add_typer() + if not isinstance(typer_info.help, DefaultPlaceholder): + return inspect.cleandoc(typer_info.help or "") + # Priority 2: Explicit value was set in sub_app.callback() + if typer_info.typer_instance and typer_info.typer_instance.registered_callback: + callback_help = typer_info.typer_instance.registered_callback.help + if not isinstance(callback_help, DefaultPlaceholder): + return inspect.cleandoc(callback_help or "") + # Priority 3: Explicit value was set in sub_app = typer.Typer() + if typer_info.typer_instance and typer_info.typer_instance.info: + instance_help = typer_info.typer_instance.info.help + if not isinstance(instance_help, DefaultPlaceholder): + return inspect.cleandoc(instance_help or "") + # Priority 4: Implicit inference from callback docstring in app.add_typer() + if typer_info.callback: + doc = inspect.getdoc(typer_info.callback) + if doc: + return doc + # Priority 5: Implicit inference from callback docstring in @app.callback() + if typer_info.typer_instance and typer_info.typer_instance.registered_callback: + callback = typer_info.typer_instance.registered_callback.callback + if not isinstance(callback, DefaultPlaceholder): + doc = inspect.getdoc(callback or "") + if doc: + return doc + # Priority 6: Implicit inference from callback docstring in typer.Typer() + if typer_info.typer_instance and typer_info.typer_instance.info: + instance_callback = typer_info.typer_instance.info.callback + if not isinstance(instance_callback, DefaultPlaceholder): + doc = inspect.getdoc(instance_callback) + if doc: + return doc + # Value not set, use the default + return typer_info.help.value + + +def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo: + values: dict[str, Any] = {} + for name, value in typer_info.__dict__.items(): + # Priority 1: Value was set in app.add_typer() + if not isinstance(value, DefaultPlaceholder): + values[name] = value + continue + # Priority 2: Value was set in @subapp.callback() + try: + callback_value = getattr( + typer_info.typer_instance.registered_callback, # type: ignore + name, + ) + if not isinstance(callback_value, DefaultPlaceholder): + values[name] = callback_value + continue + except AttributeError: + pass + # Priority 3: Value set in subapp = typer.Typer() + try: + instance_value = getattr( + typer_info.typer_instance.info, # type: ignore + name, + ) + if not isinstance(instance_value, DefaultPlaceholder): + values[name] = instance_value + continue + except AttributeError: + pass + # Value not set, use the default + values[name] = value.value + values["help"] = solve_typer_info_help(typer_info) + return TyperInfo(**values) + + +def get_group_from_info( + group_info: TyperInfo, + *, + pretty_exceptions_short: bool, + suggest_commands: bool, + rich_markup_mode: MarkupMode, +) -> TyperGroup: + assert group_info.typer_instance, ( + "A Typer instance is needed to generate a Click Group" + ) + commands: dict[str, click.Command] = {} + for command_info in group_info.typer_instance.registered_commands: + command = get_command_from_info( + command_info=command_info, + pretty_exceptions_short=pretty_exceptions_short, + rich_markup_mode=rich_markup_mode, + ) + if command.name: + commands[command.name] = command + for sub_group_info in group_info.typer_instance.registered_groups: + sub_group = get_group_from_info( + sub_group_info, + pretty_exceptions_short=pretty_exceptions_short, + rich_markup_mode=rich_markup_mode, + suggest_commands=suggest_commands, + ) + if sub_group.name: + commands[sub_group.name] = sub_group + else: + if sub_group.callback: + import warnings + + warnings.warn( + "The 'callback' parameter is not supported by Typer when using `add_typer` without a name", + stacklevel=5, + ) + for sub_command_name, sub_command in sub_group.commands.items(): + commands[sub_command_name] = sub_command + solved_info = solve_typer_info_defaults(group_info) + ( + params, + convertors, + context_param_name, + ) = get_params_convertors_ctx_param_name_from_function(solved_info.callback) + cls = solved_info.cls or TyperGroup + assert issubclass(cls, TyperGroup), f"{cls} should be a subclass of {TyperGroup}" + group = cls( + name=solved_info.name or "", + commands=commands, + invoke_without_command=solved_info.invoke_without_command, + no_args_is_help=solved_info.no_args_is_help, + subcommand_metavar=solved_info.subcommand_metavar, + chain=solved_info.chain, + result_callback=solved_info.result_callback, + context_settings=solved_info.context_settings, + callback=get_callback( + callback=solved_info.callback, + params=params, + convertors=convertors, + context_param_name=context_param_name, + pretty_exceptions_short=pretty_exceptions_short, + ), + params=params, + help=solved_info.help, + epilog=solved_info.epilog, + short_help=solved_info.short_help, + options_metavar=solved_info.options_metavar, + add_help_option=solved_info.add_help_option, + hidden=solved_info.hidden, + deprecated=solved_info.deprecated, + rich_markup_mode=rich_markup_mode, + # Rich settings + rich_help_panel=solved_info.rich_help_panel, + suggest_commands=suggest_commands, + ) + return group + + +def get_command_name(name: str) -> str: + return name.lower().replace("_", "-") + + +def get_params_convertors_ctx_param_name_from_function( + callback: Callable[..., Any] | None, +) -> tuple[list[click.Argument | click.Option], dict[str, Any], str | None]: + params = [] + convertors = {} + context_param_name = None + if callback: + parameters = get_params_from_function(callback) + for param_name, param in parameters.items(): + if lenient_issubclass(param.annotation, click.Context): + context_param_name = param_name + continue + click_param, convertor = get_click_param(param) + if convertor: + convertors[param_name] = convertor + params.append(click_param) + return params, convertors, context_param_name + + +def get_command_from_info( + command_info: CommandInfo, + *, + pretty_exceptions_short: bool, + rich_markup_mode: MarkupMode, +) -> click.Command: + assert command_info.callback, "A command must have a callback function" + name = command_info.name or get_command_name(command_info.callback.__name__) # ty:ignore[unresolved-attribute] + use_help = command_info.help + if use_help is None: + use_help = inspect.getdoc(command_info.callback) + else: + use_help = inspect.cleandoc(use_help) + ( + params, + convertors, + context_param_name, + ) = get_params_convertors_ctx_param_name_from_function(command_info.callback) + cls = command_info.cls or TyperCommand + command = cls( + name=name, + context_settings=command_info.context_settings, + callback=get_callback( + callback=command_info.callback, + params=params, + convertors=convertors, + context_param_name=context_param_name, + pretty_exceptions_short=pretty_exceptions_short, + ), + params=params, # type: ignore + help=use_help, + epilog=command_info.epilog, + short_help=command_info.short_help, + options_metavar=command_info.options_metavar, + add_help_option=command_info.add_help_option, + no_args_is_help=command_info.no_args_is_help, + hidden=command_info.hidden, + deprecated=command_info.deprecated, + rich_markup_mode=rich_markup_mode, + # Rich settings + rich_help_panel=command_info.rich_help_panel, + ) + return command + + +def determine_type_convertor(type_: Any) -> Callable[[Any], Any] | None: + convertor: Callable[[Any], Any] | None = None + if lenient_issubclass(type_, Path): + convertor = param_path_convertor + if lenient_issubclass(type_, Enum): + convertor = generate_enum_convertor(type_) + return convertor + + +def param_path_convertor(value: str | None = None) -> Path | None: + if value is not None: + # allow returning any subclass of Path created by an annotated parser without converting + # it back to a Path + return value if isinstance(value, Path) else Path(value) + return None + + +def generate_enum_convertor(enum: type[Enum]) -> Callable[[Any], Any]: + val_map = {str(val.value): val for val in enum} + + def convertor(value: Any) -> Any: + if value is not None: + val = str(value) + if val in val_map: + key = val_map[val] + return enum(key) + + return convertor + + +def generate_list_convertor( + convertor: Callable[[Any], Any] | None, default_value: Any | None +) -> Callable[[Sequence[Any] | None], list[Any] | None]: + def internal_convertor(value: Sequence[Any] | None) -> list[Any] | None: + if (value is None) or (default_value is None and len(value) == 0): + return None + return [convertor(v) if convertor else v for v in value] + + return internal_convertor + + +def generate_tuple_convertor( + types: Sequence[Any], +) -> Callable[[tuple[Any, ...] | None], tuple[Any, ...] | None]: + convertors = [determine_type_convertor(type_) for type_ in types] + + def internal_convertor( + param_args: tuple[Any, ...] | None, + ) -> tuple[Any, ...] | None: + if param_args is None: + return None + return tuple( + convertor(arg) if convertor else arg + for (convertor, arg) in zip(convertors, param_args, strict=False) + ) + + return internal_convertor + + +def get_callback( + *, + callback: Callable[..., Any] | None = None, + params: Sequence[click.Parameter] = [], + convertors: dict[str, Callable[[str], Any]] | None = None, + context_param_name: str | None = None, + pretty_exceptions_short: bool, +) -> Callable[..., Any] | None: + use_convertors = convertors or {} + if not callback: + return None + parameters = get_params_from_function(callback) + use_params: dict[str, Any] = {} + for param_name in parameters: + use_params[param_name] = None + for param in params: + if param.name: + use_params[param.name] = param.default + + def wrapper(**kwargs: Any) -> Any: + _rich_traceback_guard = pretty_exceptions_short # noqa: F841 + for k, v in kwargs.items(): + if k in use_convertors: + use_params[k] = use_convertors[k](v) + else: + use_params[k] = v + if context_param_name: + use_params[context_param_name] = click.get_current_context() + return callback(**use_params) + + update_wrapper(wrapper, callback) + return wrapper + + +def get_click_type( + *, annotation: Any, parameter_info: ParameterInfo +) -> click.ParamType: + if parameter_info.click_type is not None: + return parameter_info.click_type + + elif parameter_info.parser is not None: + return click.types.FuncParamType(parameter_info.parser) + + elif annotation is str: + return click.STRING + elif annotation is int: + if parameter_info.min is not None or parameter_info.max is not None: + min_ = None + max_ = None + if parameter_info.min is not None: + min_ = int(parameter_info.min) + if parameter_info.max is not None: + max_ = int(parameter_info.max) + return click.IntRange(min=min_, max=max_, clamp=parameter_info.clamp) + else: + return click.INT + elif annotation is float: + if parameter_info.min is not None or parameter_info.max is not None: + return click.FloatRange( + min=parameter_info.min, + max=parameter_info.max, + clamp=parameter_info.clamp, + ) + else: + return click.FLOAT + elif annotation is bool: + return click.BOOL + elif annotation == UUID: + return click.UUID + elif annotation == datetime: + return click.DateTime(formats=parameter_info.formats) + elif ( + annotation == Path + or parameter_info.allow_dash + or parameter_info.path_type + or parameter_info.resolve_path + ): + return TyperPath( + exists=parameter_info.exists, + file_okay=parameter_info.file_okay, + dir_okay=parameter_info.dir_okay, + writable=parameter_info.writable, + readable=parameter_info.readable, + resolve_path=parameter_info.resolve_path, + allow_dash=parameter_info.allow_dash, + path_type=parameter_info.path_type, + ) + elif lenient_issubclass(annotation, FileTextWrite): + return click.File( + mode=parameter_info.mode or "w", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, FileText): + return click.File( + mode=parameter_info.mode or "r", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, FileBinaryRead): + return click.File( + mode=parameter_info.mode or "rb", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, FileBinaryWrite): + return click.File( + mode=parameter_info.mode or "wb", + encoding=parameter_info.encoding, + errors=parameter_info.errors, + lazy=parameter_info.lazy, + atomic=parameter_info.atomic, + ) + elif lenient_issubclass(annotation, Enum): + # The custom TyperChoice is only needed for Click < 8.2.0, to parse the + # command line values matching them to the enum values. Click 8.2.0 added + # support for enum values but reading enum names. + # Passing here the list of enum values (instead of just the enum) accounts for + # Click < 8.2.0. + return TyperChoice( + [item.value for item in annotation], + case_sensitive=parameter_info.case_sensitive, + ) + elif is_literal_type(annotation): + return click.Choice( + literal_values(annotation), + case_sensitive=parameter_info.case_sensitive, + ) + raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover + + +def lenient_issubclass(cls: Any, class_or_tuple: AnyType | tuple[AnyType, ...]) -> bool: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) + + +def get_click_param( + param: ParamMeta, +) -> tuple[click.Argument | click.Option, Any]: + # First, find out what will be: + # * ParamInfo (ArgumentInfo or OptionInfo) + # * default_value + # * required + default_value = None + required = False + if isinstance(param.default, ParameterInfo): + parameter_info = param.default + if parameter_info.default == Required: + required = True + else: + default_value = parameter_info.default + elif param.default == Required or param.default is param.empty: + required = True + parameter_info = ArgumentInfo() + else: + default_value = param.default + parameter_info = OptionInfo() + annotation: Any + if param.annotation is not param.empty: + annotation = param.annotation + else: + annotation = str + main_type = annotation + is_list = False + is_tuple = False + parameter_type: Any = None + is_flag = None + origin = get_origin(main_type) + + if origin is not None: + # Handle SomeType | None and Optional[SomeType] + if is_union(origin): + types = [] + for type_ in get_args(main_type): + if type_ is NoneType: + continue + types.append(type_) + assert len(types) == 1, "Typer Currently doesn't support Union types" + main_type = types[0] + origin = get_origin(main_type) + # Handle Tuples and Lists + if lenient_issubclass(origin, list): + main_type = get_args(main_type)[0] + assert not get_origin(main_type), ( + "List types with complex sub-types are not currently supported" + ) + is_list = True + elif lenient_issubclass(origin, tuple): + types = [] + for type_ in get_args(main_type): + assert not get_origin(type_), ( + "Tuple types with complex sub-types are not currently supported" + ) + types.append( + get_click_type(annotation=type_, parameter_info=parameter_info) + ) + parameter_type = tuple(types) + is_tuple = True + if parameter_type is None: + parameter_type = get_click_type( + annotation=main_type, parameter_info=parameter_info + ) + convertor = determine_type_convertor(main_type) + if is_list: + convertor = generate_list_convertor( + convertor=convertor, default_value=default_value + ) + if is_tuple: + convertor = generate_tuple_convertor(get_args(main_type)) + if isinstance(parameter_info, OptionInfo): + if main_type is bool: + is_flag = True + # Click doesn't accept a flag of type bool, only None, and then it sets it + # to bool internally + parameter_type = None + default_option_name = get_command_name(param.name) + if is_flag: + default_option_declaration = ( + f"--{default_option_name}/--no-{default_option_name}" + ) + else: + default_option_declaration = f"--{default_option_name}" + param_decls = [param.name] + if parameter_info.param_decls: + param_decls.extend(parameter_info.param_decls) + else: + param_decls.append(default_option_declaration) + return ( + TyperOption( + # Option + param_decls=param_decls, + show_default=parameter_info.show_default, + prompt=parameter_info.prompt, + confirmation_prompt=parameter_info.confirmation_prompt, + prompt_required=parameter_info.prompt_required, + hide_input=parameter_info.hide_input, + is_flag=is_flag, + multiple=is_list, + count=parameter_info.count, + allow_from_autoenv=parameter_info.allow_from_autoenv, + type=parameter_type, + help=parameter_info.help, + hidden=parameter_info.hidden, + show_choices=parameter_info.show_choices, + show_envvar=parameter_info.show_envvar, + # Parameter + required=required, + default=default_value, + callback=get_param_callback( + callback=parameter_info.callback, convertor=convertor + ), + metavar=parameter_info.metavar, + expose_value=parameter_info.expose_value, + is_eager=parameter_info.is_eager, + envvar=parameter_info.envvar, + shell_complete=parameter_info.shell_complete, + autocompletion=get_param_completion(parameter_info.autocompletion), + # Rich settings + rich_help_panel=parameter_info.rich_help_panel, + ), + convertor, + ) + elif isinstance(parameter_info, ArgumentInfo): + param_decls = [param.name] + nargs = None + if is_list: + nargs = -1 + return ( + TyperArgument( + # Argument + param_decls=param_decls, + type=parameter_type, + required=required, + nargs=nargs, + # TyperArgument + show_default=parameter_info.show_default, + show_choices=parameter_info.show_choices, + show_envvar=parameter_info.show_envvar, + help=parameter_info.help, + hidden=parameter_info.hidden, + # Parameter + default=default_value, + callback=get_param_callback( + callback=parameter_info.callback, convertor=convertor + ), + metavar=parameter_info.metavar, + expose_value=parameter_info.expose_value, + is_eager=parameter_info.is_eager, + envvar=parameter_info.envvar, + shell_complete=parameter_info.shell_complete, + autocompletion=get_param_completion(parameter_info.autocompletion), + # Rich settings + rich_help_panel=parameter_info.rich_help_panel, + ), + convertor, + ) + raise AssertionError("A click.Parameter should be returned") # pragma: no cover + + +def get_param_callback( + *, + callback: Callable[..., Any] | None = None, + convertor: Callable[..., Any] | None = None, +) -> Callable[..., Any] | None: + if not callback: + return None + parameters = get_params_from_function(callback) + ctx_name = None + click_param_name = None + value_name = None + untyped_names: list[str] = [] + for param_name, param_sig in parameters.items(): + if lenient_issubclass(param_sig.annotation, click.Context): + ctx_name = param_name + elif lenient_issubclass(param_sig.annotation, click.Parameter): + click_param_name = param_name + else: + untyped_names.append(param_name) + # Extract value param name first + if untyped_names: + value_name = untyped_names.pop() + # If context and Click param were not typed (old/Click callback style) extract them + if untyped_names: + if ctx_name is None: + ctx_name = untyped_names.pop(0) + if click_param_name is None: + if untyped_names: + click_param_name = untyped_names.pop(0) + if untyped_names: + raise click.ClickException( + "Too many CLI parameter callback function parameters" + ) + + def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any: + use_params: dict[str, Any] = {} + if ctx_name: + use_params[ctx_name] = ctx + if click_param_name: + use_params[click_param_name] = param + if value_name: + if convertor: + use_value = convertor(value) + else: + use_value = value + use_params[value_name] = use_value + return callback(**use_params) + + update_wrapper(wrapper, callback) + return wrapper + + +def get_param_completion( + callback: Callable[..., Any] | None = None, +) -> Callable[..., Any] | None: + if not callback: + return None + parameters = get_params_from_function(callback) + ctx_name = None + args_name = None + incomplete_name = None + unassigned_params = list(parameters.values()) + for param_sig in unassigned_params[:]: + origin = get_origin(param_sig.annotation) + if lenient_issubclass(param_sig.annotation, click.Context): + ctx_name = param_sig.name + unassigned_params.remove(param_sig) + elif lenient_issubclass(origin, list): + args_name = param_sig.name + unassigned_params.remove(param_sig) + elif lenient_issubclass(param_sig.annotation, str): + incomplete_name = param_sig.name + unassigned_params.remove(param_sig) + # If there are still unassigned parameters (not typed), extract by name + for param_sig in unassigned_params[:]: + if ctx_name is None and param_sig.name == "ctx": + ctx_name = param_sig.name + unassigned_params.remove(param_sig) + elif args_name is None and param_sig.name == "args": + args_name = param_sig.name + unassigned_params.remove(param_sig) + elif incomplete_name is None and param_sig.name == "incomplete": + incomplete_name = param_sig.name + unassigned_params.remove(param_sig) + # Extract value param name first + if unassigned_params: + show_params = " ".join([param.name for param in unassigned_params]) + raise click.ClickException( + f"Invalid autocompletion callback parameters: {show_params}" + ) + + def wrapper(ctx: click.Context, args: list[str], incomplete: str | None) -> Any: + use_params: dict[str, Any] = {} + if ctx_name: + use_params[ctx_name] = ctx + if args_name: + use_params[args_name] = args + if incomplete_name: + use_params[incomplete_name] = incomplete + return callback(**use_params) + + update_wrapper(wrapper, callback) + return wrapper + + +def run( + function: Annotated[ + Callable[..., Any], + Doc( + """ + The function that should power this CLI application. + """ + ), + ], +) -> None: + """ + This function converts a given function to a CLI application with `Typer()` and executes it. + + ## Example + + ```python + import typer + + def main(name: str): + print(f"Hello {name}") + + if __name__ == "__main__": + typer.run(main) + ``` + """ + app = Typer(add_completion=False) + app.command()(function) + app() + + +def _is_macos() -> bool: + return platform.system() == "Darwin" + + +def _is_linux_or_bsd() -> bool: + if platform.system() == "Linux": + return True + + return "BSD" in platform.system() + + +def launch( + url: Annotated[ + str, + Doc( + """ + URL or filename of the thing to launch. + """ + ), + ], + wait: Annotated[ + bool, + Doc( + """ + Wait for the program to exit before returning. This only works if the launched program blocks. + In particular, `xdg-open` on Linux does not block. + """ + ), + ] = False, + locate: Annotated[ + bool, + Doc( + """ + If this is set to `True`, then instead of launching the application associated with the URL, it will attempt to + launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem. + """ + ), + ] = False, +) -> int: + """ + This function launches the given URL (or filename) in the default + viewer application for this file type. If this is an executable, it + might launch the executable in a new session. The return value is + the exit code of the launched application. Usually, `0` indicates + success. + + This function handles url in different operating systems separately: + - On macOS (Darwin), it uses the `open` command. + - On Linux and BSD, it uses `xdg-open` if available. + - On Windows (and other OSes), it uses the standard webbrowser module. + + The function avoids, when possible, using the webbrowser module on Linux and macOS + to prevent spammy terminal messages from some browsers (e.g., Chrome). + + ## Examples + ```python + import typer + + typer.launch("https://typer.tiangolo.com/") + ``` + + ```python + import typer + + typer.launch("/my/downloaded/file", locate=True) + ``` + """ + + if url.startswith("http://") or url.startswith("https://"): + if _is_macos(): + return subprocess.Popen( + ["open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT + ).wait() + + has_xdg_open = _is_linux_or_bsd() and shutil.which("xdg-open") is not None + + if has_xdg_open: + return subprocess.Popen( + ["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT + ).wait() + + import webbrowser + + webbrowser.open(url) + + return 0 + + else: + return click.launch(url) diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/models.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/models.py new file mode 100644 index 0000000000000000000000000000000000000000..3285a96a2433176a22c11c2402116e5f7562218e --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/models.py @@ -0,0 +1,651 @@ +import inspect +import io +from collections.abc import Callable, Sequence +from typing import ( + TYPE_CHECKING, + Any, + Optional, + TypeVar, +) + +import click +import click.shell_completion + +if TYPE_CHECKING: # pragma: no cover + from .core import TyperCommand, TyperGroup + from .main import Typer + + +NoneType = type(None) + +AnyType = type[Any] + +Required = ... + + +class Context(click.Context): + """ + The [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) has some additional data about the current execution of your program. + When declaring it in a [callback](https://typer.tiangolo.com/tutorial/options/callback-and-context/) function, + you can access this additional information. + """ + + pass + + +class FileText(io.TextIOWrapper): + """ + Gives you a file-like object for reading text, and you will get a `str` data from it. + The default mode of this class is `mode="r"`. + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(config: Annotated[typer.FileText, typer.Option()]): + for line in config: + print(f"Config line: {line}") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class FileTextWrite(FileText): + """ + You can use this class for writing text. Alternatively, you can use `FileText` with `mode="w"`. + The default mode of this class is `mode="w"`. + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(config: Annotated[typer.FileTextWrite, typer.Option()]): + config.write("Some config written by the app") + print("Config written") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class FileBinaryRead(io.BufferedReader): + """ + You can use this class to read binary data, receiving `bytes`. + The default mode of this class is `mode="rb"`. + It is useful for reading binary files like images: + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(file: Annotated[typer.FileBinaryRead, typer.Option()]): + processed_total = 0 + for bytes_chunk in file: + # Process the bytes in bytes_chunk + processed_total += len(bytes_chunk) + print(f"Processed bytes total: {processed_total}") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class FileBinaryWrite(io.BufferedWriter): + """ + You can use this class to write binary data: you pass `bytes` to it instead of strings. + The default mode of this class is `mode="wb"`. + It is useful for writing binary files like images: + + **Example** + + ```python + from typing import Annotated + + import typer + + app = typer.Typer() + + @app.command() + def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]): + first_line_str = "some settings\\n" + # You cannot write str directly to a binary file; encode it first + first_line_bytes = first_line_str.encode("utf-8") + # Then you can write the bytes + file.write(first_line_bytes) + # This is already bytes, it starts with b" + second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o" + file.write(second_line) + print("Binary file written") + + if __name__ == "__main__": + app() + ``` + """ + + pass + + +class CallbackParam(click.Parameter): + """ + In a callback function, you can declare a function parameter with type `CallbackParam` + to access the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object. + """ + + pass + + +class DefaultPlaceholder: + """ + You shouldn't use this class directly. + + It's used internally to recognize when a default value has been overwritten, even + if the new value is `None`. + """ + + def __init__(self, value: Any): + self.value = value + + def __bool__(self) -> bool: + return bool(self.value) + + +DefaultType = TypeVar("DefaultType") + +CommandFunctionType = TypeVar("CommandFunctionType", bound=Callable[..., Any]) + + +def Default(value: DefaultType) -> DefaultType: + """ + You shouldn't use this function directly. + + It's used internally to recognize when a default value has been overwritten, even + if the new value is `None`. + """ + return DefaultPlaceholder(value) # type: ignore + + +class CommandInfo: + def __init__( + self, + name: str | None = None, + *, + cls: type["TyperCommand"] | None = None, + context_settings: dict[Any, Any] | None = None, + callback: Callable[..., Any] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str = "[OPTIONS]", + add_help_option: bool = True, + no_args_is_help: bool = False, + hidden: bool = False, + deprecated: bool = False, + # Rich settings + rich_help_panel: str | None = None, + ): + self.name = name + self.cls = cls + self.context_settings = context_settings + self.callback = callback + self.help = help + self.epilog = epilog + self.short_help = short_help + self.options_metavar = options_metavar + self.add_help_option = add_help_option + self.no_args_is_help = no_args_is_help + self.hidden = hidden + self.deprecated = deprecated + # Rich settings + self.rich_help_panel = rich_help_panel + + +class TyperInfo: + def __init__( + self, + typer_instance: Optional["Typer"] = Default(None), + *, + name: str | None = Default(None), + cls: type["TyperGroup"] | None = Default(None), + invoke_without_command: bool = Default(False), + no_args_is_help: bool = Default(False), + subcommand_metavar: str | None = Default(None), + chain: bool = Default(False), + result_callback: Callable[..., Any] | None = Default(None), + # Command + context_settings: dict[Any, Any] | None = Default(None), + callback: Callable[..., Any] | None = Default(None), + help: str | None = Default(None), + epilog: str | None = Default(None), + short_help: str | None = Default(None), + options_metavar: str = Default("[OPTIONS]"), + add_help_option: bool = Default(True), + hidden: bool = Default(False), + deprecated: bool = Default(False), + # Rich settings + rich_help_panel: str | None = Default(None), + ): + self.typer_instance = typer_instance + self.name = name + self.cls = cls + self.invoke_without_command = invoke_without_command + self.no_args_is_help = no_args_is_help + self.subcommand_metavar = subcommand_metavar + self.chain = chain + self.result_callback = result_callback + self.context_settings = context_settings + self.callback = callback + self.help = help + self.epilog = epilog + self.short_help = short_help + self.options_metavar = options_metavar + self.add_help_option = add_help_option + self.hidden = hidden + self.deprecated = deprecated + self.rich_help_panel = rich_help_panel + + +class ParameterInfo: + def __init__( + self, + *, + default: Any | None = None, + param_decls: Sequence[str] | None = None, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + click_type: click.ParamType | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, + ): + # Check if user has provided multiple custom parsers + if parser and click_type: + raise ValueError( + "Multiple custom type parsers provided. " + "`parser` and `click_type` may not both be provided." + ) + + self.default = default + self.param_decls = param_decls + self.callback = callback + self.metavar = metavar + self.expose_value = expose_value + self.is_eager = is_eager + self.envvar = envvar + self.shell_complete = shell_complete + self.autocompletion = autocompletion + self.default_factory = default_factory + # Custom type + self.parser = parser + self.click_type = click_type + # TyperArgument + self.show_default = show_default + self.show_choices = show_choices + self.show_envvar = show_envvar + self.help = help + self.hidden = hidden + # Choice + self.case_sensitive = case_sensitive + # Numbers + self.min = min + self.max = max + self.clamp = clamp + # DateTime + self.formats = formats + # File + self.mode = mode + self.encoding = encoding + self.errors = errors + self.lazy = lazy + self.atomic = atomic + # Path + self.exists = exists + self.file_okay = file_okay + self.dir_okay = dir_okay + self.writable = writable + self.readable = readable + self.resolve_path = resolve_path + self.allow_dash = allow_dash + self.path_type = path_type + # Rich settings + self.rich_help_panel = rich_help_panel + + +class OptionInfo(ParameterInfo): + def __init__( + self, + *, + # ParameterInfo + default: Any | None = None, + param_decls: Sequence[str] | None = None, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + click_type: click.ParamType | None = None, + # Option + show_default: bool | str = True, + prompt: bool | str = False, + confirmation_prompt: bool = False, + prompt_required: bool = True, + hide_input: bool = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: bool | None = None, + flag_value: Any | None = None, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = True, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, + ): + super().__init__( + default=default, + param_decls=param_decls, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # TyperArgument + show_default=show_default, + show_choices=show_choices, + show_envvar=show_envvar, + help=help, + hidden=hidden, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) + if is_flag is not None or flag_value is not None: + import warnings + + warnings.warn( + "The 'is_flag' and 'flag_value' parameters are not supported by Typer " + "and will be removed entirely in a future release.", + DeprecationWarning, + stacklevel=2, + ) + self.prompt = prompt + self.confirmation_prompt = confirmation_prompt + self.prompt_required = prompt_required + self.hide_input = hide_input + self.count = count + self.allow_from_autoenv = allow_from_autoenv + + +class ArgumentInfo(ParameterInfo): + def __init__( + self, + *, + # ParameterInfo + default: Any | None = None, + param_decls: Sequence[str] | None = None, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + click_type: click.ParamType | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, + ): + super().__init__( + default=default, + param_decls=param_decls, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # TyperArgument + show_default=show_default, + show_choices=show_choices, + show_envvar=show_envvar, + help=help, + hidden=hidden, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) + + +class ParamMeta: + empty = inspect.Parameter.empty + + def __init__( + self, + *, + name: str, + default: Any = inspect.Parameter.empty, + annotation: Any = inspect.Parameter.empty, + ) -> None: + self.name = name + self.default = default + self.annotation = annotation + + +class DeveloperExceptionConfig: + def __init__( + self, + *, + pretty_exceptions_enable: bool = True, + pretty_exceptions_show_locals: bool = True, + pretty_exceptions_short: bool = True, + ) -> None: + self.pretty_exceptions_enable = pretty_exceptions_enable + self.pretty_exceptions_show_locals = pretty_exceptions_show_locals + self.pretty_exceptions_short = pretty_exceptions_short + + +class TyperPath(click.Path): + # Overwrite Click's behaviour to be compatible with Typer's autocompletion system + def shell_complete( + self, ctx: click.Context, param: click.Parameter, incomplete: str + ) -> list[click.shell_completion.CompletionItem]: + """Return an empty list so that the autocompletion functionality + will work properly from the commandline. + """ + return [] diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/params.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/params.py new file mode 100644 index 0000000000000000000000000000000000000000..b325b273c43860f79f598c11e971f60f2c95676f --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/params.py @@ -0,0 +1,1831 @@ +from collections.abc import Callable +from typing import TYPE_CHECKING, Annotated, Any, overload + +import click +from annotated_doc import Doc + +from .models import ArgumentInfo, OptionInfo + +if TYPE_CHECKING: # pragma: no cover + import click.shell_completion + + +# Overload for Option created with custom type 'parser' +@overload +def Option( + # Parameter + default: Any | None = ..., + *param_decls: str, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + # Option + show_default: bool | str = True, + prompt: bool | str = False, + confirmation_prompt: bool = False, + prompt_required: bool = True, + hide_input: bool = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: bool | None = None, + flag_value: Any | None = None, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = True, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +# Overload for Option created with custom type 'click_type' +@overload +def Option( + # Parameter + default: Any | None = ..., + *param_decls: str, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + click_type: click.ParamType | None = None, + # Option + show_default: bool | str = True, + prompt: bool | str = False, + confirmation_prompt: bool = False, + prompt_required: bool = True, + hide_input: bool = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: bool | None = None, + flag_value: Any | None = None, + count: bool = False, + allow_from_autoenv: bool = True, + help: str | None = None, + hidden: bool = False, + show_choices: bool = True, + show_envvar: bool = True, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +def Option( + # Parameter + default: Annotated[ + Any | None, + Doc( + """ + Usually, [CLI options](https://typer.tiangolo.com/tutorial/options/) are optional and have a default value, passed on like this: + + **Example** + + ```python + @app.command() + def main(network: str = typer.Option("CNN")): + print(f"Training neural network of type: {network}") + ``` + + Note that this usage is deprecated, and we recommend to use `Annotated` instead: + ``` + @app.command() + def main(network: Annotated[str, typer.Option()] = "CNN"): + print(f"Hello {name}!") + ``` + + You can also use `...` ([Ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis)) as the "default" value to clarify that this is a required CLI option. + """ + ), + ] = ..., + *param_decls: Annotated[ + str, + Doc( + """ + Positional argument that defines how users can call this option on the command line. This may be one or multiple aliases, all strings. + If not defined, Typer will automatically use the function parameter as default name. + See [the tutorial about CLI Option Names](https://typer.tiangolo.com/tutorial/options/name/) for more details. + + **Example** + + ```python + @app.command() + def main(user_name: Annotated[str, typer.Option("--user", "-u", "-x")]): + print(f"Hello {user_name}") + ``` + """ + ), + ], + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to this CLI Option, to execute additional logic after its value was received from the terminal. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details. + + **Example** + + ```python + def name_callback(value: str): + if value != "Deadpool": + raise typer.BadParameter("Only Deadpool is allowed") + return value + + @app.command() + def main(name: Annotated[str, typer.Option(callback=name_callback)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + metavar: Annotated[ + str | None, + Doc( + """ + Customize the name displayed in the [help text](https://typer.tiangolo.com/tutorial/options/help/) to represent this CLI option. + Note that this doesn't influence the way the option must be called. + + **Example** + + ```python + @app.command() + def main(user: Annotated[str, typer.Option(metavar="User name")]): + print(f"Hello {user}") + ``` + """ + ), + ] = None, + expose_value: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped. + """ + ), + ] = True, + is_eager: Annotated[ + bool, + Doc( + """ + Mark a CLI Option to be "eager", ensuring it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early. + For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager). + """ + ), + ] = False, + envvar: Annotated[ + str | list[str] | None, + Doc( + """ + Configure a CLI Option to read its value from an environment variable if it is not provided in the command line. + For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/). + + **Example** + + ```python + @app.command() + def main(user: Annotated[str, typer.Option(envvar="ME")]): + print(f"Hello {user}") + ``` + """ + ), + ] = None, + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Annotated[ + Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + autocompletion: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Provide a custom function that helps to autocomplete the values of this CLI Option. + See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details. + + **Example** + + ```python + def complete(): + return ["Me", "Myself", "I"] + + @app.command() + def main(name: Annotated[str, typer.Option(autocompletion=complete)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Option. + + **Example** + + ```python + def get_name(): + return random.choice(["Me", "Myself", "I"]) + + @app.command() + def main(name: Annotated[str, typer.Option(default_factory=get_name)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + # Custom type + parser: Annotated[ + Callable[[str], Any] | None, + Doc( + """ + Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types: + + **Example** + + ```python + class CustomClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + def my_parser(value: str): + return CustomClass(value * 2) + + @app.command() + def main(opt: Annotated[CustomClass, typer.Option(parser=my_parser)] = "Foo"): + print(f"--opt is {opt}") + ``` + """ + ), + ] = None, + click_type: Annotated[ + click.ParamType | None, + Doc( + """ + Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications. + + **Example** + + ```python + class MyClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + class MyParser(click.ParamType): + name = "MyClass" + + def convert(self, value, param, ctx): + return MyClass(value * 3) + + @app.command() + def main(opt: Annotated[MyClass, typer.Option(click_type=MyParser())] = "Foo"): + print(f"--opt is {opt}") + ``` + """ + ), + ] = None, + # Option + show_default: Annotated[ + bool | str, + Doc( + """ + When set to `False`, don't show the default value of this CLI Option in the [help text](https://typer.tiangolo.com/tutorial/options/help/). + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Option(show_default=False)] = "Rick"): + print(f"Hello {name}") + ``` + """ + ), + ] = True, + prompt: Annotated[ + bool | str, + Doc( + """ + When set to `True`, a prompt will appear to ask for the value of this CLI Option if it was not provided: + + **Example** + + ```python + @app.command() + def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]): + print(f"Hello {name} {lastname}") + ``` + """ + ), + ] = False, + confirmation_prompt: Annotated[ + bool, + Doc( + """ + When set to `True`, a user will need to type a prompted value twice (may be useful for passwords etc.). + + **Example** + + ```python + @app.command() + def main(project: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]): + print(f"Deleting project {project}") + ``` + """ + ), + ] = False, + prompt_required: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is `False` then a prompt is only shown if the option's flag is given without a value. + """ + ), + ] = True, + hide_input: Annotated[ + bool, + Doc( + """ + When you've configured a prompt, for instance for [querying a password](https://typer.tiangolo.com/tutorial/options/password/), + don't show anything on the screen while the user is typing the value. + + **Example** + + ```python + @app.command() + def login( + name: str, + password: Annotated[str, typer.Option(prompt=True, hide_input=True)], + ): + print(f"Hello {name}. Doing something very secure with password.") + ``` + """ + ), + ] = False, + # TODO: remove is_flag and flag_value in a future release + is_flag: Annotated[ + bool | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + flag_value: Annotated[ + Any | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + count: Annotated[ + bool, + Doc( + """ + Make a CLI Option work as a [counter](https://typer.tiangolo.com/tutorial/parameter-types/number/#counter-cli-options). + The CLI option will have the `int` value representing the number of times the option was used on the command line. + + **Example** + + ```python + @app.command() + def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0): + print(f"Verbose level is {verbose}") + ``` + """ + ), + ] = False, + allow_from_autoenv: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. + """ + ), + ] = True, + help: Annotated[ + str | None, + Doc( + """ + Help text for this CLI Option. + See [the tutorial about CLI Options with help](https://typer.tiangolo.com/tutorial/options/help/) for more dedails. + + **Example** + + ```python + @app.command() + def greet(name: Annotated[str, typer.Option(help="Person to greet")] = "Deadpool"): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + hidden: Annotated[ + bool, + Doc( + """ + Hide this CLI Option from [help outputs](https://typer.tiangolo.com/tutorial/options/help). `False` by default. + + **Example** + + ```python + @app.command() + def greet(name: Annotated[str, typer.Option(hidden=True)] = "Deadpool"): + print(f"Hello {name}") + ``` + """ + ), + ] = False, + show_choices: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + When set to `False`, this suppresses choices from being displayed inline when `prompt` is used. + """ + ), + ] = True, + show_envvar: Annotated[ + bool, + Doc( + """ + When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text: + + **Example** + + ```python + @app.command() + def main(user: Annotated[str, typer.Option(envvar="ME", show_envvar=False)]): + print(f"Hello {user}") + ``` + """ + ), + ] = True, + # Choice + case_sensitive: Annotated[ + bool, + Doc( + """ + For a CLI Option representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum), + you can allow case-insensitive matching with this parameter: + + **Example** + + ```python + from enum import Enum + + class NeuralNetwork(str, Enum): + simple = "simple" + conv = "conv" + lstm = "lstm" + + @app.command() + def main( + network: Annotated[NeuralNetwork, typer.Option(case_sensitive=False)]): + print(f"Training neural network of type: {network.value}") + ``` + + With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`. + """ + ), + ] = True, + # Numbers + min: Annotated[ + int | float | None, + Doc( + """ + For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Option(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + max: Annotated[ + int | float | None, + Doc( + """ + For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Option(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + clamp: Annotated[ + bool, + Doc( + """ + For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`, + you can opt to use the closest minimum or maximum value instead of raising an error when the value is out of bounds. This is done by setting `clamp` to `True`. + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Option(min=1, max=1000, clamp=True)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`. + """ + ), + ] = False, + # DateTime + formats: Annotated[ + list[str] | None, + Doc( + """ + For a CLI Option representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime), + you can customize the formats that can be parsed automatically: + + **Example** + + ```python + from datetime import datetime + + @app.command() + def main( + birthday: Annotated[ + datetime, + typer.Option( + formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"] + ), + ], + ): + print(f"Birthday defined at: {birthday}") + ``` + """ + ), + ] = None, + # File + mode: Annotated[ + str | None, + Doc( + """ + For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(mode="a")]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + encoding: Annotated[ + str | None, + Doc( + """ + Customize the encoding of this CLI Option represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(encoding="utf-8")]): + config.write("All the text gets written\\n") + ``` + """ + ), + ] = None, + errors: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + The error handling mode. + """ + ), + ] = "strict", + lazy: Annotated[ + bool | None, + Doc( + """ + For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + by default the file will not be created until you actually start writing to it. + You can change this behaviour by setting this parameter. + By default, it's set to `True` for writing and to `False` for reading. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(mode="a", lazy=False)]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + atomic: Annotated[ + bool, + Doc( + """ + For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing + by setting `atomic` to `True`. This can be useful for files with potential concurrent access. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Option(mode="a", atomic=True)]): + config.write("All the text") + ``` + """ + ), + ] = False, + # Path + exists: Annotated[ + bool, + Doc( + """ + When set to `True` for a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/), + additional validation is performed to check that the file or directory exists. If not, the value will be invalid. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(exists=True)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = False, + file_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(exists=True, file_okay=False)]): + print(f"Directory listing: {[x.name for x in config.iterdir()]}") + ``` + """ + ), + ] = True, + dir_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = True, + writable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a writable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(writable=True)]): + config.write_text("All the text") + ``` + """ + ), + ] = False, + readable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a readable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(readable=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = True, + resolve_path: Annotated[ + bool, + Doc( + """ + Whether or not to fully resolve the path of this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/), + meaning that the path becomes absolute and symlinks are resolved. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Option(resolve_path=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = False, + allow_dash: Annotated[ + bool, + Doc( + """ + When set to `True`, a single dash for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/) + would be a valid value, indicating standard streams. This is a more advanced use-case. + """ + ), + ] = False, + path_type: Annotated[ + None | type[str] | type[bytes], + Doc( + """ + A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data. + This is a more advanced use-case. + """ + ), + ] = None, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name where you want this CLI Option to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help). + + **Example** + + ```python + @app.command() + def main( + name: Annotated[str, typer.Argument(help="Who to greet")], + age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")], + ): + print(f"Hello {name} of age {age}") + ``` + """ + ), + ] = None, +) -> Any: + """ + A [CLI Option](https://typer.tiangolo.com/tutorial/options) is a parameter to your command line application that is called with a single or double dash, something like `--verbose` or `-v`. + + Often, CLI Options are optional, meaning that users can omit them from the command. However, you can set them to be required by using `Annotated` + and omitting a default value. + + ## Example + + ```python + @app.command() + def register( + user: Annotated[str, typer.Argument()], + age: Annotated[int, typer.Option(min=18)], + ): + print(f"User is {user}") + print(f"--age is {age}") + ``` + + Note how in this example, `--age` is a required CLI Option. + """ + return OptionInfo( + # Parameter + default=default, + param_decls=param_decls, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # Option + show_default=show_default, + prompt=prompt, + confirmation_prompt=confirmation_prompt, + prompt_required=prompt_required, + hide_input=hide_input, + is_flag=is_flag, + flag_value=flag_value, + count=count, + allow_from_autoenv=allow_from_autoenv, + help=help, + hidden=hidden, + show_choices=show_choices, + show_envvar=show_envvar, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) + + +# Overload for Argument created with custom type 'parser' +@overload +def Argument( + # Parameter + default: Any | None = ..., + *, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + parser: Callable[[str], Any] | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +# Overload for Argument created with custom type 'click_type' +@overload +def Argument( + # Parameter + default: Any | None = ..., + *, + callback: Callable[..., Any] | None = None, + metavar: str | None = None, + expose_value: bool = True, + is_eager: bool = False, + envvar: str | list[str] | None = None, + # Note that shell_complete is not fully supported and will be removed in future versions + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None = None, + autocompletion: Callable[..., Any] | None = None, + default_factory: Callable[[], Any] | None = None, + # Custom type + click_type: click.ParamType | None = None, + # TyperArgument + show_default: bool | str = True, + show_choices: bool = True, + show_envvar: bool = True, + help: str | None = None, + hidden: bool = False, + # Choice + case_sensitive: bool = True, + # Numbers + min: int | float | None = None, + max: int | float | None = None, + clamp: bool = False, + # DateTime + formats: list[str] | None = None, + # File + mode: str | None = None, + encoding: str | None = None, + errors: str | None = "strict", + lazy: bool | None = None, + atomic: bool = False, + # Path + exists: bool = False, + file_okay: bool = True, + dir_okay: bool = True, + writable: bool = False, + readable: bool = True, + resolve_path: bool = False, + allow_dash: bool = False, + path_type: None | type[str] | type[bytes] = None, + # Rich settings + rich_help_panel: str | None = None, +) -> Any: ... + + +def Argument( + # Parameter + default: Annotated[ + Any | None, + Doc( + """ + By default, CLI arguments are required. However, by giving them a default value they become [optional](https://typer.tiangolo.com/tutorial/arguments/optional): + + **Example** + + ```python + @app.command() + def main(name: str = typer.Argument("World")): + print(f"Hello {name}!") + ``` + + Note that this usage is deprecated, and we recommend to use `Annotated` instead: + ```python + @app.command() + def main(name: Annotated[str, typer.Argument()] = "World"): + print(f"Hello {name}!") + ``` + """ + ), + ] = ..., + *, + callback: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Add a callback to this CLI Argument, to execute additional logic with the value received from the terminal. + See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details. + + **Example** + + ```python + def name_callback(value: str): + if value != "Deadpool": + raise typer.BadParameter("Only Deadpool is allowed") + return value + + @app.command() + def main(name: Annotated[str, typer.Argument(callback=name_callback)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + metavar: Annotated[ + str | None, + Doc( + """ + Customize the name displayed in the help text to represent this CLI Argument. + By default, it will be the same name you declared, in uppercase. + See [the tutorial about CLI Arguments with Help](https://typer.tiangolo.com/tutorial/arguments/help/#custom-help-name-metavar) for more details. + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(metavar="✨username✨")]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + expose_value: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped. + """ + ), + ] = True, + is_eager: Annotated[ + bool, + Doc( + """ + Set an argument to "eager" to ensure it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early. + For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager). + """ + ), + ] = False, + envvar: Annotated[ + str | list[str] | None, + Doc( + """ + Configure an argument to read a value from an environment variable if it is not provided in the command line as a CLI argument. + For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/). + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(envvar="ME")]): + print(f"Hello Mr. {name}") + ``` + """ + ), + ] = None, + # TODO: Remove shell_complete in a future version (after 0.16.0) + shell_complete: Annotated[ + Callable[ + [click.Context, click.Parameter, str], + list["click.shell_completion.CompletionItem"] | list[str], + ] + | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + It is however not fully functional, and will likely be removed in future versions. + """ + ), + ] = None, + autocompletion: Annotated[ + Callable[..., Any] | None, + Doc( + """ + Provide a custom function that helps to autocomplete the values of this CLI Argument. + See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details. + + **Example** + + ```python + def complete(): + return ["Me", "Myself", "I"] + + @app.command() + def main(name: Annotated[str, typer.Argument(autocompletion=complete)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + default_factory: Annotated[ + Callable[[], Any] | None, + Doc( + """ + Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Argument. + + **Example** + + ```python + def get_name(): + return random.choice(["Me", "Myself", "I"]) + + @app.command() + def main(name: Annotated[str, typer.Argument(default_factory=get_name)]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + # Custom type + parser: Annotated[ + Callable[[str], Any] | None, + Doc( + """ + Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types: + + **Example** + + ```python + class CustomClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + def my_parser(value: str): + return CustomClass(value * 2) + + @app.command() + def main(arg: Annotated[CustomClass, typer.Argument(parser=my_parser): + print(f"arg is {arg}") + ``` + """ + ), + ] = None, + click_type: Annotated[ + click.ParamType | None, + Doc( + """ + Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications. + + **Example** + + ```python + class MyClass: + def __init__(self, value: str): + self.value = value + + def __str__(self): + return f"" + + class MyParser(click.ParamType): + name = "MyClass" + + def convert(self, value, param, ctx): + return MyClass(value * 3) + + @app.command() + def main(arg: Annotated[MyClass, typer.Argument(click_type=MyParser())]): + print(f"arg is {arg}") + ``` + """ + ), + ] = None, + # TyperArgument + show_default: Annotated[ + bool | str, + Doc( + """ + When set to `False`, don't show the default value of this CLI Argument in the [help text](https://typer.tiangolo.com/tutorial/arguments/help/). + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(show_default=False)] = "Rick"): + print(f"Hello {name}") + ``` + """ + ), + ] = True, + show_choices: Annotated[ + bool, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + When set to `False`, this suppresses choices from being displayed inline when `prompt` is used. + """ + ), + ] = True, + show_envvar: Annotated[ + bool, + Doc( + """ + When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text: + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(envvar="ME", show_envvar=False)]): + print(f"Hello Mr. {name}") + ``` + """ + ), + ] = True, + help: Annotated[ + str | None, + Doc( + """ + Help text for this CLI Argument. + See [the tutorial about CLI Arguments with help](https://typer.tiangolo.com/tutorial/arguments/help/) for more dedails. + + **Example** + + ```python + @app.command() + def greet(name: Annotated[str, typer.Argument(help="Person to greet")]): + print(f"Hello {name}") + ``` + """ + ), + ] = None, + hidden: Annotated[ + bool, + Doc( + """ + Hide this CLI Argument from [help outputs](https://typer.tiangolo.com/tutorial/arguments/help). `False` by default. + + **Example** + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument(hidden=True)] = "World"): + print(f"Hello {name}") + ``` + """ + ), + ] = False, + # Choice + case_sensitive: Annotated[ + bool, + Doc( + """ + For a CLI Argument representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum), + you can allow case-insensitive matching with this parameter: + + **Example** + + ```python + from enum import Enum + + class NeuralNetwork(str, Enum): + simple = "simple" + conv = "conv" + lstm = "lstm" + + @app.command() + def main( + network: Annotated[NeuralNetwork, typer.Argument(case_sensitive=False)]): + print(f"Training neural network of type: {network.value}") + ``` + + With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`. + """ + ), + ] = True, + # Numbers + min: Annotated[ + int | float | None, + Doc( + """ + For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Argument(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + max: Annotated[ + int | float | None, + Doc( + """ + For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`), + you can define numeric validations with `min` and `max` values: + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Argument(min=1, max=1000)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid. + """ + ), + ] = None, + clamp: Annotated[ + bool, + Doc( + """ + For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`, + you can opt to use the closest minimum or maximum value instead of raising an error. This is done by setting `clamp` to `True`. + + **Example** + + ```python + @app.command() + def main( + user: Annotated[str, typer.Argument()], + user_id: Annotated[int, typer.Argument(min=1, max=1000, clamp=True)], + ): + print(f"ID for {user} is {user_id}") + ``` + + If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`. + """ + ), + ] = False, + # DateTime + formats: Annotated[ + list[str] | None, + Doc( + """ + For a CLI Argument representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime), + you can customize the formats that can be parsed automatically: + + **Example** + + ```python + from datetime import datetime + + @app.command() + def main( + birthday: Annotated[ + datetime, + typer.Argument( + formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"] + ), + ], + ): + print(f"Birthday defined at: {birthday}") + ``` + """ + ), + ] = None, + # File + mode: Annotated[ + str | None, + Doc( + """ + For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(mode="a")]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + encoding: Annotated[ + str | None, + Doc( + """ + Customize the encoding of this CLI Argument represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/). + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(encoding="utf-8")]): + config.write("All the text gets written\\n") + ``` + """ + ), + ] = None, + errors: Annotated[ + str | None, + Doc( + """ + **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility. + + --- + + The error handling mode. + """ + ), + ] = "strict", + lazy: Annotated[ + bool | None, + Doc( + """ + For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + by default the file will not be created until you actually start writing to it. + You can change this behaviour by setting this parameter. + By default, it's set to `True` for writing and to `False` for reading. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(mode="a", lazy=False)]): + config.write("This is a single line\\n") + print("Config line written") + ``` + """ + ), + ] = None, + atomic: Annotated[ + bool, + Doc( + """ + For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/), + you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing + by setting `atomic` to `True`. This can be useful for files with potential concurrent access. + + **Example** + + ```python + @app.command() + def main(config: Annotated[typer.FileText, typer.Argument(mode="a", atomic=True)]): + config.write("All the text") + ``` + """ + ), + ] = False, + # Path + exists: Annotated[ + bool, + Doc( + """ + When set to `True` for a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/), + additional validation is performed to check that the file or directory exists. If not, the value will be invalid. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = False, + file_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True, file_okay=False)]): + print(f"Directory listing: {[x.name for x in config.iterdir()]}") + ``` + """ + ), + ] = True, + dir_okay: Annotated[ + bool, + Doc( + """ + Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/) + is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]): + text = config.read_text() + print(f"Config file contents: {text}") + ``` + """ + ), + ] = True, + writable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a writable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(writable=True)]): + config.write_text("All the text") + ``` + """ + ), + ] = False, + readable: Annotated[ + bool, + Doc( + """ + Whether or not to perform a readable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(readable=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = True, + resolve_path: Annotated[ + bool, + Doc( + """ + Whether or not to fully resolve the path of this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/), + meaning that the path becomes absolute and symlinks are resolved. + + **Example** + + ```python + from pathlib import Path + + @app.command() + def main(config: Annotated[Path, typer.Argument(resolve_path=True)]): + config.read_text("All the text") + ``` + """ + ), + ] = False, + allow_dash: Annotated[ + bool, + Doc( + """ + When set to `True`, a single dash for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/) + would be a valid value, indicating standard streams. This is a more advanced use-case. + """ + ), + ] = False, + path_type: Annotated[ + None | type[str] | type[bytes], + Doc( + """ + A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/). + The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data. + This is a more advanced use-case. + """ + ), + ] = None, + # Rich settings + rich_help_panel: Annotated[ + str | None, + Doc( + """ + Set the panel name where you want this CLI Argument to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help). + + **Example** + + ```python + @app.command() + def main( + name: Annotated[str, typer.Argument(help="Who to greet")], + age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")], + ): + print(f"Hello {name} of age {age}") + ``` + """ + ), + ] = None, +) -> Any: + """ + A [CLI Argument](https://typer.tiangolo.com/tutorial/arguments) is a positional parameter to your command line application. + + Often, CLI Arguments are required, meaning that users have to specify them. However, you can set them to be optional by defining a default value: + + ## Example + + ```python + @app.command() + def main(name: Annotated[str, typer.Argument()] = "World"): + print(f"Hello {name}!") + ``` + + Note how in this example, if `name` is not specified on the command line, the application will still execute normally and print "Hello World!". + """ + return ArgumentInfo( + # Parameter + default=default, + # Arguments can only have one param declaration + # it will be generated from the param name + param_decls=None, + callback=callback, + metavar=metavar, + expose_value=expose_value, + is_eager=is_eager, + envvar=envvar, + shell_complete=shell_complete, + autocompletion=autocompletion, + default_factory=default_factory, + # Custom type + parser=parser, + click_type=click_type, + # TyperArgument + show_default=show_default, + show_choices=show_choices, + show_envvar=show_envvar, + help=help, + hidden=hidden, + # Choice + case_sensitive=case_sensitive, + # Numbers + min=min, + max=max, + clamp=clamp, + # DateTime + formats=formats, + # File + mode=mode, + encoding=encoding, + errors=errors, + lazy=lazy, + atomic=atomic, + # Path + exists=exists, + file_okay=file_okay, + dir_okay=dir_okay, + writable=writable, + readable=readable, + resolve_path=resolve_path, + allow_dash=allow_dash, + path_type=path_type, + # Rich settings + rich_help_panel=rich_help_panel, + ) diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/py.typed b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/rich_utils.py b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/rich_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d85043238c3d47a89cd6d5127fce198c0564f0b7 --- /dev/null +++ b/.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/rich_utils.py @@ -0,0 +1,753 @@ +# Extracted and modified from https://github.com/ewels/rich-click + +import inspect +import io +from collections import defaultdict +from collections.abc import Iterable +from gettext import gettext as _ +from os import getenv +from typing import Any, Literal + +import click +from rich import box +from rich.align import Align +from rich.columns import Columns +from rich.console import Console, RenderableType, group +from rich.emoji import Emoji +from rich.highlighter import RegexHighlighter +from rich.markdown import Markdown +from rich.markup import escape +from rich.padding import Padding +from rich.panel import Panel +from rich.table import Table +from rich.text import Text +from rich.theme import Theme +from rich.traceback import Traceback +from typer.models import DeveloperExceptionConfig + +# Default styles +STYLE_OPTION = "bold cyan" +STYLE_SWITCH = "bold green" +STYLE_NEGATIVE_OPTION = "bold magenta" +STYLE_NEGATIVE_SWITCH = "bold red" +STYLE_METAVAR = "bold yellow" +STYLE_METAVAR_SEPARATOR = "dim" +STYLE_USAGE = "yellow" +STYLE_USAGE_COMMAND = "bold" +STYLE_DEPRECATED = "red" +STYLE_DEPRECATED_COMMAND = "dim" +STYLE_HELPTEXT_FIRST_LINE = "" +STYLE_HELPTEXT = "dim" +STYLE_OPTION_HELP = "" +STYLE_OPTION_DEFAULT = "dim" +STYLE_OPTION_ENVVAR = "dim yellow" +STYLE_REQUIRED_SHORT = "red" +STYLE_REQUIRED_LONG = "dim red" +STYLE_OPTIONS_PANEL_BORDER = "dim" +ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left" +STYLE_OPTIONS_TABLE_SHOW_LINES = False +STYLE_OPTIONS_TABLE_LEADING = 0 +STYLE_OPTIONS_TABLE_PAD_EDGE = False +STYLE_OPTIONS_TABLE_PADDING = (0, 1) +STYLE_OPTIONS_TABLE_BOX = "" +STYLE_OPTIONS_TABLE_ROW_STYLES = None +STYLE_OPTIONS_TABLE_BORDER_STYLE = None +STYLE_COMMANDS_PANEL_BORDER = "dim" +ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left" +STYLE_COMMANDS_TABLE_SHOW_LINES = False +STYLE_COMMANDS_TABLE_LEADING = 0 +STYLE_COMMANDS_TABLE_PAD_EDGE = False +STYLE_COMMANDS_TABLE_PADDING = (0, 1) +STYLE_COMMANDS_TABLE_BOX = "" +STYLE_COMMANDS_TABLE_ROW_STYLES = None +STYLE_COMMANDS_TABLE_BORDER_STYLE = None +STYLE_COMMANDS_TABLE_FIRST_COLUMN = "bold cyan" +STYLE_ERRORS_PANEL_BORDER = "red" +ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left" +STYLE_ERRORS_SUGGESTION = "dim" +STYLE_ABORTED = "red" +_TERMINAL_WIDTH = getenv("TERMINAL_WIDTH") +MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None +COLOR_SYSTEM: Literal["auto", "standard", "256", "truecolor", "windows"] | None = ( + "auto" # Set to None to disable colors +) +_TYPER_FORCE_DISABLE_TERMINAL = getenv("_TYPER_FORCE_DISABLE_TERMINAL") +FORCE_TERMINAL = ( + True + if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS") + else None +) +if _TYPER_FORCE_DISABLE_TERMINAL: + FORCE_TERMINAL = False + +# Fixed strings +DEPRECATED_STRING = _("(deprecated) ") +DEFAULT_STRING = _("[default: {}]") +ENVVAR_STRING = _("[env var: {}]") +REQUIRED_SHORT_STRING = "*" +REQUIRED_LONG_STRING = _("[required]") +RANGE_STRING = " [{}]" +ARGUMENTS_PANEL_TITLE = _("Arguments") +OPTIONS_PANEL_TITLE = _("Options") +COMMANDS_PANEL_TITLE = _("Commands") +ERRORS_PANEL_TITLE = _("Error") +ABORTED_TEXT = _("Aborted.") +RICH_HELP = _("Try [blue]'{command_path} {help_option}'[/] for help.") + +MARKUP_MODE_MARKDOWN = "markdown" +MARKUP_MODE_RICH = "rich" +_RICH_HELP_PANEL_NAME = "rich_help_panel" +ANSI_PREFIX = "\033[" + +MarkupModeStrict = Literal["markdown", "rich"] + + +# Rich regex highlighter +class OptionHighlighter(RegexHighlighter): + """Highlights our special options.""" + + highlights = [ + r"(^|\W)(?P\-\w+)(?![a-zA-Z0-9])", + r"(^|\W)(?P