Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .cache/pip/http-v2/a/3/2/f/7/a32f793a951b4bb55e15bb0126f9c9127aab8cec4ba5607016d8841e.bodyAdded+3
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/METADATAAdded+412
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/RECORDAdded+22
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/entry_points.txtAdded+5
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/licenses/LICENSEAdded+21
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__init__.pyAdded+39
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__main__.pyAdded+3
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_classes.pyAdded+199
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_shared.pyAdded+252
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_types.pyAdded+27
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_typing.pyAdded+73
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/cli.pyAdded+317
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/colors.pyAdded+20
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/completion.pyAdded+146
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/core.pyAdded+821
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/main.pyAdded+2013
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/models.pyAdded+651
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/params.pyAdded+1831
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/py.typedAdded
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/rich_utils.pyAdded+753
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/testing.pyAdded+30
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/utils.pyAdded+197
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/METADATAAdded+84
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/RECORDAdded+22
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/WHEELAdded+4
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/licenses/LICENSE.txtAdded+28
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/__init__.pyAdded+123
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_compat.pyAdded+622
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_termui_impl.pyAdded+852
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_textwrap.pyAdded+51
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_utils.pyAdded+36
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_winconsole.pyAdded+296
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/core.pyAdded
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/decorators.pyAdded+551
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/exceptions.pyAdded+308
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/formatting.pyAdded+301
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/globals.pyAdded+67
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/parser.pyAdded+532
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/py.typedAdded
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/shell_completion.pyAdded+667
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/termui.pyAdded+883
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/testing.pyAdded+574
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/types.pyAdded+1209
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/utils.pyAdded+627
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/__init__.pyAdded+62
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_abnf.pyAdded+132
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_connection.pyAdded+659
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_events.pyAdded+369
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_headers.pyAdded+282
123version https://git-lfs.github.com/spec/v1oid sha256:149f7d84afca659d1a97e39a4778794a2f83bf344c5ee5134e09995086cc2392size 4988768123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412Metadata-Version: 2.4Name: typerVersion: 0.24.1Summary: Typer, build great CLIs. Easy to code. Based on Python type hints.Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>License-Expression: MITLicense-File: LICENSEClassifier: Intended Audience :: Information TechnologyClassifier: Intended Audience :: System AdministratorsClassifier: Operating System :: OS IndependentClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: PythonClassifier: Topic :: Software Development :: Libraries :: Application FrameworksClassifier: Topic :: Software Development :: Libraries :: Python ModulesClassifier: Topic :: Software Development :: LibrariesClassifier: Topic :: Software DevelopmentClassifier: Typing :: TypedClassifier: Development Status :: 4 - BetaClassifier: Intended Audience :: DevelopersClassifier: Programming Language :: Python :: 3 :: OnlyClassifier: Programming Language :: Python :: 3.10Classifier: Programming Language :: Python :: 3.11Classifier: Programming Language :: Python :: 3.12Classifier: Programming Language :: Python :: 3.13Classifier: Programming Language :: Python :: 3.14Project-URL: Homepage, https://github.com/fastapi/typerProject-URL: Documentation, https://typer.tiangolo.comProject-URL: Repository, https://github.com/fastapi/typerProject-URL: Issues, https://github.com/fastapi/typer/issuesProject-URL: Changelog, https://typer.tiangolo.com/release-notes/Requires-Python: >=3.10Requires-Dist: click>=8.2.1Requires-Dist: shellingham>=1.3.0Requires-Dist: rich>=12.3.0Requires-Dist: annotated-doc>=0.0.2Description-Content-Type: text/markdown
<p align="center"> <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>
</p><p align="center"> <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em></p><p align="center"><a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank"> <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test"></a><a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish" target="_blank"> <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish"></a><a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer" target="_blank"> <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage"><a href="https://pypi.org/project/typer" target="_blank"> <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version"></a></p>
---
**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com</a>
**Source Code**: <a href="https://github.com/fastapi/typer" target="_blank">https://github.com/fastapi/typer</a>
---
Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> 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. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> 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 <a href="https://forms.gle/nYvutPrVkmBQZLas7" class="external-link" target="_blank">Typer developer survey</a>. ✨
## FastAPI of CLIs
**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.
## Installation
Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:
<div class="termy">
```console$ pip install typer---> 100%Successfully installed typer rich shellingham```
</div>
## Example
### The absolute minimum
* Create a file `main.py` with:
```Pythondef 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:
<div class="termy">
```console// Run your application$ typer main.py run
// You get a nice error, you are missing NAMEUsage: typer [PATH_OR_MODULE] run [OPTIONS] NAMETry '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! 🎉```
</div>
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:
```Pythonimport typer
def main(name: str): print(f"Hello {name}")
if __name__ == "__main__": typer.run(main)```
Now you could run it with Python directly:
<div class="termy">
```console// Run your application$ python main.py
// You get a nice error, you are missing NAMEUsage: main.py [OPTIONS] NAMETry '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! 🎉```
</div>
**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:
<div class="termy">
```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```
</div>
Now check the help for the `hello` command:
<div class="termy">
```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. │╰───────────────────────────────────────────────────╯```
</div>
And now check the help for the `goodbye` command:
<div class="termy">
```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 🎉```
</div>
Now you can try out the new command line application:
<div class="termy">
```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.```
</div>
**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`:
```Pythontotal: int```
or for a `bool` flag:
```Pythonforce: 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 <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
## Dependencies
**Typer** stands on the shoulders of giants. It has three required dependencies:
* <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>: a popular tool for building CLIs in Python. Typer is based on it.* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: 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.12345678910111213141516171819202122typer-0.24.1.dist-info/METADATA,sha256=V4OWoWjBhPNcoIaOxhr1cszo69nePKOHMRXERkMscKs,16057typer-0.24.1.dist-info/WHEEL,sha256=Wb0ASbVj8JvWHpOiIpPi7ucfIgJeCi__PzivviEAQFc,90typer-0.24.1.dist-info/entry_points.txt,sha256=YO13ByiqWeuas9V0JADLUARZFUe_cwU_7wmTNvxBYQ8,57typer-0.24.1.dist-info/licenses/LICENSE,sha256=WJks68-N-25AxOIRLtEhJsJDZm3KORKj14t-ysSFnUk,1086typer/__init__.py,sha256=WOelHJu4PW0hk9nfjEX0Qxssb58NCh1km_Xq5LY_33s,1596typer/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30typer/_completion_classes.py,sha256=R9v4D8pJ_-n8fLOuyxrRSu7sP5lpXIy5fsLUW8zwsDU,7039typer/_completion_shared.py,sha256=-uhCUIMc2S1ywdB-fBSSccH70mIBEsVTxHomcmy-klE,9129typer/_types.py,sha256=0lcBDLcsxqr1sxTsqObj_u0Dfa37lWJYUY4PNkX4QlA,974typer/_typing.py,sha256=QOw5o-B2L--C3ly2DQH6aUwag6x5brV5FhVaBZ5gzMg,1727typer/cli.py,sha256=icRbazvdRdbYeaidPZOmJDOzrP3RAa7vj2INVV9Zb8Q,10183typer/colors.py,sha256=e42j8uB520hLpX5C_0fiR3OOoIFMbhO3ADZvv6hlAV8,430typer/completion.py,sha256=FRTR9hP_IPdJp-4GXPOq0btXo5SvgAtLVfS3ZkAMpgQ,4793typer/core.py,sha256=O5NywSwHPyYbLhZkPYSfwIj7Za2hPnoPP4xPXRa97a0,27947typer/main.py,sha256=xyNex-QfGUi-enu9j9rl-_wofApxs5VwdpCthAUAAkk,69005typer/models.py,sha256=OwPG3MAXiUD5ih3p8eNVciXUsL07UIJfNWy3JiNpDfg,19843typer/params.py,sha256=AovViRtl-VvUIXnmKKpnxoWK9_gHUbyQgXxxv3h_7lI,59713typer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0typer/rich_utils.py,sha256=RTyeoxwz16ZZXYbwoEixB_LSEnqpoStG_TGCRTz6zFQ,25424typer/testing.py,sha256=-ovLNjUNNEFCJoau-41iTJIobsjPbqyTrRq7-8ac4z4,871typer/utils.py,sha256=wnJ1DWXBFMnxLHaMN_HDYntxLRby0K-rux63aokHInI,7599typer-0.24.1.dist-info/RECORD,,1234Wheel-Version: 1.0Generator: pdm-backend (2.4.7)Root-Is-Purelib: trueTag: py3-none-any12345[console_scripts]typer = typer.cli:main
[gui_scripts]
123456789101112131415161718192021The MIT License (MIT)
Copyright (c) 2019 Sebastián Ramírez
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 INTHE SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839"""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 Abortfrom click.exceptions import BadParameter as BadParameterfrom click.exceptions import Exit as Exitfrom click.termui import clear as clearfrom click.termui import confirm as confirmfrom click.termui import echo_via_pager as echo_via_pagerfrom click.termui import edit as editfrom click.termui import getchar as getcharfrom click.termui import pause as pausefrom click.termui import progressbar as progressbarfrom click.termui import prompt as promptfrom click.termui import secho as sechofrom click.termui import style as stylefrom click.termui import unstyle as unstylefrom click.utils import echo as echofrom click.utils import format_filename as format_filenamefrom click.utils import get_app_dir as get_app_dirfrom click.utils import get_binary_stream as get_binary_streamfrom click.utils import get_text_stream as get_text_streamfrom click.utils import open_file as open_file
from . import colors as colorsfrom .main import Typer as Typerfrom .main import launch as launchfrom .main import run as runfrom .models import CallbackParam as CallbackParamfrom .models import Context as Contextfrom .models import FileBinaryRead as FileBinaryReadfrom .models import FileBinaryWrite as FileBinaryWritefrom .models import FileText as FileTextfrom .models import FileTextWrite as FileTextWritefrom .params import Argument as Argumentfrom .params import Option as Option123from .cli import main
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import importlib.utilimport osimport reimport sysfrom typing import Any
import clickimport click.parserimport click.shell_completionfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252import osimport reimport subprocessfrom enum import Enumfrom pathlib import Path
import clickimport 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 PSReadLineSet-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 name123456789101112131415161718192021222324252627from enum import Enumfrom 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_value12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# 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 typesfrom collections.abc import Callablefrom 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))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317import importlib.utilimport reimport sysfrom pathlib import Pathfrom typing import Any
import clickimport typerimport typer.corefrom 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()1234567891011121314151617181920# Variable names to colors, just for completionBLACK = "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"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146import osimport sysfrom collections.abc import MutableMappingfrom typing import Any
import click
from ._completion_classes import completion_initfrom ._completion_shared import Shells, _get_shell_name, get_completion_script, installfrom .models import ParamMetafrom .params import Optionfrom .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 parametersdef _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 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821import errnoimport inspectimport osimport sysfrom collections.abc import Callable, MutableMapping, Sequencefrom difflib import get_close_matchesfrom enum import Enumfrom gettext import gettext as _from typing import ( Any, TextIO, Union, cast,)
import clickimport click.coreimport click.formattingimport click.shell_completionimport click.typesimport click.utils
from ._typing import Literalfrom .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_optdef _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()]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013import inspectimport osimport platformimport shutilimport subprocessimport sysimport tracebackfrom collections.abc import Callable, Sequencefrom datetime import datetimefrom enum import Enumfrom functools import update_wrapperfrom pathlib import Pathfrom traceback import FrameSummary, StackSummaryfrom types import TracebackTypefrom typing import Annotated, Anyfrom uuid import UUID
import clickfrom annotated_doc import Docfrom typer._types import TyperChoice
from ._typing import get_args, get_origin, is_literal_type, is_union, literal_valuesfrom .completion import get_completion_inspect_parametersfrom .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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651import inspectimport iofrom collections.abc import Callable, Sequencefrom typing import ( TYPE_CHECKING, Any, Optional, TypeVar,)
import clickimport 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 []1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831from collections.abc import Callablefrom typing import TYPE_CHECKING, Annotated, Any, overload
import clickfrom 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'@overloaddef 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'@overloaddef 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"<CustomClass: value={self.value}>"
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"<MyClass: value={self.value}>"
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'@overloaddef 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'@overloaddef 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"<CustomClass: value={self.value}>"
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"<MyClass: value={self.value}>"
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, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753# Extracted and modified from https://github.com/ewels/rich-click
import inspectimport iofrom collections import defaultdictfrom collections.abc import Iterablefrom gettext import gettext as _from os import getenvfrom typing import Any, Literal
import clickfrom rich import boxfrom rich.align import Alignfrom rich.columns import Columnsfrom rich.console import Console, RenderableType, groupfrom rich.emoji import Emojifrom rich.highlighter import RegexHighlighterfrom rich.markdown import Markdownfrom rich.markup import escapefrom rich.padding import Paddingfrom rich.panel import Panelfrom rich.table import Tablefrom rich.text import Textfrom rich.theme import Themefrom rich.traceback import Tracebackfrom typer.models import DeveloperExceptionConfig
# Default stylesSTYLE_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 = FalseSTYLE_OPTIONS_TABLE_LEADING = 0STYLE_OPTIONS_TABLE_PAD_EDGE = FalseSTYLE_OPTIONS_TABLE_PADDING = (0, 1)STYLE_OPTIONS_TABLE_BOX = ""STYLE_OPTIONS_TABLE_ROW_STYLES = NoneSTYLE_OPTIONS_TABLE_BORDER_STYLE = NoneSTYLE_COMMANDS_PANEL_BORDER = "dim"ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left"STYLE_COMMANDS_TABLE_SHOW_LINES = FalseSTYLE_COMMANDS_TABLE_LEADING = 0STYLE_COMMANDS_TABLE_PAD_EDGE = FalseSTYLE_COMMANDS_TABLE_PADDING = (0, 1)STYLE_COMMANDS_TABLE_BOX = ""STYLE_COMMANDS_TABLE_ROW_STYLES = NoneSTYLE_COMMANDS_TABLE_BORDER_STYLE = NoneSTYLE_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 NoneCOLOR_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 stringsDEPRECATED_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 highlighterclass OptionHighlighter(RegexHighlighter): """Highlights our special options."""
highlights = [ r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])", r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])", r"(?P<metavar>\<[^\>]+\>)", r"(?P<usage>Usage: )", ]
class NegativeOptionHighlighter(RegexHighlighter): highlights = [ r"(^|\W)(?P<negative_switch>\-\w+)(?![a-zA-Z0-9])", r"(^|\W)(?P<negative_option>\-\-[\w\-]+)(?![a-zA-Z0-9])", ]
# Highlighter to make [ | ] and <> dimclass MetavarHighlighter(RegexHighlighter): highlights = [ r"^(?P<metavar_sep>(\[|<))", r"(?P<metavar_sep>\|)", r"(?P<metavar_sep>(\]|>))(\.\.\.)?$", ]
highlighter = OptionHighlighter()negative_highlighter = NegativeOptionHighlighter()metavar_highlighter = MetavarHighlighter()
def _has_ansi_character(text: str) -> bool: return ANSI_PREFIX in text
def _get_rich_console(stderr: bool = False) -> Console: return Console( theme=Theme( { "option": STYLE_OPTION, "switch": STYLE_SWITCH, "negative_option": STYLE_NEGATIVE_OPTION, "negative_switch": STYLE_NEGATIVE_SWITCH, "metavar": STYLE_METAVAR, "metavar_sep": STYLE_METAVAR_SEPARATOR, "usage": STYLE_USAGE, }, ), highlighter=highlighter, color_system=COLOR_SYSTEM, force_terminal=FORCE_TERMINAL, width=MAX_WIDTH, stderr=stderr, )
def _make_rich_text( *, text: str, style: str = "", markup_mode: MarkupModeStrict) -> Markdown | Text: """Take a string, remove indentations, and return styled text.
If `markup_mode` is `"rich"`, the text is parsed for Rich markup strings. If `markup_mode` is `"markdown"`, parse as Markdown. """ # Remove indentations from input text text = inspect.cleandoc(text) if markup_mode == MARKUP_MODE_MARKDOWN: text = Emoji.replace(text) return Markdown(text, style=style) else: assert markup_mode == MARKUP_MODE_RICH if _has_ansi_character(text): return highlighter(Text.from_ansi(text, style=style)) else: return highlighter(Text.from_markup(text, style=style))
@group()def _get_help_text( *, obj: click.Command | click.Group, markup_mode: MarkupModeStrict,) -> Iterable[Markdown | Text]: """Build primary help text for a click command or group.
Returns the prose help text for a command or group, rendered either as a Rich Text object or as Markdown. If the command is marked as deprecated, the deprecated string will be prepended. """ # Prepend deprecated status if obj.deprecated: yield Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)
# Fetch and dedent the help text help_text = inspect.cleandoc(obj.help or "")
# Trim off anything that comes after \f on its own line help_text = help_text.partition("\f")[0]
# Get the first paragraph first_line, *remaining_paragraphs = help_text.split("\n\n")
# Remove single linebreaks if markup_mode != MARKUP_MODE_MARKDOWN and not first_line.startswith("\b"): first_line = first_line.replace("\n", " ") yield _make_rich_text( text=first_line.strip(), style=STYLE_HELPTEXT_FIRST_LINE, markup_mode=markup_mode, )
# Get remaining lines, remove single line breaks and format as dim if remaining_paragraphs: # Add a newline inbetween the header and the remaining paragraphs yield Text("") # Join with double linebreaks for markdown and Rich markup remaining_lines = "\n\n".join(remaining_paragraphs)
yield _make_rich_text( text=remaining_lines, style=STYLE_HELPTEXT, markup_mode=markup_mode, )
def _get_parameter_help( *, param: click.Option | click.Argument | click.Parameter, ctx: click.Context, markup_mode: MarkupModeStrict,) -> Columns: """Build primary help text for a click option or argument.
Returns the prose help text for an option or argument, rendered either as a Rich Text object or as Markdown. Additional elements are appended to show the default and required status if applicable. """ # import here to avoid cyclic imports from .core import TyperArgument, TyperOption
items: list[Text | Markdown] = []
# Get the environment variable first
envvar = getattr(param, "envvar", None) var_str = "" # https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L2720-L2726 if envvar is None: if ( getattr(param, "allow_from_autoenv", None) and getattr(ctx, "auto_envvar_prefix", None) is not None and param.name is not None ): envvar = f"{ctx.auto_envvar_prefix}_{param.name.upper()}" if envvar is not None: var_str = ( envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar) )
# Main help text help_value: str | None = getattr(param, "help", None) if help_value: paragraphs = help_value.split("\n\n") # Remove single linebreaks if markup_mode != MARKUP_MODE_MARKDOWN: paragraphs = [ x.replace("\n", " ").strip() if not x.startswith("\b") else "{}\n".format(x.strip("\b\n")) for x in paragraphs ] items.append( _make_rich_text( text="\n".join(paragraphs).strip(), style=STYLE_OPTION_HELP, markup_mode=markup_mode, ) )
# Environment variable AFTER help text if envvar and getattr(param, "show_envvar", None): items.append(Text(ENVVAR_STRING.format(var_str), style=STYLE_OPTION_ENVVAR))
# Default value # This uses Typer's specific param._get_default_string if isinstance(param, (TyperOption, TyperArgument)): default_value = param._extract_default_help_str(ctx=ctx) show_default_is_str = isinstance(param.show_default, str) if show_default_is_str or ( default_value is not None and (param.show_default or ctx.show_default) ): default_str = param._get_default_string( ctx=ctx, show_default_is_str=show_default_is_str, default_value=default_value, ) if default_str: items.append( Text( DEFAULT_STRING.format(default_str), style=STYLE_OPTION_DEFAULT, ) )
# Required? if param.required: items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG))
# Use Columns - this allows us to group different renderable types # (Text, Markdown) onto a single line. return Columns(items)
def _make_command_help( *, help_text: str, markup_mode: MarkupModeStrict,) -> Text | Markdown: """Build cli help text for a click group command.
That is, when calling help on groups with multiple subcommands (not the main help text when calling the subcommand help).
Returns the first paragraph of help text for a command, rendered either as a Rich Text object or as Markdown. Ignores single newlines as paragraph markers, looks for double only. """ paragraphs = inspect.cleandoc(help_text).split("\n\n") # Remove single linebreaks if markup_mode != MARKUP_MODE_RICH and not paragraphs[0].startswith("\b"): paragraphs[0] = paragraphs[0].replace("\n", " ") elif paragraphs[0].startswith("\b"): paragraphs[0] = paragraphs[0].replace("\b\n", "") return _make_rich_text( text=paragraphs[0].strip(), style=STYLE_OPTION_HELP, markup_mode=markup_mode, )
def _print_options_panel( *, name: str, params: list[click.Option] | list[click.Argument], ctx: click.Context, markup_mode: MarkupModeStrict, console: Console,) -> None: options_rows: list[list[RenderableType]] = [] required_rows: list[str | Text] = [] for param in params: # Short and long form opt_long_strs = [] opt_short_strs = [] secondary_opt_long_strs = [] secondary_opt_short_strs = [] for opt_str in param.opts: if "--" in opt_str: opt_long_strs.append(opt_str) else: opt_short_strs.append(opt_str) for opt_str in param.secondary_opts: if "--" in opt_str: secondary_opt_long_strs.append(opt_str) else: secondary_opt_short_strs.append(opt_str)
# Column for a metavar, if we have one metavar = Text(style=STYLE_METAVAR, overflow="fold") metavar_str = param.make_metavar(ctx=ctx) # Do it ourselves if this is a positional argument if ( isinstance(param, click.Argument) and param.name and metavar_str == param.name.upper() ): metavar_str = param.type.name.upper()
# Skip booleans and choices (handled above) if metavar_str != "BOOLEAN": metavar.append(metavar_str)
# Range - from # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501 # skip count with default range type if ( isinstance(param.type, click.types._NumberRangeBase) and isinstance(param, click.Option) and not (param.count and param.type.min == 0 and param.type.max is None) ): range_str = param.type._describe_range() if range_str: metavar.append(RANGE_STRING.format(range_str))
# Required asterisk required: str | Text = "" if param.required: required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT)
required_rows.append(required) options_rows.append( [ highlighter(",".join(opt_long_strs)), highlighter(",".join(opt_short_strs)), negative_highlighter(",".join(secondary_opt_long_strs)), negative_highlighter(",".join(secondary_opt_short_strs)), metavar_highlighter(metavar), _get_parameter_help( param=param, ctx=ctx, markup_mode=markup_mode, ), ] ) rows_with_required: list[list[RenderableType]] = [] if any(required_rows): for required, row in zip(required_rows, options_rows, strict=True): rows_with_required.append([required, *row]) else: rows_with_required = options_rows if options_rows: t_styles: dict[str, Any] = { "show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES, "leading": STYLE_OPTIONS_TABLE_LEADING, "box": STYLE_OPTIONS_TABLE_BOX, "border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE, "row_styles": STYLE_OPTIONS_TABLE_ROW_STYLES, "pad_edge": STYLE_OPTIONS_TABLE_PAD_EDGE, "padding": STYLE_OPTIONS_TABLE_PADDING, } box_style = getattr(box, t_styles.pop("box"), None)
options_table = Table( highlight=True, show_header=False, expand=True, box=box_style, **t_styles, ) for row in rows_with_required: options_table.add_row(*row) console.print( Panel( options_table, border_style=STYLE_OPTIONS_PANEL_BORDER, title=name, title_align=ALIGN_OPTIONS_PANEL, ) )
def _print_commands_panel( *, name: str, commands: list[click.Command], markup_mode: MarkupModeStrict, console: Console, cmd_len: int,) -> None: t_styles: dict[str, Any] = { "show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES, "leading": STYLE_COMMANDS_TABLE_LEADING, "box": STYLE_COMMANDS_TABLE_BOX, "border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE, "row_styles": STYLE_COMMANDS_TABLE_ROW_STYLES, "pad_edge": STYLE_COMMANDS_TABLE_PAD_EDGE, "padding": STYLE_COMMANDS_TABLE_PADDING, } box_style = getattr(box, t_styles.pop("box"), None)
commands_table = Table( highlight=False, show_header=False, expand=True, box=box_style, **t_styles, ) # Define formatting in first column, as commands don't match highlighter # regex commands_table.add_column( style=STYLE_COMMANDS_TABLE_FIRST_COLUMN, no_wrap=True, width=cmd_len, )
# A big ratio makes the description column be greedy and take all the space # available instead of allowing the command column to grow and misalign with # other panels. commands_table.add_column("Description", justify="left", no_wrap=False, ratio=10) rows: list[list[RenderableType | None]] = [] deprecated_rows: list[RenderableType | None] = [] for command in commands: helptext = command.short_help or command.help or "" command_name = command.name or "" if command.deprecated: command_name_text = Text(f"{command_name}", style=STYLE_DEPRECATED_COMMAND) deprecated_rows.append(Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)) else: command_name_text = Text(command_name) deprecated_rows.append(None) rows.append( [ command_name_text, _make_command_help( help_text=helptext, markup_mode=markup_mode, ), ] ) rows_with_deprecated = rows if any(deprecated_rows): rows_with_deprecated = [] for row, deprecated_text in zip(rows, deprecated_rows, strict=True): rows_with_deprecated.append([*row, deprecated_text]) for row in rows_with_deprecated: commands_table.add_row(*row) if commands_table.row_count: console.print( Panel( commands_table, border_style=STYLE_COMMANDS_PANEL_BORDER, title=name, title_align=ALIGN_COMMANDS_PANEL, ) )
def rich_format_help( *, obj: click.Command | click.Group, ctx: click.Context, markup_mode: MarkupModeStrict,) -> None: """Print nicely formatted help text using rich.
Based on original code from rich-cli, by @willmcgugan. https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236
Replacement for the click function format_help(). Takes a command or group and builds the help text output. """ console = _get_rich_console()
# Print usage console.print( Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND )
# Print command / group help if we have some if obj.help: # Print with some padding console.print( Padding( Align( _get_help_text( obj=obj, markup_mode=markup_mode, ), pad=False, ), (0, 1, 1, 1), ) ) panel_to_arguments: defaultdict[str, list[click.Argument]] = defaultdict(list) panel_to_options: defaultdict[str, list[click.Option]] = defaultdict(list) for param in obj.get_params(ctx): # Skip if option is hidden if getattr(param, "hidden", False): continue if isinstance(param, click.Argument): panel_name = ( getattr(param, _RICH_HELP_PANEL_NAME, None) or ARGUMENTS_PANEL_TITLE ) panel_to_arguments[panel_name].append(param) elif isinstance(param, click.Option): panel_name = ( getattr(param, _RICH_HELP_PANEL_NAME, None) or OPTIONS_PANEL_TITLE ) panel_to_options[panel_name].append(param) default_arguments = panel_to_arguments.get(ARGUMENTS_PANEL_TITLE, []) _print_options_panel( name=ARGUMENTS_PANEL_TITLE, params=default_arguments, ctx=ctx, markup_mode=markup_mode, console=console, ) for panel_name, arguments in panel_to_arguments.items(): if panel_name == ARGUMENTS_PANEL_TITLE: # Already printed above continue _print_options_panel( name=panel_name, params=arguments, ctx=ctx, markup_mode=markup_mode, console=console, ) default_options = panel_to_options.get(OPTIONS_PANEL_TITLE, []) _print_options_panel( name=OPTIONS_PANEL_TITLE, params=default_options, ctx=ctx, markup_mode=markup_mode, console=console, ) for panel_name, options in panel_to_options.items(): if panel_name == OPTIONS_PANEL_TITLE: # Already printed above continue _print_options_panel( name=panel_name, params=options, ctx=ctx, markup_mode=markup_mode, console=console, )
if isinstance(obj, click.Group): panel_to_commands: defaultdict[str, list[click.Command]] = defaultdict(list) for command_name in obj.list_commands(ctx): command = obj.get_command(ctx, command_name) if command and not command.hidden: panel_name = ( getattr(command, _RICH_HELP_PANEL_NAME, None) or COMMANDS_PANEL_TITLE ) panel_to_commands[panel_name].append(command)
# Identify the longest command name in all panels max_cmd_len = max( [ len(command.name or "") for commands in panel_to_commands.values() for command in commands ], default=0, )
# Print each command group panel default_commands = panel_to_commands.get(COMMANDS_PANEL_TITLE, []) _print_commands_panel( name=COMMANDS_PANEL_TITLE, commands=default_commands, markup_mode=markup_mode, console=console, cmd_len=max_cmd_len, ) for panel_name, commands in panel_to_commands.items(): if panel_name == COMMANDS_PANEL_TITLE: # Already printed above continue _print_commands_panel( name=panel_name, commands=commands, markup_mode=markup_mode, console=console, cmd_len=max_cmd_len, )
# Epilogue if we have it if obj.epilog: # Remove single linebreaks, replace double with single lines = obj.epilog.split("\n\n") epilogue = "\n".join([x.replace("\n", " ").strip() for x in lines]) epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode) console.print(Padding(Align(epilogue_text, pad=False), 1))
def rich_format_error(self: click.ClickException) -> None: """Print richly formatted click errors.
Called by custom exception handler to print richly formatted click errors. Mimics original click.ClickException.echo() function but with rich formatting. """ # Don't do anything when it's a NoArgsIsHelpError (without importing it, cf. #1278) if self.__class__.__name__ == "NoArgsIsHelpError": return
console = _get_rich_console(stderr=True) ctx: click.Context | None = getattr(self, "ctx", None) if ctx is not None: console.print(ctx.get_usage())
if ctx is not None and ctx.command.get_help_option(ctx) is not None: console.print( RICH_HELP.format( command_path=ctx.command_path, help_option=ctx.help_option_names[0] ), style=STYLE_ERRORS_SUGGESTION, )
console.print( Panel( highlighter(self.format_message()), border_style=STYLE_ERRORS_PANEL_BORDER, title=ERRORS_PANEL_TITLE, title_align=ALIGN_ERRORS_PANEL, ) )
def rich_abort_error() -> None: """Print richly formatted abort error.""" console = _get_rich_console(stderr=True) console.print(ABORTED_TEXT, style=STYLE_ABORTED)
def escape_before_html_export(input_text: str) -> str: """Ensure that the input string can be used for HTML export.""" return escape(input_text).strip()
def rich_to_html(input_text: str) -> str: """Print the HTML version of a rich-formatted input string.
This function does not provide a full HTML page, but can be used to insert HTML-formatted text spans into a markdown file. """ console = Console(record=True, highlight=False, file=io.StringIO())
console.print(input_text, overflow="ignore", crop=False)
return console.export_html(inline_styles=True, code_format="{code}").strip()
def rich_render_text(text: str) -> str: """Remove rich tags and render a pure text representation""" console = _get_rich_console() return "".join(segment.text for segment in console.render(text)).rstrip("\n")
def get_traceback( exc: BaseException, exception_config: DeveloperExceptionConfig, internal_dir_names: list[str],) -> Traceback: rich_tb = Traceback.from_exception( type(exc), exc, exc.__traceback__, show_locals=exception_config.pretty_exceptions_show_locals, suppress=internal_dir_names, width=MAX_WIDTH, ) return rich_tb123456789101112131415161718192021222324252627282930from collections.abc import Mapping, Sequencefrom typing import IO, Any
from click.testing import CliRunner as ClickCliRunner # noqafrom click.testing import Resultfrom typer.main import Typerfrom typer.main import get_command as _get_command
class CliRunner(ClickCliRunner): def invoke( # type: ignore self, app: Typer, args: str | Sequence[str] | None = None, input: bytes | str | IO[Any] | None = None, env: Mapping[str, str | None] | None = None, catch_exceptions: bool = True, color: bool = False, **extra: Any, ) -> Result: use_cli = _get_command(app) return super().invoke( use_cli, args=args, input=input, env=env, catch_exceptions=catch_exceptions, color=color, **extra, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import inspectfrom collections.abc import Callablefrom copy import copyfrom typing import Any, cast
from ._typing import Annotated, get_args, get_origin, get_type_hintsfrom .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta
def _param_type_to_user_string(param_type: type[ParameterInfo]) -> str: # Render a `ParameterInfo` subclass for use in error messages. # User code doesn't call `*Info` directly, so errors should present the classes how # they were (probably) defined in the user code. if param_type is OptionInfo: return "`Option`" elif param_type is ArgumentInfo: return "`Argument`" # This line shouldn't be reachable during normal use. return f"`{param_type.__name__}`" # pragma: no cover
class AnnotatedParamWithDefaultValueError(Exception): argument_name: str param_type: type[ParameterInfo]
def __init__(self, argument_name: str, param_type: type[ParameterInfo]): self.argument_name = argument_name self.param_type = param_type
def __str__(self) -> str: param_type_str = _param_type_to_user_string(self.param_type) return ( f"{param_type_str} default value cannot be set in `Annotated`" f" for {self.argument_name!r}. Set the default value with `=` instead." )
class MixedAnnotatedAndDefaultStyleError(Exception): argument_name: str annotated_param_type: type[ParameterInfo] default_param_type: type[ParameterInfo]
def __init__( self, argument_name: str, annotated_param_type: type[ParameterInfo], default_param_type: type[ParameterInfo], ): self.argument_name = argument_name self.annotated_param_type = annotated_param_type self.default_param_type = default_param_type
def __str__(self) -> str: annotated_param_type_str = _param_type_to_user_string(self.annotated_param_type) default_param_type_str = _param_type_to_user_string(self.default_param_type) msg = f"Cannot specify {annotated_param_type_str} in `Annotated` and" if self.annotated_param_type is self.default_param_type: msg += " default value" else: msg += f" {default_param_type_str} as a default value" msg += f" together for {self.argument_name!r}" return msg
class MultipleTyperAnnotationsError(Exception): argument_name: str
def __init__(self, argument_name: str): self.argument_name = argument_name
def __str__(self) -> str: return ( "Cannot specify multiple `Annotated` Typer arguments" f" for {self.argument_name!r}" )
class DefaultFactoryAndDefaultValueError(Exception): argument_name: str param_type: type[ParameterInfo]
def __init__(self, argument_name: str, param_type: type[ParameterInfo]): self.argument_name = argument_name self.param_type = param_type
def __str__(self) -> str: param_type_str = _param_type_to_user_string(self.param_type) return ( "Cannot specify `default_factory` and a default value together" f" for {param_type_str}" )
def _split_annotation_from_typer_annotations( base_annotation: type[Any],) -> tuple[type[Any], list[ParameterInfo]]: if get_origin(base_annotation) is not Annotated: return base_annotation, [] base_annotation, *maybe_typer_annotations = get_args(base_annotation) return base_annotation, [ annotation for annotation in maybe_typer_annotations if isinstance(annotation, ParameterInfo) ]
def get_params_from_function(func: Callable[..., Any]) -> dict[str, ParamMeta]: signature = inspect.signature(func, eval_str=True) type_hints = get_type_hints(func) params = {} for param in signature.parameters.values(): annotation, typer_annotations = _split_annotation_from_typer_annotations( param.annotation, ) if len(typer_annotations) > 1: raise MultipleTyperAnnotationsError(param.name)
default = param.default if typer_annotations: # It's something like `my_param: Annotated[str, Argument()]` [parameter_info] = typer_annotations
# Forbid `my_param: Annotated[str, Argument()] = Argument("...")` if isinstance(param.default, ParameterInfo): raise MixedAnnotatedAndDefaultStyleError( argument_name=param.name, annotated_param_type=type(parameter_info), default_param_type=type(param.default), )
parameter_info = copy(parameter_info)
# When used as a default, `Option` takes a default value and option names # as positional arguments: # `Option(some_value, "--some-argument", "-s")` # When used in `Annotated` (ie, what this is handling), `Option` just takes # option names as positional arguments: # `Option("--some-argument", "-s")` # In this case, the `default` attribute of `parameter_info` is actually # meant to be the first item of `param_decls`. if ( isinstance(parameter_info, OptionInfo) and parameter_info.default is not ... ): parameter_info.param_decls = ( cast(str, parameter_info.default), *(parameter_info.param_decls or ()), ) parameter_info.default = ...
# Forbid `my_param: Annotated[str, Argument('some-default')]` if parameter_info.default is not ...: raise AnnotatedParamWithDefaultValueError( param_type=type(parameter_info), argument_name=param.name, ) if param.default is not param.empty: # Put the parameter's default (set by `=`) into `parameter_info`, where # typer can find it. parameter_info.default = param.default
default = parameter_info elif param.name in type_hints: # Resolve forward references. annotation = type_hints[param.name]
if isinstance(default, ParameterInfo): parameter_info = copy(default) # Click supports `default` as either # - an actual value; or # - a factory function (returning a default value.) # The two are not interchangeable for static typing, so typer allows # specifying `default_factory`. Move the `default_factory` into `default` # so click can find it. if parameter_info.default is ... and parameter_info.default_factory: parameter_info.default = parameter_info.default_factory elif parameter_info.default_factory: raise DefaultFactoryAndDefaultValueError( argument_name=param.name, param_type=type(parameter_info) ) default = parameter_info
params[param.name] = ParamMeta( name=param.name, default=default, annotation=annotation ) return params
def parse_boolean_env_var(env_var_value: str | None, default: bool) -> bool: if env_var_value is None: return default value = env_var_value.lower() if value in ("y", "yes", "t", "true", "on", "1"): return True if value in ("n", "no", "f", "false", "off", "0"): return False return default123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384Metadata-Version: 2.4Name: clickVersion: 8.3.2Summary: Composable command line interface toolkitMaintainer-email: Pallets <contact@palletsprojects.com>Requires-Python: >=3.10Description-Content-Type: text/markdownLicense-Expression: BSD-3-ClauseClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Typing :: TypedLicense-File: LICENSE.txtRequires-Dist: colorama; platform_system == 'Windows'Project-URL: Changes, https://click.palletsprojects.com/page/changes/Project-URL: Chat, https://discord.gg/palletsProject-URL: Documentation, https://click.palletsprojects.com/Project-URL: Donate, https://palletsprojects.com/donateProject-URL: Source, https://github.com/pallets/click/
<div align="center"><img src="https://raw.githubusercontent.com/pallets/click/refs/heads/stable/docs/_static/click-name.svg" alt="" height="150"></div>
# Click
Click is a Python package for creating beautiful command line interfacesin a composable way with as little code as necessary. It's the "CommandLine Interface Creation Kit". It's highly configurable but comes withsensible defaults out of the box.
It aims to make the process of writing command line tools quick and funwhile also preventing any frustration caused by the inability toimplement an intended CLI API.
Click in three points:
- Arbitrary nesting of commands- Automatic help page generation- Supports lazy loading of subcommands at runtime
## A Simple Example
```pythonimport click
@click.command()@click.option("--count", default=1, help="Number of greetings.")@click.option("--name", prompt="Your name", help="The person to greet.")def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for _ in range(count): click.echo(f"Hello, {name}!")
if __name__ == '__main__': hello()```
```$ python hello.py --count=3Your name: ClickHello, Click!Hello, Click!Hello, Click!```
## Donate
The Pallets organization develops and supports Click and other popularpackages. In order to grow the community of contributors and users, andallow the maintainers to devote more time to the projects, [pleasedonate today][].
[please donate today]: https://palletsprojects.com/donate
## Contributing
See our [detailed contributing documentation][contrib] for many ways tocontribute, including reporting issues, requesting features, asking or answeringquestions, and making PRs.
[contrib]: https://palletsprojects.com/contributing/
12345678910111213141516171819202122click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693click/_termui_impl.py,sha256=rgCb3On8X5A4200rA5L6i13u5iapmFer7sru57Jy6zA,27093click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400click/_utils.py,sha256=kZwtTf5gMuCilJJceS2iTCvRvCY-0aN5rJq8gKw7p8g,943click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465click/core.py,sha256=7db9qr_wqXbQriDHCDc26OK0MsaLCSt4yrz14Kn7AEQ,132905click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461click/exceptions.py,sha256=8utf8w6V5hJXMnO_ic1FNrtbwuEn1NUu1aDwV8UqnG4,9954click/formatting.py,sha256=RVfwwr0rwWNpgGr8NaHodPzkIr7_tUyVh_nDdanLMNc,9730click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923click/parser.py,sha256=Q31pH0FlQZEq-UXE_ABRzlygEfvxPTuZbWNh4xfXmzw,19010click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0click/shell_completion.py,sha256=Cc4GQUFuWpfQBa9sF5qXeeYI7n3tI_1k6ZdSn4BZbT0,20994click/termui.py,sha256=hqCEjNndU-nzW08nRAkBaVgfZp_FdCA9KxfIWlKYaMc,31037click/testing.py,sha256=LjNfHqNctxc3GfRkLgifO6gnRetblh8yGXzjw4FPFCQ,18978click/types.py,sha256=ek54BNSFwPKsqtfT7jsqcc4WHui8AIFVMKM4oVZIXhc,39927click/utils.py,sha256=gCUoewdAhA-QLBUUHxrLh4uj6m7T1WjZZMNPvR0I7YA,20257click-8.3.2.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475click-8.3.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82click-8.3.2.dist-info/METADATA,sha256=yA3Hu5bMxtntTd4QrI8hTFAc58rHSPhDbP6bklbUQkA,2621click-8.3.2.dist-info/RECORD,,1234Wheel-Version: 1.0Generator: flit 3.12.0Root-Is-Purelib: trueTag: py3-none-any12345678910111213141516171819202122232425262728Copyright 2014 Pallets
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITEDTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Click is a simple Python module inspired by the stdlib optparse to makewriting command line scripts fun. Unlike other modules, it's basedaround a simple API that does not come with too much magic and iscomposable."""
from __future__ import annotations
from .core import Argument as Argumentfrom .core import Command as Commandfrom .core import CommandCollection as CommandCollectionfrom .core import Context as Contextfrom .core import Group as Groupfrom .core import Option as Optionfrom .core import Parameter as Parameterfrom .decorators import argument as argumentfrom .decorators import command as commandfrom .decorators import confirmation_option as confirmation_optionfrom .decorators import group as groupfrom .decorators import help_option as help_optionfrom .decorators import make_pass_decorator as make_pass_decoratorfrom .decorators import option as optionfrom .decorators import pass_context as pass_contextfrom .decorators import pass_obj as pass_objfrom .decorators import password_option as password_optionfrom .decorators import version_option as version_optionfrom .exceptions import Abort as Abortfrom .exceptions import BadArgumentUsage as BadArgumentUsagefrom .exceptions import BadOptionUsage as BadOptionUsagefrom .exceptions import BadParameter as BadParameterfrom .exceptions import ClickException as ClickExceptionfrom .exceptions import FileError as FileErrorfrom .exceptions import MissingParameter as MissingParameterfrom .exceptions import NoSuchOption as NoSuchOptionfrom .exceptions import UsageError as UsageErrorfrom .formatting import HelpFormatter as HelpFormatterfrom .formatting import wrap_text as wrap_textfrom .globals import get_current_context as get_current_contextfrom .termui import clear as clearfrom .termui import confirm as confirmfrom .termui import echo_via_pager as echo_via_pagerfrom .termui import edit as editfrom .termui import getchar as getcharfrom .termui import launch as launchfrom .termui import pause as pausefrom .termui import progressbar as progressbarfrom .termui import prompt as promptfrom .termui import secho as sechofrom .termui import style as stylefrom .termui import unstyle as unstylefrom .types import BOOL as BOOLfrom .types import Choice as Choicefrom .types import DateTime as DateTimefrom .types import File as Filefrom .types import FLOAT as FLOATfrom .types import FloatRange as FloatRangefrom .types import INT as INTfrom .types import IntRange as IntRangefrom .types import ParamType as ParamTypefrom .types import Path as Pathfrom .types import STRING as STRINGfrom .types import Tuple as Tuplefrom .types import UNPROCESSED as UNPROCESSEDfrom .types import UUID as UUIDfrom .utils import echo as echofrom .utils import format_filename as format_filenamefrom .utils import get_app_dir as get_app_dirfrom .utils import get_binary_stream as get_binary_streamfrom .utils import get_text_stream as get_text_streamfrom .utils import open_file as open_file
def __getattr__(name: str) -> object: import warnings
if name == "BaseCommand": from .core import _BaseCommand
warnings.warn( "'BaseCommand' is deprecated and will be removed in Click 9.0. Use" " 'Command' instead.", DeprecationWarning, stacklevel=2, ) return _BaseCommand
if name == "MultiCommand": from .core import _MultiCommand
warnings.warn( "'MultiCommand' is deprecated and will be removed in Click 9.0. Use" " 'Group' instead.", DeprecationWarning, stacklevel=2, ) return _MultiCommand
if name == "OptionParser": from .parser import _OptionParser
warnings.warn( "'OptionParser' is deprecated and will be removed in Click 9.0. The" " old parser is available in 'optparse'.", DeprecationWarning, stacklevel=2, ) return _OptionParser
if name == "__version__": import importlib.metadata import warnings
warnings.warn( "The '__version__' attribute is deprecated and will be removed in" " Click 9.1. Use feature detection or" " 'importlib.metadata.version(\"click\")' instead.", DeprecationWarning, stacklevel=2, ) return importlib.metadata.version("click")
raise AttributeError(name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622from __future__ import annotations
import codecsimport collections.abc as cabcimport ioimport osimport reimport sysimport typing as tfrom types import TracebackTypefrom weakref import WeakKeyDictionary
CYGWIN = sys.platform.startswith("cygwin")WIN = sys.platform.startswith("win")auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
def _make_text_stream( stream: t.BinaryIO, encoding: str | None, errors: str | None, force_readable: bool = False, force_writable: bool = False,) -> t.TextIO: if encoding is None: encoding = get_best_encoding(stream) if errors is None: errors = "replace" return _NonClosingTextIOWrapper( stream, encoding, errors, line_buffering=True, force_readable=force_readable, force_writable=force_writable, )
def is_ascii_encoding(encoding: str) -> bool: """Checks if a given encoding is ascii.""" try: return codecs.lookup(encoding).name == "ascii" except LookupError: return False
def get_best_encoding(stream: t.IO[t.Any]) -> str: """Returns the default stream encoding if not found.""" rv = getattr(stream, "encoding", None) or sys.getdefaultencoding() if is_ascii_encoding(rv): return "utf-8" return rv
class _NonClosingTextIOWrapper(io.TextIOWrapper): def __init__( self, stream: t.BinaryIO, encoding: str | None, errors: str | None, force_readable: bool = False, force_writable: bool = False, **extra: t.Any, ) -> None: self._stream = stream = t.cast( t.BinaryIO, _FixupStream(stream, force_readable, force_writable) ) super().__init__(stream, encoding, errors, **extra)
def __del__(self) -> None: try: self.detach() except Exception: pass
def isatty(self) -> bool: # https://bitbucket.org/pypy/pypy/issue/1803 return self._stream.isatty()
class _FixupStream: """The new io interface needs more from streams than streams traditionally implement. As such, this fix-up code is necessary in some circumstances.
The forcing of readable and writable flags are there because some tools put badly patched objects on sys (one such offender are certain version of jupyter notebook). """
def __init__( self, stream: t.BinaryIO, force_readable: bool = False, force_writable: bool = False, ): self._stream = stream self._force_readable = force_readable self._force_writable = force_writable
def __getattr__(self, name: str) -> t.Any: return getattr(self._stream, name)
def read1(self, size: int) -> bytes: f = getattr(self._stream, "read1", None)
if f is not None: return t.cast(bytes, f(size))
return self._stream.read(size)
def readable(self) -> bool: if self._force_readable: return True x = getattr(self._stream, "readable", None) if x is not None: return t.cast(bool, x()) try: self._stream.read(0) except Exception: return False return True
def writable(self) -> bool: if self._force_writable: return True x = getattr(self._stream, "writable", None) if x is not None: return t.cast(bool, x()) try: self._stream.write(b"") except Exception: try: self._stream.write(b"") except Exception: return False return True
def seekable(self) -> bool: x = getattr(self._stream, "seekable", None) if x is not None: return t.cast(bool, x()) try: self._stream.seek(self._stream.tell()) except Exception: return False return True
def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool: try: return isinstance(stream.read(0), bytes) except Exception: return default # This happens in some cases where the stream was already # closed. In this case, we assume the default.
def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool: try: stream.write(b"") except Exception: try: stream.write("") return False except Exception: pass return default return True
def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None: # We need to figure out if the given stream is already binary. # This can happen because the official docs recommend detaching # the streams to get binary streams. Some code might do this, so # we need to deal with this case explicitly. if _is_binary_reader(stream, False): return t.cast(t.BinaryIO, stream)
buf = getattr(stream, "buffer", None)
# Same situation here; this time we assume that the buffer is # actually binary in case it's closed. if buf is not None and _is_binary_reader(buf, True): return t.cast(t.BinaryIO, buf)
return None
def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None: # We need to figure out if the given stream is already binary. # This can happen because the official docs recommend detaching # the streams to get binary streams. Some code might do this, so # we need to deal with this case explicitly. if _is_binary_writer(stream, False): return t.cast(t.BinaryIO, stream)
buf = getattr(stream, "buffer", None)
# Same situation here; this time we assume that the buffer is # actually binary in case it's closed. if buf is not None and _is_binary_writer(buf, True): return t.cast(t.BinaryIO, buf)
return None
def _stream_is_misconfigured(stream: t.TextIO) -> bool: """A stream is misconfigured if its encoding is ASCII.""" # If the stream does not have an encoding set, we assume it's set # to ASCII. This appears to happen in certain unittest # environments. It's not quite clear what the correct behavior is # but this at least will force Click to recover somehow. return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool: """A stream attribute is compatible if it is equal to the desired value or the desired value is unset and the attribute has a value. """ stream_value = getattr(stream, attr, None) return stream_value == value or (value is None and stream_value is not None)
def _is_compatible_text_stream( stream: t.TextIO, encoding: str | None, errors: str | None) -> bool: """Check if a stream's encoding and errors attributes are compatible with the desired values. """ return _is_compat_stream_attr( stream, "encoding", encoding ) and _is_compat_stream_attr(stream, "errors", errors)
def _force_correct_text_stream( text_stream: t.IO[t.Any], encoding: str | None, errors: str | None, is_binary: t.Callable[[t.IO[t.Any], bool], bool], find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None], force_readable: bool = False, force_writable: bool = False,) -> t.TextIO: if is_binary(text_stream, False): binary_reader = t.cast(t.BinaryIO, text_stream) else: text_stream = t.cast(t.TextIO, text_stream) # If the stream looks compatible, and won't default to a # misconfigured ascii encoding, return it as-is. if _is_compatible_text_stream(text_stream, encoding, errors) and not ( encoding is None and _stream_is_misconfigured(text_stream) ): return text_stream
# Otherwise, get the underlying binary reader. possible_binary_reader = find_binary(text_stream)
# If that's not possible, silently use the original reader # and get mojibake instead of exceptions. if possible_binary_reader is None: return text_stream
binary_reader = possible_binary_reader
# Default errors to replace instead of strict in order to get # something that works. if errors is None: errors = "replace"
# Wrap the binary stream in a text stream with the correct # encoding parameters. return _make_text_stream( binary_reader, encoding, errors, force_readable=force_readable, force_writable=force_writable, )
def _force_correct_text_reader( text_reader: t.IO[t.Any], encoding: str | None, errors: str | None, force_readable: bool = False,) -> t.TextIO: return _force_correct_text_stream( text_reader, encoding, errors, _is_binary_reader, _find_binary_reader, force_readable=force_readable, )
def _force_correct_text_writer( text_writer: t.IO[t.Any], encoding: str | None, errors: str | None, force_writable: bool = False,) -> t.TextIO: return _force_correct_text_stream( text_writer, encoding, errors, _is_binary_writer, _find_binary_writer, force_writable=force_writable, )
def get_binary_stdin() -> t.BinaryIO: reader = _find_binary_reader(sys.stdin) if reader is None: raise RuntimeError("Was not able to determine binary stream for sys.stdin.") return reader
def get_binary_stdout() -> t.BinaryIO: writer = _find_binary_writer(sys.stdout) if writer is None: raise RuntimeError("Was not able to determine binary stream for sys.stdout.") return writer
def get_binary_stderr() -> t.BinaryIO: writer = _find_binary_writer(sys.stderr) if writer is None: raise RuntimeError("Was not able to determine binary stream for sys.stderr.") return writer
def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO: rv = _get_windows_console_stream(sys.stdin, encoding, errors) if rv is not None: return rv return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)
def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO: rv = _get_windows_console_stream(sys.stdout, encoding, errors) if rv is not None: return rv return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)
def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO: rv = _get_windows_console_stream(sys.stderr, encoding, errors) if rv is not None: return rv return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)
def _wrap_io_open( file: str | os.PathLike[str] | int, mode: str, encoding: str | None, errors: str | None,) -> t.IO[t.Any]: """Handles not passing ``encoding`` and ``errors`` in binary mode.""" if "b" in mode: return open(file, mode)
return open(file, mode, encoding=encoding, errors=errors)
def open_stream( filename: str | os.PathLike[str], mode: str = "r", encoding: str | None = None, errors: str | None = "strict", atomic: bool = False,) -> tuple[t.IO[t.Any], bool]: binary = "b" in mode filename = os.fspath(filename)
# Standard streams first. These are simple because they ignore the # atomic flag. Use fsdecode to handle Path("-"). if os.fsdecode(filename) == "-": if any(m in mode for m in ["w", "a", "x"]): if binary: return get_binary_stdout(), False return get_text_stdout(encoding=encoding, errors=errors), False if binary: return get_binary_stdin(), False return get_text_stdin(encoding=encoding, errors=errors), False
# Non-atomic writes directly go out through the regular open functions. if not atomic: return _wrap_io_open(filename, mode, encoding, errors), True
# Some usability stuff for atomic writes if "a" in mode: raise ValueError( "Appending to an existing file is not supported, because that" " would involve an expensive `copy`-operation to a temporary" " file. Open the file in normal `w`-mode and copy explicitly" " if that's what you're after." ) if "x" in mode: raise ValueError("Use the `overwrite`-parameter instead.") if "w" not in mode: raise ValueError("Atomic writes only make sense with `w`-mode.")
# Atomic writes are more complicated. They work by opening a file # as a proxy in the same folder and then using the fdopen # functionality to wrap it in a Python file. Then we wrap it in an # atomic file that moves the file over on close. import errno import random
try: perm: int | None = os.stat(filename).st_mode except OSError: perm = None
flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
if binary: flags |= getattr(os, "O_BINARY", 0)
while True: tmp_filename = os.path.join( os.path.dirname(filename), f".__atomic-write{random.randrange(1 << 32):08x}", ) try: fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm) break except OSError as e: if e.errno == errno.EEXIST or ( os.name == "nt" and e.errno == errno.EACCES and os.path.isdir(e.filename) and os.access(e.filename, os.W_OK) ): continue raise
if perm is not None: os.chmod(tmp_filename, perm) # in case perm includes bits in umask
f = _wrap_io_open(fd, mode, encoding, errors) af = _AtomicFile(f, tmp_filename, os.path.realpath(filename)) return t.cast(t.IO[t.Any], af), True
class _AtomicFile: def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: self._f = f self._tmp_filename = tmp_filename self._real_filename = real_filename self.closed = False
@property def name(self) -> str: return self._real_filename
def close(self, delete: bool = False) -> None: if self.closed: return self._f.close() os.replace(self._tmp_filename, self._real_filename) self.closed = True
def __getattr__(self, name: str) -> t.Any: return getattr(self._f, name)
def __enter__(self) -> _AtomicFile: return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.close(delete=exc_type is not None)
def __repr__(self) -> str: return repr(self._f)
def strip_ansi(value: str) -> str: return _ansi_re.sub("", value)
def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool: while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)): stream = stream._stream
return stream.__class__.__module__.startswith("ipykernel.")
def should_strip_ansi( stream: t.IO[t.Any] | None = None, color: bool | None = None) -> bool: if color is None: if stream is None: stream = sys.stdin return not isatty(stream) and not _is_jupyter_kernel_output(stream) return not color
# On Windows, wrap the output streams with colorama to support ANSI# color codes.# NOTE: double check is needed so mypy does not analyze this on Linuxif sys.platform.startswith("win") and WIN: from ._winconsole import _get_windows_console_stream
def _get_argv_encoding() -> str: import locale
return locale.getpreferredencoding()
_ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO: """Support ANSI color and style codes on Windows by wrapping a stream with colorama. """ try: cached = _ansi_stream_wrappers.get(stream) except Exception: cached = None
if cached is not None: return cached
import colorama
strip = should_strip_ansi(stream, color) ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) rv = t.cast(t.TextIO, ansi_wrapper.stream) _write = rv.write
def _safe_write(s: str) -> int: try: return _write(s) except BaseException: ansi_wrapper.reset_all() raise
rv.write = _safe_write # type: ignore[method-assign]
try: _ansi_stream_wrappers[stream] = rv except Exception: pass
return rv
else:
def _get_argv_encoding() -> str: return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()
def _get_windows_console_stream( f: t.TextIO, encoding: str | None, errors: str | None ) -> t.TextIO | None: return None
def term_len(x: str) -> int: return len(strip_ansi(x))
def isatty(stream: t.IO[t.Any]) -> bool: try: return stream.isatty() except Exception: return False
def _make_cached_stream_func( src_func: t.Callable[[], t.TextIO | None], wrapper_func: t.Callable[[], t.TextIO],) -> t.Callable[[], t.TextIO | None]: cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
def func() -> t.TextIO | None: stream = src_func()
if stream is None: return None
try: rv = cache.get(stream) except Exception: rv = None if rv is not None: return rv rv = wrapper_func() try: cache[stream] = rv except Exception: pass return rv
return func
_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = { "stdin": get_binary_stdin, "stdout": get_binary_stdout, "stderr": get_binary_stderr,}
text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = { "stdin": get_text_stdin, "stdout": get_text_stdout, "stderr": get_text_stderr,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852"""This module contains implementations for the termui module. To keep theimport time of Click down, some infrequently used functionality isplaced in this module and only imported as needed."""
from __future__ import annotations
import collections.abc as cabcimport contextlibimport mathimport osimport shleximport sysimport timeimport typing as tfrom gettext import gettext as _from io import StringIOfrom pathlib import Pathfrom types import TracebackType
from ._compat import _default_text_stdoutfrom ._compat import CYGWINfrom ._compat import get_best_encodingfrom ._compat import isattyfrom ._compat import open_streamfrom ._compat import strip_ansifrom ._compat import term_lenfrom ._compat import WINfrom .exceptions import ClickExceptionfrom .utils import echo
V = t.TypeVar("V")
if os.name == "nt": BEFORE_BAR = "\r" AFTER_BAR = "\n"else: BEFORE_BAR = "\r\033[?25l" AFTER_BAR = "\033[?25h\n"
class ProgressBar(t.Generic[V]): def __init__( self, iterable: cabc.Iterable[V] | None, length: int | None = None, fill_char: str = "#", empty_char: str = " ", bar_template: str = "%(bar)s", info_sep: str = " ", hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, label: str | None = None, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1, width: int = 30, ) -> None: self.fill_char = fill_char self.empty_char = empty_char self.bar_template = bar_template self.info_sep = info_sep self.hidden = hidden self.show_eta = show_eta self.show_percent = show_percent self.show_pos = show_pos self.item_show_func = item_show_func self.label: str = label or ""
if file is None: file = _default_text_stdout()
# There are no standard streams attached to write to. For example, # pythonw on Windows. if file is None: file = StringIO()
self.file = file self.color = color self.update_min_steps = update_min_steps self._completed_intervals = 0 self.width: int = width self.autowidth: bool = width == 0
if length is None: from operator import length_hint
length = length_hint(iterable, -1)
if length == -1: length = None if iterable is None: if length is None: raise TypeError("iterable or length is required") iterable = t.cast("cabc.Iterable[V]", range(length)) self.iter: cabc.Iterable[V] = iter(iterable) self.length = length self.pos: int = 0 self.avg: list[float] = [] self.last_eta: float self.start: float self.start = self.last_eta = time.time() self.eta_known: bool = False self.finished: bool = False self.max_width: int | None = None self.entered: bool = False self.current_item: V | None = None self._is_atty = isatty(self.file) self._last_line: str | None = None
def __enter__(self) -> ProgressBar[V]: self.entered = True self.render_progress() return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.render_finish()
def __iter__(self) -> cabc.Iterator[V]: if not self.entered: raise RuntimeError("You need to use progress bars in a with block.") self.render_progress() return self.generator()
def __next__(self) -> V: # Iteration is defined in terms of a generator function, # returned by iter(self); use that to define next(). This works # because `self.iter` is an iterable consumed by that generator, # so it is re-entry safe. Calling `next(self.generator())` # twice works and does "what you want". return next(iter(self))
def render_finish(self) -> None: if self.hidden or not self._is_atty: return self.file.write(AFTER_BAR) self.file.flush()
@property def pct(self) -> float: if self.finished: return 1.0 return min(self.pos / (float(self.length or 1) or 1), 1.0)
@property def time_per_iteration(self) -> float: if not self.avg: return 0.0 return sum(self.avg) / float(len(self.avg))
@property def eta(self) -> float: if self.length is not None and not self.finished: return self.time_per_iteration * (self.length - self.pos) return 0.0
def format_eta(self) -> str: if self.eta_known: t = int(self.eta) seconds = t % 60 t //= 60 minutes = t % 60 t //= 60 hours = t % 24 t //= 24 if t > 0: return f"{t}d {hours:02}:{minutes:02}:{seconds:02}" else: return f"{hours:02}:{minutes:02}:{seconds:02}" return ""
def format_pos(self) -> str: pos = str(self.pos) if self.length is not None: pos += f"/{self.length}" return pos
def format_pct(self) -> str: return f"{int(self.pct * 100): 4}%"[1:]
def format_bar(self) -> str: if self.length is not None: bar_length = int(self.pct * self.width) bar = self.fill_char * bar_length bar += self.empty_char * (self.width - bar_length) elif self.finished: bar = self.fill_char * self.width else: chars = list(self.empty_char * (self.width or 1)) if self.time_per_iteration != 0: chars[ int( (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5) * self.width ) ] = self.fill_char bar = "".join(chars) return bar
def format_progress_line(self) -> str: show_percent = self.show_percent
info_bits = [] if self.length is not None and show_percent is None: show_percent = not self.show_pos
if self.show_pos: info_bits.append(self.format_pos()) if show_percent: info_bits.append(self.format_pct()) if self.show_eta and self.eta_known and not self.finished: info_bits.append(self.format_eta()) if self.item_show_func is not None: item_info = self.item_show_func(self.current_item) if item_info is not None: info_bits.append(item_info)
return ( self.bar_template % { "label": self.label, "bar": self.format_bar(), "info": self.info_sep.join(info_bits), } ).rstrip()
def render_progress(self) -> None: if self.hidden: return
if not self._is_atty: # Only output the label once if the output is not a TTY. if self._last_line != self.label: self._last_line = self.label echo(self.label, file=self.file, color=self.color) return
buf = [] # Update width in case the terminal has been resized if self.autowidth: import shutil
old_width = self.width self.width = 0 clutter_length = term_len(self.format_progress_line()) new_width = max(0, shutil.get_terminal_size().columns - clutter_length) if new_width < old_width and self.max_width is not None: buf.append(BEFORE_BAR) buf.append(" " * self.max_width) self.max_width = new_width self.width = new_width
clear_width = self.width if self.max_width is not None: clear_width = self.max_width
buf.append(BEFORE_BAR) line = self.format_progress_line() line_len = term_len(line) if self.max_width is None or self.max_width < line_len: self.max_width = line_len
buf.append(line) buf.append(" " * (clear_width - line_len)) line = "".join(buf) # Render the line only if it changed.
if line != self._last_line: self._last_line = line echo(line, file=self.file, color=self.color, nl=False) self.file.flush()
def make_step(self, n_steps: int) -> None: self.pos += n_steps if self.length is not None and self.pos >= self.length: self.finished = True
if (time.time() - self.last_eta) < 1.0: return
self.last_eta = time.time()
# self.avg is a rolling list of length <= 7 of steps where steps are # defined as time elapsed divided by the total progress through # self.length. if self.pos: step = (time.time() - self.start) / self.pos else: step = time.time() - self.start
self.avg = self.avg[-6:] + [step]
self.eta_known = self.length is not None
def update(self, n_steps: int, current_item: V | None = None) -> None: """Update the progress bar by advancing a specified number of steps, and optionally set the ``current_item`` for this new position.
:param n_steps: Number of steps to advance. :param current_item: Optional item to set as ``current_item`` for the updated position.
.. versionchanged:: 8.0 Added the ``current_item`` optional parameter.
.. versionchanged:: 8.0 Only render when the number of steps meets the ``update_min_steps`` threshold. """ if current_item is not None: self.current_item = current_item
self._completed_intervals += n_steps
if self._completed_intervals >= self.update_min_steps: self.make_step(self._completed_intervals) self.render_progress() self._completed_intervals = 0
def finish(self) -> None: self.eta_known = False self.current_item = None self.finished = True
def generator(self) -> cabc.Iterator[V]: """Return a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns. """ # WARNING: the iterator interface for `ProgressBar` relies on # this and only works because this is a simple generator which # doesn't create or manage additional state. If this function # changes, the impact should be evaluated both against # `iter(bar)` and `next(bar)`. `next()` in particular may call # `self.generator()` repeatedly, and this must remain safe in # order for that interface to work. if not self.entered: raise RuntimeError("You need to use progress bars in a with block.")
if not self._is_atty: yield from self.iter else: for rv in self.iter: self.current_item = rv
# This allows show_item_func to be updated before the # item is processed. Only trigger at the beginning of # the update interval. if self._completed_intervals == 0: self.render_progress()
yield rv self.update(1)
self.finish() self.render_progress()
def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None: """Decide what method to use for paging through text.""" stdout = _default_text_stdout()
# There are no standard streams attached to write to. For example, # pythonw on Windows. if stdout is None: stdout = StringIO()
if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, generator, color)
# Split and normalize the pager command into parts. pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False) if pager_cmd_parts: if WIN: if _tempfilepager(generator, pager_cmd_parts, color): return elif _pipepager(generator, pager_cmd_parts, color): return
if os.environ.get("TERM") in ("dumb", "emacs"): return _nullpager(stdout, generator, color) if (WIN or sys.platform.startswith("os2")) and _tempfilepager( generator, ["more"], color ): return if _pipepager(generator, ["less"], color): return
import tempfile
fd, filename = tempfile.mkstemp() os.close(fd) try: if _pipepager(generator, ["more"], color): return return _nullpager(stdout, generator, color) finally: os.unlink(filename)
def _pipepager( generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None) -> bool: """Page through text by feeding it to another program. Invoking a pager through this might support colors.
Returns `True` if the command was found, `False` otherwise and thus another pager should be attempted. """ # Split the command into the invoked CLI and its parameters. if not cmd_parts: return False
import shutil
cmd = cmd_parts[0] cmd_params = cmd_parts[1:]
cmd_filepath = shutil.which(cmd) if not cmd_filepath: return False
# Produces a normalized absolute path string. # multi-call binaries such as busybox derive their identity from the symlink # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox) cmd_path = Path(cmd_filepath).absolute() cmd_name = cmd_path.name
import subprocess
# Make a local copy of the environment to not affect the global one. env = dict(os.environ)
# If we're piping to less and the user hasn't decided on colors, we enable # them by default we find the -R flag in the command line arguments. if color is None and cmd_name == "less": less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}" if not less_flags: env["LESS"] = "-R" color = True elif "r" in less_flags or "R" in less_flags: color = True
c = subprocess.Popen( [str(cmd_path)] + cmd_params, shell=False, stdin=subprocess.PIPE, env=env, errors="replace", text=True, ) assert c.stdin is not None try: for text in generator: if not color: text = strip_ansi(text)
c.stdin.write(text) except BrokenPipeError: # In case the pager exited unexpectedly, ignore the broken pipe error. pass except Exception as e: # In case there is an exception we want to close the pager immediately # and let the caller handle it. # Otherwise the pager will keep running, and the user may not notice # the error message, or worse yet it may leave the terminal in a broken state. c.terminate() raise e finally: # We must close stdin and wait for the pager to exit before we continue try: c.stdin.close() # Close implies flush, so it might throw a BrokenPipeError if the pager # process exited already. except BrokenPipeError: pass
# Less doesn't respect ^C, but catches it for its own UI purposes (aborting # search or other commands inside less). # # That means when the user hits ^C, the parent process (click) terminates, # but less is still alive, paging the output and messing up the terminal. # # If the user wants to make the pager exit on ^C, they should set # `LESS='-K'`. It's not our decision to make. while True: try: c.wait() except KeyboardInterrupt: pass else: break
return True
def _tempfilepager( generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None) -> bool: """Page through text by invoking a program on a temporary file.
Returns `True` if the command was found, `False` otherwise and thus another pager should be attempted. """ # Split the command into the invoked CLI and its parameters. if not cmd_parts: return False
import shutil
cmd = cmd_parts[0]
cmd_filepath = shutil.which(cmd) if not cmd_filepath: return False # Produces a normalized absolute path string. # multi-call binaries such as busybox derive their identity from the symlink # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox) cmd_path = Path(cmd_filepath).absolute()
import subprocess import tempfile
fd, filename = tempfile.mkstemp() # TODO: This never terminates if the passed generator never terminates. text = "".join(generator) if not color: text = strip_ansi(text) encoding = get_best_encoding(sys.stdout) with open_stream(filename, "wb")[0] as f: f.write(text.encode(encoding)) try: subprocess.call([str(cmd_path), filename]) except OSError: # Command not found pass finally: os.close(fd) os.unlink(filename)
return True
def _nullpager( stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None) -> None: """Simply print unformatted text. This is the ultimate fallback.""" for text in generator: if not color: text = strip_ansi(text) stream.write(text)
class Editor: def __init__( self, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", ) -> None: self.editor = editor self.env = env self.require_save = require_save self.extension = extension
def get_editor(self) -> str: if self.editor is not None: return self.editor for key in "VISUAL", "EDITOR": rv = os.environ.get(key) if rv: return rv if WIN: return "notepad"
from shutil import which
for editor in "sensible-editor", "vim", "nano": if which(editor) is not None: return editor return "vi"
def edit_files(self, filenames: cabc.Iterable[str]) -> None: import subprocess
editor = self.get_editor() environ: dict[str, str] | None = None
if self.env: environ = os.environ.copy() environ.update(self.env)
exc_filename = " ".join(f'"{filename}"' for filename in filenames)
try: c = subprocess.Popen( args=f"{editor} {exc_filename}", env=environ, shell=True ) exit_code = c.wait() if exit_code != 0: raise ClickException( _("{editor}: Editing failed").format(editor=editor) ) except OSError as e: raise ClickException( _("{editor}: Editing failed: {e}").format(editor=editor, e=e) ) from e
@t.overload def edit(self, text: bytes | bytearray) -> bytes | None: ...
# We cannot know whether or not the type expected is str or bytes when None # is passed, so str is returned as that was what was done before. @t.overload def edit(self, text: str | None) -> str | None: ...
def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None: import tempfile
if text is None: data: bytes | bytearray = b"" elif isinstance(text, (bytes, bytearray)): data = text else: if text and not text.endswith("\n"): text += "\n"
if WIN: data = text.replace("\n", "\r\n").encode("utf-8-sig") else: data = text.encode("utf-8")
fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension) f: t.BinaryIO
try: with os.fdopen(fd, "wb") as f: f.write(data)
# If the filesystem resolution is 1 second, like Mac OS # 10.12 Extended, or 2 seconds, like FAT32, and the editor # closes very fast, require_save can fail. Set the modified # time to be 2 seconds in the past to work around this. os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2)) # Depending on the resolution, the exact value might not be # recorded, so get the new recorded value. timestamp = os.path.getmtime(name)
self.edit_files((name,))
if self.require_save and os.path.getmtime(name) == timestamp: return None
with open(name, "rb") as f: rv = f.read()
if isinstance(text, (bytes, bytearray)): return rv
return rv.decode("utf-8-sig").replace("\r\n", "\n") finally: os.unlink(name)
def open_url(url: str, wait: bool = False, locate: bool = False) -> int: import subprocess
def _unquote_file(url: str) -> str: from urllib.parse import unquote
if url.startswith("file://"): url = unquote(url[7:])
return url
if sys.platform == "darwin": args = ["open"] if wait: args.append("-W") if locate: args.append("-R") args.append(_unquote_file(url)) null = open("/dev/null", "w") try: return subprocess.Popen(args, stderr=null).wait() finally: null.close() elif WIN: if locate: url = _unquote_file(url) args = ["explorer", f"/select,{url}"] else: args = ["start"] if wait: args.append("/WAIT") args.append("") args.append(url) try: return subprocess.call(args) except OSError: # Command not found return 127 elif CYGWIN: if locate: url = _unquote_file(url) args = ["cygstart", os.path.dirname(url)] else: args = ["cygstart"] if wait: args.append("-w") args.append(url) try: return subprocess.call(args) except OSError: # Command not found return 127
try: if locate: url = os.path.dirname(_unquote_file(url)) or "." else: url = _unquote_file(url) c = subprocess.Popen(["xdg-open", url]) if wait: return c.wait() return 0 except OSError: if url.startswith(("http://", "https://")) and not locate and not wait: import webbrowser
webbrowser.open(url) return 0 return 1
def _translate_ch_to_exc(ch: str) -> None: if ch == "\x03": raise KeyboardInterrupt()
if ch == "\x04" and not WIN: # Unix-like, Ctrl+D raise EOFError()
if ch == "\x1a" and WIN: # Windows, Ctrl+Z raise EOFError()
return None
if sys.platform == "win32": import msvcrt
@contextlib.contextmanager def raw_terminal() -> cabc.Iterator[int]: yield -1
def getchar(echo: bool) -> str: # The function `getch` will return a bytes object corresponding to # the pressed character. Since Windows 10 build 1803, it will also # return \x00 when called a second time after pressing a regular key. # # `getwch` does not share this probably-bugged behavior. Moreover, it # returns a Unicode object by default, which is what we want. # # Either of these functions will return \x00 or \xe0 to indicate # a special key, and you need to call the same function again to get # the "rest" of the code. The fun part is that \u00e0 is # "latin small letter a with grave", so if you type that on a French # keyboard, you _also_ get a \xe0. # E.g., consider the Up arrow. This returns \xe0 and then \x48. The # resulting Unicode string reads as "a with grave" + "capital H". # This is indistinguishable from when the user actually types # "a with grave" and then "capital H". # # When \xe0 is returned, we assume it's part of a special-key sequence # and call `getwch` again, but that means that when the user types # the \u00e0 character, `getchar` doesn't return until a second # character is typed. # The alternative is returning immediately, but that would mess up # cross-platform handling of arrow keys and others that start with # \xe0. Another option is using `getch`, but then we can't reliably # read non-ASCII characters, because return values of `getch` are # limited to the current 8-bit codepage. # # Anyway, Click doesn't claim to do this Right(tm), and using `getwch` # is doing the right thing in more situations than with `getch`.
if echo: func = t.cast(t.Callable[[], str], msvcrt.getwche) else: func = t.cast(t.Callable[[], str], msvcrt.getwch)
rv = func()
if rv in ("\x00", "\xe0"): # \x00 and \xe0 are control characters that indicate special key, # see above. rv += func()
_translate_ch_to_exc(rv) return rv
else: import termios import tty
@contextlib.contextmanager def raw_terminal() -> cabc.Iterator[int]: f: t.TextIO | None fd: int
if not isatty(sys.stdin): f = open("/dev/tty") fd = f.fileno() else: fd = sys.stdin.fileno() f = None
try: old_settings = termios.tcgetattr(fd)
try: tty.setraw(fd) yield fd finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) sys.stdout.flush()
if f is not None: f.close() except termios.error: pass
def getchar(echo: bool) -> str: with raw_terminal() as fd: ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
if echo and isatty(sys.stdout): sys.stdout.write(ch)
_translate_ch_to_exc(ch) return ch123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051from __future__ import annotations
import collections.abc as cabcimport textwrapfrom contextlib import contextmanager
class TextWrapper(textwrap.TextWrapper): def _handle_long_word( self, reversed_chunks: list[str], cur_line: list[str], cur_len: int, width: int, ) -> None: space_left = max(width - cur_len, 1)
if self.break_long_words: last = reversed_chunks[-1] cut = last[:space_left] res = last[space_left:] cur_line.append(cut) reversed_chunks[-1] = res elif not cur_line: cur_line.append(reversed_chunks.pop())
@contextmanager def extra_indent(self, indent: str) -> cabc.Iterator[None]: old_initial_indent = self.initial_indent old_subsequent_indent = self.subsequent_indent self.initial_indent += indent self.subsequent_indent += indent
try: yield finally: self.initial_indent = old_initial_indent self.subsequent_indent = old_subsequent_indent
def indent_only(self, text: str) -> str: rv = []
for idx, line in enumerate(text.splitlines()): indent = self.initial_indent
if idx > 0: indent = self.subsequent_indent
rv.append(f"{indent}{line}")
return "\n".join(rv)123456789101112131415161718192021222324252627282930313233343536from __future__ import annotations
import enumimport typing as t
class Sentinel(enum.Enum): """Enum used to define sentinel values.
.. seealso::
`PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_. """
UNSET = object() FLAG_NEEDS_VALUE = object()
def __repr__(self) -> str: return f"{self.__class__.__name__}.{self.name}"
UNSET = Sentinel.UNSET"""Sentinel used to indicate that a value is not set."""
FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE"""Sentinel used to indicate an option was passed as a flag without avalue but is not a flag option.
``Option.consume_value`` uses this to prompt or use the ``flag_value``."""
T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]"""Type hint for the :data:`UNSET` sentinel value."""
T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type]"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296# This module is based on the excellent work by Adam Bartoš who# provided a lot of what went into the implementation here in# the discussion to issue1602 in the Python bug tracker.## There are some general differences in regards to how this works# compared to the original patches as we do not need to patch# the entire interpreter but just work in our little world of# echo and prompt.from __future__ import annotations
import collections.abc as cabcimport ioimport sysimport timeimport typing as tfrom ctypes import Arrayfrom ctypes import byreffrom ctypes import c_charfrom ctypes import c_char_pfrom ctypes import c_intfrom ctypes import c_ssize_tfrom ctypes import c_ulongfrom ctypes import c_void_pfrom ctypes import POINTERfrom ctypes import py_objectfrom ctypes import Structurefrom ctypes.wintypes import DWORDfrom ctypes.wintypes import HANDLEfrom ctypes.wintypes import LPCWSTRfrom ctypes.wintypes import LPWSTR
from ._compat import _NonClosingTextIOWrapper
assert sys.platform == "win32"import msvcrt # noqa: E402from ctypes import windll # noqa: E402from ctypes import WINFUNCTYPE # noqa: E402
c_ssize_p = POINTER(c_ssize_t)
kernel32 = windll.kernel32GetStdHandle = kernel32.GetStdHandleReadConsoleW = kernel32.ReadConsoleWWriteConsoleW = kernel32.WriteConsoleWGetConsoleMode = kernel32.GetConsoleModeGetLastError = kernel32.GetLastErrorGetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))( ("CommandLineToArgvW", windll.shell32))LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))
STDIN_HANDLE = GetStdHandle(-10)STDOUT_HANDLE = GetStdHandle(-11)STDERR_HANDLE = GetStdHandle(-12)
PyBUF_SIMPLE = 0PyBUF_WRITABLE = 1
ERROR_SUCCESS = 0ERROR_NOT_ENOUGH_MEMORY = 8ERROR_OPERATION_ABORTED = 995
STDIN_FILENO = 0STDOUT_FILENO = 1STDERR_FILENO = 2
EOF = b"\x1a"MAX_BYTES_WRITTEN = 32767
if t.TYPE_CHECKING: try: # Using `typing_extensions.Buffer` instead of `collections.abc` # on Windows for some reason does not have `Sized` implemented. from collections.abc import Buffer # type: ignore except ImportError: from typing_extensions import Buffer
try: from ctypes import pythonapiexcept ImportError: # On PyPy we cannot get buffers so our ability to operate here is # severely limited. get_buffer = Noneelse:
class Py_buffer(Structure): _fields_ = [ # noqa: RUF012 ("buf", c_void_p), ("obj", py_object), ("len", c_ssize_t), ("itemsize", c_ssize_t), ("readonly", c_int), ("ndim", c_int), ("format", c_char_p), ("shape", c_ssize_p), ("strides", c_ssize_p), ("suboffsets", c_ssize_p), ("internal", c_void_p), ]
PyObject_GetBuffer = pythonapi.PyObject_GetBuffer PyBuffer_Release = pythonapi.PyBuffer_Release
def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]: buf = Py_buffer() flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE PyObject_GetBuffer(py_object(obj), byref(buf), flags)
try: buffer_type = c_char * buf.len out: Array[c_char] = buffer_type.from_address(buf.buf) return out finally: PyBuffer_Release(byref(buf))
class _WindowsConsoleRawIOBase(io.RawIOBase): def __init__(self, handle: int | None) -> None: self.handle = handle
def isatty(self) -> t.Literal[True]: super().isatty() return True
class _WindowsConsoleReader(_WindowsConsoleRawIOBase): def readable(self) -> t.Literal[True]: return True
def readinto(self, b: Buffer) -> int: bytes_to_be_read = len(b) if not bytes_to_be_read: return 0 elif bytes_to_be_read % 2: raise ValueError( "cannot read odd number of bytes from UTF-16-LE encoded console" )
buffer = get_buffer(b, writable=True) code_units_to_be_read = bytes_to_be_read // 2 code_units_read = c_ulong()
rv = ReadConsoleW( HANDLE(self.handle), buffer, code_units_to_be_read, byref(code_units_read), None, ) if GetLastError() == ERROR_OPERATION_ABORTED: # wait for KeyboardInterrupt time.sleep(0.1) if not rv: raise OSError(f"Windows error: {GetLastError()}")
if buffer[0] == EOF: return 0 return 2 * code_units_read.value
class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): def writable(self) -> t.Literal[True]: return True
@staticmethod def _get_error_message(errno: int) -> str: if errno == ERROR_SUCCESS: return "ERROR_SUCCESS" elif errno == ERROR_NOT_ENOUGH_MEMORY: return "ERROR_NOT_ENOUGH_MEMORY" return f"Windows error {errno}"
def write(self, b: Buffer) -> int: bytes_to_be_written = len(b) buf = get_buffer(b) code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2 code_units_written = c_ulong()
WriteConsoleW( HANDLE(self.handle), buf, code_units_to_be_written, byref(code_units_written), None, ) bytes_written = 2 * code_units_written.value
if bytes_written == 0 and bytes_to_be_written > 0: raise OSError(self._get_error_message(GetLastError())) return bytes_written
class ConsoleStream: def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None: self._text_stream = text_stream self.buffer = byte_stream
@property def name(self) -> str: return self.buffer.name
def write(self, x: t.AnyStr) -> int: if isinstance(x, str): return self._text_stream.write(x) try: self.flush() except Exception: pass return self.buffer.write(x)
def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None: for line in lines: self.write(line)
def __getattr__(self, name: str) -> t.Any: return getattr(self._text_stream, name)
def isatty(self) -> bool: return self.buffer.isatty()
def __repr__(self) -> str: return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO: text_stream = _NonClosingTextIOWrapper( io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)), "utf-16-le", "strict", line_buffering=True, ) return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO: text_stream = _NonClosingTextIOWrapper( io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)), "utf-16-le", "strict", line_buffering=True, ) return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO: text_stream = _NonClosingTextIOWrapper( io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)), "utf-16-le", "strict", line_buffering=True, ) return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = { 0: _get_text_stdin, 1: _get_text_stdout, 2: _get_text_stderr,}
def _is_console(f: t.TextIO) -> bool: if not hasattr(f, "fileno"): return False
try: fileno = f.fileno() except (OSError, io.UnsupportedOperation): return False
handle = msvcrt.get_osfhandle(fileno) return bool(GetConsoleMode(handle, byref(DWORD())))
def _get_windows_console_stream( f: t.TextIO, encoding: str | None, errors: str | None) -> t.TextIO | None: if ( get_buffer is None or encoding not in {"utf-16-le", None} or errors not in {"strict", None} or not _is_console(f) ): return None
func = _stream_factories.get(f.fileno()) if func is None: return None
b = getattr(f, "buffer", None)
if b is None: return None
return func(b)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551from __future__ import annotations
import inspectimport typing as tfrom functools import update_wrapperfrom gettext import gettext as _
from .core import Argumentfrom .core import Commandfrom .core import Contextfrom .core import Groupfrom .core import Optionfrom .core import Parameterfrom .globals import get_current_contextfrom .utils import echo
if t.TYPE_CHECKING: import typing_extensions as te
P = te.ParamSpec("P")
R = t.TypeVar("R")T = t.TypeVar("T")_AnyCallable = t.Callable[..., t.Any]FC = t.TypeVar("FC", bound="_AnyCallable | Command")
def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]: """Marks a callback as wanting to receive the current context object as first argument. """
def new_func(*args: P.args, **kwargs: P.kwargs) -> R: return f(get_current_context(), *args, **kwargs)
return update_wrapper(new_func, f)
def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. """
def new_func(*args: P.args, **kwargs: P.kwargs) -> R: return f(get_current_context().obj, *args, **kwargs)
return update_wrapper(new_func, f)
def make_pass_decorator( object_type: type[T], ensure: bool = False) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type :func:`object_type`.
This generates a decorator that works roughly like this::
from functools import update_wrapper
def decorator(f): @pass_context def new_func(ctx, *args, **kwargs): obj = ctx.find_object(object_type) return ctx.invoke(f, obj, *args, **kwargs) return update_wrapper(new_func, f) return decorator
:param object_type: the type of the object to pass. :param ensure: if set to `True`, a new object will be created and remembered on the context if it's not there yet. """
def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: def new_func(*args: P.args, **kwargs: P.kwargs) -> R: ctx = get_current_context()
obj: T | None if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type)
if obj is None: raise RuntimeError( "Managed to invoke callback without a context" f" object of type {object_type.__name__!r}" " existing." )
return ctx.invoke(f, obj, *args, **kwargs)
return update_wrapper(new_func, f)
return decorator
def pass_meta_key( key: str, *, doc_description: str | None = None) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]: """Create a decorator that passes a key from :attr:`click.Context.meta` as the first argument to the decorated function.
:param key: Key in ``Context.meta`` to pass. :param doc_description: Description of the object being passed, inserted into the decorator's docstring. Defaults to "the 'key' key from Context.meta".
.. versionadded:: 8.0 """
def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]: def new_func(*args: P.args, **kwargs: P.kwargs) -> R: ctx = get_current_context() obj = ctx.meta[key] return ctx.invoke(f, obj, *args, **kwargs)
return update_wrapper(new_func, f)
if doc_description is None: doc_description = f"the {key!r} key from :attr:`click.Context.meta`"
decorator.__doc__ = ( f"Decorator that passes {doc_description} as the first argument" " to the decorated function." ) return decorator
CmdType = t.TypeVar("CmdType", bound=Command)
# variant: no call, directly as decorator for a function.@t.overloaddef command(name: _AnyCallable) -> Command: ...
# variant: with positional name and with positional or keyword cls argument:# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)@t.overloaddef command( name: str | None, cls: type[CmdType], **attrs: t.Any,) -> t.Callable[[_AnyCallable], CmdType]: ...
# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)@t.overloaddef command( name: None = None, *, cls: type[CmdType], **attrs: t.Any,) -> t.Callable[[_AnyCallable], CmdType]: ...
# variant: with optional string name, no cls argument provided.@t.overloaddef command( name: str | None = ..., cls: None = None, **attrs: t.Any) -> t.Callable[[_AnyCallable], Command]: ...
def command( name: str | _AnyCallable | None = None, cls: type[CmdType] | None = None, **attrs: t.Any,) -> Command | t.Callable[[_AnyCallable], Command | CmdType]: r"""Creates a new :class:`Command` and uses the decorated function as callback. This will also automatically attach all decorated :func:`option`\s and :func:`argument`\s as parameters to the command.
The name of the command defaults to the name of the function, converted to lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example, ``init_data_command`` becomes ``init-data``.
All keyword arguments are forwarded to the underlying command class. For the ``params`` argument, any decorated params are appended to the end of the list.
Once decorated the function turns into a :class:`Command` instance that can be invoked as a command line utility or be attached to a command :class:`Group`.
:param name: The name of the command. Defaults to modifying the function's name as described above. :param cls: The command class to create. Defaults to :class:`Command`.
.. versionchanged:: 8.2 The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed when generating the name.
.. versionchanged:: 8.1 This decorator can be applied without parentheses.
.. versionchanged:: 8.1 The ``params`` argument can be used. Decorated params are appended to the end of the list. """
func: t.Callable[[_AnyCallable], t.Any] | None = None
if callable(name): func = name name = None assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class." assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
if cls is None: cls = t.cast("type[CmdType]", Command)
def decorator(f: _AnyCallable) -> CmdType: if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.")
attr_params = attrs.pop("params", None) params = attr_params if attr_params is not None else []
try: decorator_params = f.__click_params__ # type: ignore except AttributeError: pass else: del f.__click_params__ # type: ignore params.extend(reversed(decorator_params))
if attrs.get("help") is None: attrs["help"] = f.__doc__
if t.TYPE_CHECKING: assert cls is not None assert not callable(name)
if name is not None: cmd_name = name else: cmd_name = f.__name__.lower().replace("_", "-") cmd_left, sep, suffix = cmd_name.rpartition("-")
if sep and suffix in {"command", "cmd", "group", "grp"}: cmd_name = cmd_left
cmd = cls(name=cmd_name, callback=f, params=params, **attrs) cmd.__doc__ = f.__doc__ return cmd
if func is not None: return decorator(func)
return decorator
GrpType = t.TypeVar("GrpType", bound=Group)
# variant: no call, directly as decorator for a function.@t.overloaddef group(name: _AnyCallable) -> Group: ...
# variant: with positional name and with positional or keyword cls argument:# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)@t.overloaddef group( name: str | None, cls: type[GrpType], **attrs: t.Any,) -> t.Callable[[_AnyCallable], GrpType]: ...
# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)@t.overloaddef group( name: None = None, *, cls: type[GrpType], **attrs: t.Any,) -> t.Callable[[_AnyCallable], GrpType]: ...
# variant: with optional string name, no cls argument provided.@t.overloaddef group( name: str | None = ..., cls: None = None, **attrs: t.Any) -> t.Callable[[_AnyCallable], Group]: ...
def group( name: str | _AnyCallable | None = None, cls: type[GrpType] | None = None, **attrs: t.Any,) -> Group | t.Callable[[_AnyCallable], Group | GrpType]: """Creates a new :class:`Group` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Group`.
.. versionchanged:: 8.1 This decorator can be applied without parentheses. """ if cls is None: cls = t.cast("type[GrpType]", Group)
if callable(name): return command(cls=cls, **attrs)(name)
return command(name, cls, **attrs)
def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None: if isinstance(f, Command): f.params.append(param) else: if not hasattr(f, "__click_params__"): f.__click_params__ = [] # type: ignore
f.__click_params__.append(param) # type: ignore
def argument( *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any) -> t.Callable[[FC], FC]: """Attaches an argument to the command. All positional arguments are passed as parameter declarations to :class:`Argument`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Argument` instance manually and attaching it to the :attr:`Command.params` list.
For the default argument class, refer to :class:`Argument` and :class:`Parameter` for descriptions of parameters.
:param cls: the argument class to instantiate. This defaults to :class:`Argument`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ if cls is None: cls = Argument
def decorator(f: FC) -> FC: _param_memo(f, cls(param_decls, **attrs)) return f
return decorator
def option( *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any) -> t.Callable[[FC], FC]: """Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list.
For the default option class, refer to :class:`Option` and :class:`Parameter` for descriptions of parameters.
:param cls: the option class to instantiate. This defaults to :class:`Option`. :param param_decls: Passed as positional arguments to the constructor of ``cls``. :param attrs: Passed as keyword arguments to the constructor of ``cls``. """ if cls is None: cls = Option
def decorator(f: FC) -> FC: _param_memo(f, cls(param_decls, **attrs)) return f
return decorator
def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Add a ``--yes`` option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit.
:param param_decls: One or more option names. Defaults to the single value ``"--yes"``. :param kwargs: Extra arguments are passed to :func:`option`. """
def callback(ctx: Context, param: Parameter, value: bool) -> None: if not value: ctx.abort()
if not param_decls: param_decls = ("--yes",)
kwargs.setdefault("is_flag", True) kwargs.setdefault("callback", callback) kwargs.setdefault("expose_value", False) kwargs.setdefault("prompt", "Do you want to continue?") kwargs.setdefault("help", "Confirm the action without prompting.") return option(*param_decls, **kwargs)
def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Add a ``--password`` option which prompts for a password, hiding input and asking to enter the value again for confirmation.
:param param_decls: One or more option names. Defaults to the single value ``"--password"``. :param kwargs: Extra arguments are passed to :func:`option`. """ if not param_decls: param_decls = ("--password",)
kwargs.setdefault("prompt", True) kwargs.setdefault("confirmation_prompt", True) kwargs.setdefault("hide_input", True) return option(*param_decls, **kwargs)
def version_option( version: str | None = None, *param_decls: str, package_name: str | None = None, prog_name: str | None = None, message: str | None = None, **kwargs: t.Any,) -> t.Callable[[FC], FC]: """Add a ``--version`` option which immediately prints the version number and exits the program.
If ``version`` is not provided, Click will try to detect it using :func:`importlib.metadata.version` to get the version for the ``package_name``.
If ``package_name`` is not provided, Click will try to detect it by inspecting the stack frames. This will be used to detect the version, so it must match the name of the installed package.
:param version: The version number to show. If not provided, Click will try to detect it. :param param_decls: One or more option names. Defaults to the single value ``"--version"``. :param package_name: The package name to detect the version from. If not provided, Click will try to detect it. :param prog_name: The name of the CLI to show in the message. If not provided, it will be detected from the command. :param message: The message to show. The values ``%(prog)s``, ``%(package)s``, and ``%(version)s`` are available. Defaults to ``"%(prog)s, version %(version)s"``. :param kwargs: Extra arguments are passed to :func:`option`. :raise RuntimeError: ``version`` could not be detected.
.. versionchanged:: 8.0 Add the ``package_name`` parameter, and the ``%(package)s`` value for messages.
.. versionchanged:: 8.0 Use :mod:`importlib.metadata` instead of ``pkg_resources``. The version is detected based on the package name, not the entry point name. The Python package name must match the installed package name, or be passed with ``package_name=``. """ if message is None: message = _("%(prog)s, version %(version)s")
if version is None and package_name is None: frame = inspect.currentframe() f_back = frame.f_back if frame is not None else None f_globals = f_back.f_globals if f_back is not None else None # break reference cycle # https://docs.python.org/3/library/inspect.html#the-interpreter-stack del frame
if f_globals is not None: package_name = f_globals.get("__name__")
if package_name == "__main__": package_name = f_globals.get("__package__")
if package_name: package_name = package_name.partition(".")[0]
def callback(ctx: Context, param: Parameter, value: bool) -> None: if not value or ctx.resilient_parsing: return
nonlocal prog_name nonlocal version
if prog_name is None: prog_name = ctx.find_root().info_name
if version is None and package_name is not None: import importlib.metadata
try: version = importlib.metadata.version(package_name) except importlib.metadata.PackageNotFoundError: raise RuntimeError( f"{package_name!r} is not installed. Try passing" " 'package_name' instead." ) from None
if version is None: raise RuntimeError( f"Could not determine the version for {package_name!r} automatically." )
echo( message % {"prog": prog_name, "package": package_name, "version": version}, color=ctx.color, ) ctx.exit()
if not param_decls: param_decls = ("--version",)
kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) kwargs.setdefault("help", _("Show the version and exit.")) kwargs["callback"] = callback return option(*param_decls, **kwargs)
def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]: """Pre-configured ``--help`` option which immediately prints the help page and exits the program.
:param param_decls: One or more option names. Defaults to the single value ``"--help"``. :param kwargs: Extra arguments are passed to :func:`option`. """
def show_help(ctx: Context, param: Parameter, value: bool) -> None: """Callback that print the help page on ``<stdout>`` and exits.""" if value and not ctx.resilient_parsing: echo(ctx.get_help(), color=ctx.color) ctx.exit()
if not param_decls: param_decls = ("--help",)
kwargs.setdefault("is_flag", True) kwargs.setdefault("expose_value", False) kwargs.setdefault("is_eager", True) kwargs.setdefault("help", _("Show this message and exit.")) kwargs.setdefault("callback", show_help)
return option(*param_decls, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308from __future__ import annotations
import collections.abc as cabcimport typing as tfrom gettext import gettext as _from gettext import ngettext
from ._compat import get_text_stderrfrom .globals import resolve_color_defaultfrom .utils import echofrom .utils import format_filename
if t.TYPE_CHECKING: from .core import Command from .core import Context from .core import Parameter
def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None: if param_hint is not None and not isinstance(param_hint, str): return " / ".join(repr(x) for x in param_hint)
return param_hint
class ClickException(Exception): """An exception that Click can handle and show to the user."""
#: The exit code for this exception. exit_code = 1
def __init__(self, message: str) -> None: super().__init__(message) # The context will be removed by the time we print the message, so cache # the color settings here to be used later on (in `show`) self.show_color: bool | None = resolve_color_default() self.message = message
def format_message(self) -> str: return self.message
def __str__(self) -> str: return self.message
def show(self, file: t.IO[t.Any] | None = None) -> None: if file is None: file = get_text_stderr()
echo( _("Error: {message}").format(message=self.format_message()), file=file, color=self.show_color, )
class UsageError(ClickException): """An internal exception that signals a usage error. This typically aborts any further handling.
:param message: the error message to display. :param ctx: optionally the context that caused this error. Click will fill in the context automatically in some situations. """
exit_code = 2
def __init__(self, message: str, ctx: Context | None = None) -> None: super().__init__(message) self.ctx = ctx self.cmd: Command | None = self.ctx.command if self.ctx else None
def show(self, file: t.IO[t.Any] | None = None) -> None: if file is None: file = get_text_stderr() color = None hint = "" if ( self.ctx is not None and self.ctx.command.get_help_option(self.ctx) is not None ): hint = _("Try '{command} {option}' for help.").format( command=self.ctx.command_path, option=self.ctx.help_option_names[0] ) hint = f"{hint}\n" if self.ctx is not None: color = self.ctx.color echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color) echo( _("Error: {message}").format(message=self.format_message()), file=file, color=color, )
class BadParameter(UsageError): """An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is).
.. versionadded:: 2.0
:param param: the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible. :param param_hint: a string that shows up as parameter name. This can be used as alternative to `param` in cases where custom validation should happen. If it is a string it's used as such, if it's a list then each item is quoted and separated. """
def __init__( self, message: str, ctx: Context | None = None, param: Parameter | None = None, param_hint: cabc.Sequence[str] | str | None = None, ) -> None: super().__init__(message, ctx) self.param = param self.param_hint = param_hint
def format_message(self) -> str: if self.param_hint is not None: param_hint = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: return _("Invalid value: {message}").format(message=self.message)
return _("Invalid value for {param_hint}: {message}").format( param_hint=_join_param_hints(param_hint), message=self.message )
class MissingParameter(BadParameter): """Raised if click required an option or argument but it was not provided when invoking the script.
.. versionadded:: 4.0
:param param_type: a string that indicates the type of the parameter. The default is to inherit the parameter type from the given `param`. Valid values are ``'parameter'``, ``'option'`` or ``'argument'``. """
def __init__( self, message: str | None = None, ctx: Context | None = None, param: Parameter | None = None, param_hint: cabc.Sequence[str] | str | None = None, param_type: str | None = None, ) -> None: super().__init__(message or "", ctx, param, param_hint) self.param_type = param_type
def format_message(self) -> str: if self.param_hint is not None: param_hint: cabc.Sequence[str] | str | None = self.param_hint elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) # type: ignore else: param_hint = None
param_hint = _join_param_hints(param_hint) param_hint = f" {param_hint}" if param_hint else ""
param_type = self.param_type if param_type is None and self.param is not None: param_type = self.param.param_type_name
msg = self.message if self.param is not None: msg_extra = self.param.type.get_missing_message( param=self.param, ctx=self.ctx ) if msg_extra: if msg: msg += f". {msg_extra}" else: msg = msg_extra
msg = f" {msg}" if msg else ""
# Translate param_type for known types. if param_type == "argument": missing = _("Missing argument") elif param_type == "option": missing = _("Missing option") elif param_type == "parameter": missing = _("Missing parameter") else: missing = _("Missing {param_type}").format(param_type=param_type)
return f"{missing}{param_hint}.{msg}"
def __str__(self) -> str: if not self.message: param_name = self.param.name if self.param else None return _("Missing parameter: {param_name}").format(param_name=param_name) else: return self.message
class NoSuchOption(UsageError): """Raised if click attempted to handle an option that does not exist.
.. versionadded:: 4.0 """
def __init__( self, option_name: str, message: str | None = None, possibilities: cabc.Sequence[str] | None = None, ctx: Context | None = None, ) -> None: if message is None: message = _("No such option: {name}").format(name=option_name)
super().__init__(message, ctx) self.option_name = option_name self.possibilities = possibilities
def format_message(self) -> str: if not self.possibilities: return self.message
possibility_str = ", ".join(sorted(self.possibilities)) suggest = ngettext( "Did you mean {possibility}?", "(Possible options: {possibilities})", len(self.possibilities), ).format(possibility=possibility_str, possibilities=possibility_str) return f"{self.message} {suggest}"
class BadOptionUsage(UsageError): """Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct.
.. versionadded:: 4.0
:param option_name: the name of the option being used incorrectly. """
def __init__( self, option_name: str, message: str, ctx: Context | None = None ) -> None: super().__init__(message, ctx) self.option_name = option_name
class BadArgumentUsage(UsageError): """Raised if an argument is generally supplied but the use of the argument was incorrect. This is for instance raised if the number of values for an argument is not correct.
.. versionadded:: 6.0 """
class NoArgsIsHelpError(UsageError): def __init__(self, ctx: Context) -> None: self.ctx: Context super().__init__(ctx.get_help(), ctx=ctx)
def show(self, file: t.IO[t.Any] | None = None) -> None: echo(self.format_message(), file=file, err=True, color=self.ctx.color)
class FileError(ClickException): """Raised if a file cannot be opened."""
def __init__(self, filename: str, hint: str | None = None) -> None: if hint is None: hint = _("unknown error")
super().__init__(hint) self.ui_filename: str = format_filename(filename) self.filename = filename
def format_message(self) -> str: return _("Could not open file {filename!r}: {message}").format( filename=self.ui_filename, message=self.message )
class Abort(RuntimeError): """An internal signalling exception that signals Click to abort."""
class Exit(RuntimeError): """An exception that indicates that the application should exit with some status code.
:param code: the status code to exit with. """
__slots__ = ("exit_code",)
def __init__(self, code: int = 0) -> None: self.exit_code: int = code123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301from __future__ import annotations
import collections.abc as cabcfrom contextlib import contextmanagerfrom gettext import gettext as _
from ._compat import term_lenfrom .parser import _split_opt
# Can force a width. This is used by the test systemFORCED_WIDTH: int | None = None
def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]: widths: dict[int, int] = {}
for row in rows: for idx, col in enumerate(row): widths[idx] = max(widths.get(idx, 0), term_len(col))
return tuple(y for x, y in sorted(widths.items()))
def iter_rows( rows: cabc.Iterable[tuple[str, str]], col_count: int) -> cabc.Iterator[tuple[str, ...]]: for row in rows: yield row + ("",) * (col_count - len(row))
def wrap_text( text: str, width: int = 78, initial_indent: str = "", subsequent_indent: str = "", preserve_paragraphs: bool = False,) -> str: """A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines).
If paragraphs are handled, a paragraph can be prefixed with an empty line containing the ``\\b`` character (``\\x08``) to indicate that no rewrapping should happen in that block.
:param text: the text that should be rewrapped. :param width: the maximum width for the text. :param initial_indent: the initial indent that should be placed on the first line as a string. :param subsequent_indent: the indent string that should be placed on each consecutive line. :param preserve_paragraphs: if this flag is set then the wrapping will intelligently handle paragraphs. """ from ._textwrap import TextWrapper
text = text.expandtabs() wrapper = TextWrapper( width, initial_indent=initial_indent, subsequent_indent=subsequent_indent, replace_whitespace=False, ) if not preserve_paragraphs: return wrapper.fill(text)
p: list[tuple[int, bool, str]] = [] buf: list[str] = [] indent = None
def _flush_par() -> None: if not buf: return if buf[0].strip() == "\b": p.append((indent or 0, True, "\n".join(buf[1:]))) else: p.append((indent or 0, False, " ".join(buf))) del buf[:]
for line in text.splitlines(): if not line: _flush_par() indent = None else: if indent is None: orig_len = term_len(line) line = line.lstrip() indent = orig_len - term_len(line) buf.append(line) _flush_par()
rv = [] for indent, raw, text in p: with wrapper.extra_indent(" " * indent): if raw: rv.append(wrapper.indent_only(text)) else: rv.append(wrapper.fill(text))
return "\n\n".join(rv)
class HelpFormatter: """This class helps with formatting text-based help pages. It's usually just needed for very special internal cases, but it's also exposed so that developers can write their own fancy outputs.
At present, it always writes into memory.
:param indent_increment: the additional increment for each level. :param width: the width for the text. This defaults to the terminal width clamped to a maximum of 78. """
def __init__( self, indent_increment: int = 2, width: int | None = None, max_width: int | None = None, ) -> None: self.indent_increment = indent_increment if max_width is None: max_width = 80 if width is None: import shutil
width = FORCED_WIDTH if width is None: width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50) self.width = width self.current_indent: int = 0 self.buffer: list[str] = []
def write(self, string: str) -> None: """Writes a unicode string into the internal buffer.""" self.buffer.append(string)
def indent(self) -> None: """Increases the indentation.""" self.current_indent += self.indent_increment
def dedent(self) -> None: """Decreases the indentation.""" self.current_indent -= self.indent_increment
def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None: """Writes a usage line into the buffer.
:param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: The prefix for the first line. Defaults to ``"Usage: "``. """ if prefix is None: prefix = f"{_('Usage:')} "
usage_prefix = f"{prefix:>{self.current_indent}}{prog} " text_width = self.width - self.current_indent
if text_width >= (term_len(usage_prefix) + 20): # The arguments will fit to the right of the prefix. indent = " " * term_len(usage_prefix) self.write( wrap_text( args, text_width, initial_indent=usage_prefix, subsequent_indent=indent, ) ) else: # The prefix is too long, put the arguments on the next line. self.write(usage_prefix) self.write("\n") indent = " " * (max(self.current_indent, term_len(prefix)) + 4) self.write( wrap_text( args, text_width, initial_indent=indent, subsequent_indent=indent ) )
self.write("\n")
def write_heading(self, heading: str) -> None: """Writes a heading into the buffer.""" self.write(f"{'':>{self.current_indent}}{heading}:\n")
def write_paragraph(self) -> None: """Writes a paragraph into the buffer.""" if self.buffer: self.write("\n")
def write_text(self, text: str) -> None: """Writes re-indented text into the buffer. This rewraps and preserves paragraphs. """ indent = " " * self.current_indent self.write( wrap_text( text, self.width, initial_indent=indent, subsequent_indent=indent, preserve_paragraphs=True, ) ) self.write("\n")
def write_dl( self, rows: cabc.Sequence[tuple[str, str]], col_max: int = 30, col_spacing: int = 2, ) -> None: """Writes a definition list into the buffer. This is how options and commands are usually formatted.
:param rows: a list of two item tuples for the terms and values. :param col_max: the maximum width of the first column. :param col_spacing: the number of spaces between the first and second column. """ rows = list(rows) widths = measure_table(rows) if len(widths) != 2: raise TypeError("Expected two columns for definition list")
first_col = min(widths[0], col_max) + col_spacing
for first, second in iter_rows(rows, len(widths)): self.write(f"{'':>{self.current_indent}}{first}") if not second: self.write("\n") continue if term_len(first) <= first_col - col_spacing: self.write(" " * (first_col - term_len(first))) else: self.write("\n") self.write(" " * (first_col + self.current_indent))
text_width = max(self.width - first_col - 2, 10) wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True) lines = wrapped_text.splitlines()
if lines: self.write(f"{lines[0]}\n")
for line in lines[1:]: self.write(f"{'':>{first_col + self.current_indent}}{line}\n") else: self.write("\n")
@contextmanager def section(self, name: str) -> cabc.Iterator[None]: """Helpful context manager that writes a paragraph, a heading, and the indents.
:param name: the section name that is written as heading. """ self.write_paragraph() self.write_heading(name) self.indent() try: yield finally: self.dedent()
@contextmanager def indentation(self) -> cabc.Iterator[None]: """A context manager that increases the indentation.""" self.indent() try: yield finally: self.dedent()
def getvalue(self) -> str: """Returns the buffer contents.""" return "".join(self.buffer)
def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]: """Given a list of option strings this joins them in the most appropriate way and returns them in the form ``(formatted_string, any_prefix_is_slash)`` where the second item in the tuple is a flag that indicates if any of the option prefixes was a slash. """ rv = [] any_prefix_is_slash = False
for opt in options: prefix = _split_opt(opt)[0]
if prefix == "/": any_prefix_is_slash = True
rv.append((len(prefix), opt))
rv.sort(key=lambda x: x[0]) return ", ".join(x[1] for x in rv), any_prefix_is_slash12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667from __future__ import annotations
import typing as tfrom threading import local
if t.TYPE_CHECKING: from .core import Context
_local = local()
@t.overloaddef get_current_context(silent: t.Literal[False] = False) -> Context: ...
@t.overloaddef get_current_context(silent: bool = ...) -> Context | None: ...
def get_current_context(silent: bool = False) -> Context | None: """Returns the current click context. This can be used as a way to access the current context object from anywhere. This is a more implicit alternative to the :func:`pass_context` decorator. This function is primarily useful for helpers such as :func:`echo` which might be interested in changing its behavior based on the current context.
To push the current context, :meth:`Context.scope` can be used.
.. versionadded:: 5.0
:param silent: if set to `True` the return value is `None` if no context is available. The default behavior is to raise a :exc:`RuntimeError`. """ try: return t.cast("Context", _local.stack[-1]) except (AttributeError, IndexError) as e: if not silent: raise RuntimeError("There is no active click context.") from e
return None
def push_context(ctx: Context) -> None: """Pushes a new context to the current stack.""" _local.__dict__.setdefault("stack", []).append(ctx)
def pop_context() -> None: """Removes the top level from the stack.""" _local.stack.pop()
def resolve_color_default(color: bool | None = None) -> bool | None: """Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context. """ if color is not None: return color
ctx = get_current_context(silent=True)
if ctx is not None: return ctx.color
return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532"""This module started out as largely a copy paste from the stdlib'soptparse module with the features removed that we do not need fromoptparse because we implement them in Click on a higher level (forinstance type handling, help formatting and a lot more).
The plan is to remove more and more from here over time.
The reason this is a different module and not optparse from the stdlibis that there are differences in 2.x and 3.x about the error messagesgenerated and optparse in the stdlib uses gettext for no good reasonand might cause us issues.
Click uses parts of optparse written by Gregory P. Ward and maintainedby the Python Software Foundation. This is limited to code in parser.py.
Copyright 2001-2006 Gregory P. Ward. All rights reserved.Copyright 2002-2006 Python Software Foundation. All rights reserved."""
# This code uses parts of optparse written by Gregory P. Ward and# maintained by the Python Software Foundation.# Copyright 2001-2006 Gregory P. Ward# Copyright 2002-2006 Python Software Foundationfrom __future__ import annotations
import collections.abc as cabcimport typing as tfrom collections import dequefrom gettext import gettext as _from gettext import ngettext
from ._utils import FLAG_NEEDS_VALUEfrom ._utils import UNSETfrom .exceptions import BadArgumentUsagefrom .exceptions import BadOptionUsagefrom .exceptions import NoSuchOptionfrom .exceptions import UsageError
if t.TYPE_CHECKING: from ._utils import T_FLAG_NEEDS_VALUE from ._utils import T_UNSET from .core import Argument as CoreArgument from .core import Context from .core import Option as CoreOption from .core import Parameter as CoreParameter
V = t.TypeVar("V")
def _unpack_args( args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]: """Given an iterable of arguments and an iterable of nargs specifications, it returns a tuple with all the unpacked arguments at the first index and all remaining arguments as the second.
The nargs specification is the number of arguments that should be consumed or `-1` to indicate that this position should eat up all the remainders.
Missing items are filled with ``UNSET``. """ args = deque(args) nargs_spec = deque(nargs_spec) rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = [] spos: int | None = None
def _fetch(c: deque[V]) -> V | T_UNSET: try: if spos is None: return c.popleft() else: return c.pop() except IndexError: return UNSET
while nargs_spec: nargs = _fetch(nargs_spec)
if nargs is None: continue
if nargs == 1: rv.append(_fetch(args)) # type: ignore[arg-type] elif nargs > 1: x = [_fetch(args) for _ in range(nargs)]
# If we're reversed, we're pulling in the arguments in reverse, # so we need to turn them around. if spos is not None: x.reverse()
rv.append(tuple(x)) elif nargs < 0: if spos is not None: raise TypeError("Cannot have two nargs < 0")
spos = len(rv) rv.append(UNSET)
# spos is the position of the wildcard (star). If it's not `None`, # we fill it with the remainder. if spos is not None: rv[spos] = tuple(args) args = [] rv[spos + 1 :] = reversed(rv[spos + 1 :])
return tuple(rv), list(args)
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 _normalize_opt(opt: str, ctx: Context | None) -> str: if ctx is None or ctx.token_normalize_func is None: return opt prefix, opt = _split_opt(opt) return f"{prefix}{ctx.token_normalize_func(opt)}"
class _Option: def __init__( self, obj: CoreOption, opts: cabc.Sequence[str], dest: str | None, action: str | None = None, nargs: int = 1, const: t.Any | None = None, ): self._short_opts = [] self._long_opts = [] self.prefixes: set[str] = set()
for opt in opts: prefix, value = _split_opt(opt) if not prefix: raise ValueError(f"Invalid start character for option ({opt})") self.prefixes.add(prefix[0]) if len(prefix) == 1 and len(value) == 1: self._short_opts.append(opt) else: self._long_opts.append(opt) self.prefixes.add(prefix)
if action is None: action = "store"
self.dest = dest self.action = action self.nargs = nargs self.const = const self.obj = obj
@property def takes_value(self) -> bool: return self.action in ("store", "append")
def process(self, value: t.Any, state: _ParsingState) -> None: if self.action == "store": state.opts[self.dest] = value # type: ignore elif self.action == "store_const": state.opts[self.dest] = self.const # type: ignore elif self.action == "append": state.opts.setdefault(self.dest, []).append(value) # type: ignore elif self.action == "append_const": state.opts.setdefault(self.dest, []).append(self.const) # type: ignore elif self.action == "count": state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore else: raise ValueError(f"unknown action '{self.action}'") state.order.append(self.obj)
class _Argument: def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1): self.dest = dest self.nargs = nargs self.obj = obj
def process( self, value: str | cabc.Sequence[str | None] | None | T_UNSET, state: _ParsingState, ) -> None: if self.nargs > 1: assert isinstance(value, cabc.Sequence) holes = sum(1 for x in value if x is UNSET) if holes == len(value): value = UNSET elif holes != 0: raise BadArgumentUsage( _("Argument {name!r} takes {nargs} values.").format( name=self.dest, nargs=self.nargs ) )
# We failed to collect any argument value so we consider the argument as unset. if value == (): value = UNSET
state.opts[self.dest] = value # type: ignore state.order.append(self.obj)
class _ParsingState: def __init__(self, rargs: list[str]) -> None: self.opts: dict[str, t.Any] = {} self.largs: list[str] = [] self.rargs = rargs self.order: list[CoreParameter] = []
class _OptionParser: """The option parser is an internal class that is ultimately used to parse options and arguments. It's modelled after optparse and brings a similar but vastly simplified API. It should generally not be used directly as the high level Click classes wrap it for you.
It's not nearly as extensible as optparse or argparse as it does not implement features that are implemented on a higher level (such as types or defaults).
:param ctx: optionally the :class:`~click.Context` where this parser should go with.
.. deprecated:: 8.2 Will be removed in Click 9.0. """
def __init__(self, ctx: Context | None = None) -> None: #: The :class:`~click.Context` for this parser. This might be #: `None` for some advanced use cases. self.ctx = ctx #: This controls how the parser deals with interspersed arguments. #: If this is set to `False`, the parser will stop on the first #: non-option. Click uses this to implement nested subcommands #: safely. self.allow_interspersed_args: bool = True #: This tells the parser how to deal with unknown options. By #: default it will error out (which is sensible), but there is a #: second mode where it will ignore it and continue processing #: after shifting all the unknown options into the resulting args. self.ignore_unknown_options: bool = False
if ctx is not None: self.allow_interspersed_args = ctx.allow_interspersed_args self.ignore_unknown_options = ctx.ignore_unknown_options
self._short_opt: dict[str, _Option] = {} self._long_opt: dict[str, _Option] = {} self._opt_prefixes = {"-", "--"} self._args: list[_Argument] = []
def add_option( self, obj: CoreOption, opts: cabc.Sequence[str], dest: str | None, action: str | None = None, nargs: int = 1, const: t.Any | None = None, ) -> None: """Adds a new option named `dest` to the parser. The destination is not inferred (unlike with optparse) and needs to be explicitly provided. Action can be any of ``store``, ``store_const``, ``append``, ``append_const`` or ``count``.
The `obj` can be used to identify the option in the order list that is returned from the parser. """ opts = [_normalize_opt(opt, self.ctx) for opt in opts] option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const) self._opt_prefixes.update(option.prefixes) for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option
def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None: """Adds a positional argument named `dest` to the parser.
The `obj` can be used to identify the option in the order list that is returned from the parser. """ self._args.append(_Argument(obj, dest=dest, nargs=nargs))
def parse_args( self, args: list[str] ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]: """Parses positional arguments and returns ``(values, args, order)`` for the parsed options and arguments as well as the leftover arguments if there are any. The order is a list of objects as they appear on the command line. If arguments appear multiple times they will be memorized multiple times as well. """ state = _ParsingState(args) try: self._process_args_for_options(state) self._process_args_for_args(state) except UsageError: if self.ctx is None or not self.ctx.resilient_parsing: raise return state.opts, state.largs, state.order
def _process_args_for_args(self, state: _ParsingState) -> None: pargs, args = _unpack_args( state.largs + state.rargs, [x.nargs for x in self._args] )
for idx, arg in enumerate(self._args): arg.process(pargs[idx], state)
state.largs = args state.rargs = []
def _process_args_for_options(self, state: _ParsingState) -> None: while state.rargs: arg = state.rargs.pop(0) arglen = len(arg) # Double dashes always handled explicitly regardless of what # prefixes are valid. if arg == "--": return elif arg[:1] in self._opt_prefixes and arglen > 1: self._process_opts(arg, state) elif self.allow_interspersed_args: state.largs.append(arg) else: state.rargs.insert(0, arg) return
# Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset!
def _match_long_opt( self, opt: str, explicit_value: str | None, state: _ParsingState ) -> None: if opt not in self._long_opt: from difflib import get_close_matches
possibilities = get_close_matches(opt, self._long_opt) raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
option = self._long_opt[opt] if option.takes_value: # At this point it's safe to modify rargs by injecting the # explicit value, because no exception is raised in this # branch. This means that the inserted value will be fully # consumed. if explicit_value is not None: state.rargs.insert(0, explicit_value)
value = self._get_value_from_state(opt, option, state)
elif explicit_value is not None: raise BadOptionUsage( opt, _("Option {name!r} does not take a value.").format(name=opt) )
else: value = UNSET
option.process(value, state)
def _match_short_opt(self, arg: str, state: _ParsingState) -> None: stop = False i = 1 prefix = arg[0] unknown_options = []
for ch in arg[1:]: opt = _normalize_opt(f"{prefix}{ch}", self.ctx) option = self._short_opt.get(opt) i += 1
if not option: if self.ignore_unknown_options: unknown_options.append(ch) continue raise NoSuchOption(opt, ctx=self.ctx) if option.takes_value: # Any characters left in arg? Pretend they're the # next arg, and stop consuming characters of arg. if i < len(arg): state.rargs.insert(0, arg[i:]) stop = True
value = self._get_value_from_state(opt, option, state)
else: value = UNSET
option.process(value, state)
if stop: break
# If we got any unknown options we recombine the string of the # remaining options and re-attach the prefix, then report that # to the state as new larg. This way there is basic combinatorics # that can be achieved while still ignoring unknown arguments. if self.ignore_unknown_options and unknown_options: state.largs.append(f"{prefix}{''.join(unknown_options)}")
def _get_value_from_state( self, option_name: str, option: _Option, state: _ParsingState ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE: nargs = option.nargs
value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE
if len(state.rargs) < nargs: if option.obj._flag_needs_value: # Option allows omitting the value. value = FLAG_NEEDS_VALUE else: raise BadOptionUsage( option_name, ngettext( "Option {name!r} requires an argument.", "Option {name!r} requires {nargs} arguments.", nargs, ).format(name=option_name, nargs=nargs), ) elif nargs == 1: next_rarg = state.rargs[0]
if ( option.obj._flag_needs_value and isinstance(next_rarg, str) and next_rarg[:1] in self._opt_prefixes and len(next_rarg) > 1 ): # The next arg looks like the start of an option, don't # use it as the value if omitting the value is allowed. value = FLAG_NEEDS_VALUE else: value = state.rargs.pop(0) else: value = tuple(state.rargs[:nargs]) del state.rargs[:nargs]
return value
def _process_opts(self, arg: str, state: _ParsingState) -> None: explicit_value = None # Long option handling happens in two parts. The first part is # supporting explicitly attached values. In any case, we will try # to long match the option first. if "=" in arg: long_opt, explicit_value = arg.split("=", 1) else: long_opt = arg norm_long_opt = _normalize_opt(long_opt, self.ctx)
# At this point we will match the (assumed) long option through # the long option matching code. Note that this allows options # like "-foo" to be matched as long options. try: self._match_long_opt(norm_long_opt, explicit_value, state) except NoSuchOption: # At this point the long option matching failed, and we need # to try with short options. However there is a special rule # which says, that if we have a two character options prefix # (applies to "--foo" for instance), we do not dispatch to the # short option code and will instead raise the no option # error. if arg[:2] not in self._opt_prefixes: self._match_short_opt(arg, state) return
if not self.ignore_unknown_options: raise
state.largs.append(arg)
def __getattr__(name: str) -> object: import warnings
if name in { "OptionParser", "Argument", "Option", "split_opt", "normalize_opt", "ParsingState", }: warnings.warn( f"'parser.{name}' is deprecated and will be removed in Click 9.0." " The old parser is available in 'optparse'.", DeprecationWarning, stacklevel=2, ) return globals()[f"_{name}"]
if name == "split_arg_string": from .shell_completion import split_arg_string
warnings.warn( "Importing 'parser.split_arg_string' is deprecated, it will only be" " available in 'shell_completion' in Click 9.0.", DeprecationWarning, stacklevel=2, ) return split_arg_string
raise AttributeError(name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667from __future__ import annotations
import collections.abc as cabcimport osimport reimport typing as tfrom gettext import gettext as _
from .core import Argumentfrom .core import Commandfrom .core import Contextfrom .core import Groupfrom .core import Optionfrom .core import Parameterfrom .core import ParameterSourcefrom .utils import echo
def shell_complete( cli: Command, ctx_args: cabc.MutableMapping[str, t.Any], prog_name: str, complete_var: str, instruction: str,) -> int: """Perform shell completion for the given CLI program.
:param cli: Command being called. :param ctx_args: Extra arguments to pass to ``cli.make_context``. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction. :param instruction: Value of ``complete_var`` with the completion instruction and shell, in the form ``instruction_shell``. :return: Status code to exit with. """ shell, _, instruction = instruction.partition("_") comp_cls = get_completion_class(shell)
if comp_cls is None: return 1
comp = comp_cls(cli, ctx_args, prog_name, complete_var)
if instruction == "source": echo(comp.source()) return 0
if instruction == "complete": echo(comp.complete()) return 0
return 1
class CompletionItem: """Represents a completion value and metadata about the value. The default metadata is ``type`` to indicate special shell handling, and ``help`` if a shell supports showing a help string next to the value.
Arbitrary parameters can be passed when creating the object, and accessed using ``item.attr``. If an attribute wasn't passed, accessing it returns ``None``.
:param value: The completion suggestion. :param type: Tells the shell script to provide special completion support for the type. Click uses ``"dir"`` and ``"file"``. :param help: String shown next to the value if supported. :param kwargs: Arbitrary metadata. The built-in implementations don't use this, but custom type completions paired with custom shell support could use it. """
__slots__ = ("value", "type", "help", "_info")
def __init__( self, value: t.Any, type: str = "plain", help: str | None = None, **kwargs: t.Any, ) -> None: self.value: t.Any = value self.type: str = type self.help: str | None = help self._info = kwargs
def __getattr__(self, name: str) -> t.Any: return self._info.get(name)
# Only Bash >= 4.4 has the nosort option._SOURCE_BASH = """\%(complete_func)s() { local IFS=$'\\n' local response
response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \%(complete_var)s=bash_complete $1)
for completion in $response; do IFS=',' read type value <<< "$completion"
if [[ $type == 'dir' ]]; then COMPREPLY=() compopt -o dirnames elif [[ $type == 'file' ]]; then COMPREPLY=() compopt -o default elif [[ $type == 'plain' ]]; then COMPREPLY+=($value) fi done
return 0}
%(complete_func)s_setup() { complete -o nosort -F %(complete_func)s %(prog_name)s}
%(complete_func)s_setup;"""
# See ZshComplete.format_completion below, and issue #2703, before# changing this script.## (TL;DR: _describe is picky about the format, but this Zsh script snippet# is already widely deployed. So freeze this script, and use clever-ish# handling of colons in ZshComplet.format_completion.)_SOURCE_ZSH = """\#compdef %(prog_name)s
%(complete_func)s() { local -a completions local -a completions_with_descriptions local -a response (( ! $+commands[%(prog_name)s] )) && return 1
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \%(complete_var)s=zsh_complete %(prog_name)s)}")
for type key descr in ${response}; do if [[ "$type" == "plain" ]]; then if [[ "$descr" == "_" ]]; then completions+=("$key") else completions_with_descriptions+=("$key":"$descr") fi elif [[ "$type" == "dir" ]]; then _path_files -/ elif [[ "$type" == "file" ]]; then _path_files -f fi done
if [ -n "$completions_with_descriptions" ]; then _describe -V unsorted completions_with_descriptions -U fi
if [ -n "$completions" ]; then compadd -U -V unsorted -a completions fi}
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then # autoload from fpath, call function directly %(complete_func)s "$@"else # eval/source/. command, register function for later compdef %(complete_func)s %(prog_name)sfi"""
_SOURCE_FISH = """\function %(complete_func)s; set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \COMP_CWORD=(commandline -t) %(prog_name)s);
for completion in $response; set -l metadata (string split "," $completion);
if test $metadata[1] = "dir"; __fish_complete_directories $metadata[2]; else if test $metadata[1] = "file"; __fish_complete_path $metadata[2]; else if test $metadata[1] = "plain"; echo $metadata[2]; end; end;end;
complete --no-files --command %(prog_name)s --arguments \"(%(complete_func)s)";"""
class ShellComplete: """Base class for providing shell completion support. A subclass for a given shell will override attributes and methods to implement the completion instructions (``source`` and ``complete``).
:param cli: Command being called. :param prog_name: Name of the executable in the shell. :param complete_var: Name of the environment variable that holds the completion instruction.
.. versionadded:: 8.0 """
name: t.ClassVar[str] """Name to register the shell as with :func:`add_completion_class`. This is used in completion instructions (``{name}_source`` and ``{name}_complete``). """
source_template: t.ClassVar[str] """Completion script template formatted by :meth:`source`. This must be provided by subclasses. """
def __init__( self, cli: Command, ctx_args: cabc.MutableMapping[str, t.Any], prog_name: str, complete_var: str, ) -> None: self.cli = cli self.ctx_args = ctx_args self.prog_name = prog_name self.complete_var = complete_var
@property def func_name(self) -> str: """The name of the shell function defined by the completion script. """ safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII) return f"_{safe_name}_completion"
def source_vars(self) -> dict[str, t.Any]: """Vars for formatting :attr:`source_template`.
By default this provides ``complete_func``, ``complete_var``, and ``prog_name``. """ return { "complete_func": self.func_name, "complete_var": self.complete_var, "prog_name": self.prog_name, }
def source(self) -> str: """Produce the shell script that defines the completion function. By default this ``%``-style formats :attr:`source_template` with the dict returned by :meth:`source_vars`. """ return self.source_template % self.source_vars()
def get_completion_args(self) -> tuple[list[str], str]: """Use the env vars defined by the shell script to return a tuple of ``args, incomplete``. This must be implemented by subclasses. """ raise NotImplementedError
def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]: """Determine the context and last complete command or parameter from the complete args. Call that object's ``shell_complete`` method to get the completions for the incomplete value.
:param args: List of complete args before the incomplete value. :param incomplete: Value being completed. May be empty. """ ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args) obj, incomplete = _resolve_incomplete(ctx, args, incomplete) return obj.shell_complete(ctx, incomplete)
def format_completion(self, item: CompletionItem) -> str: """Format a completion item into the form recognized by the shell script. This must be implemented by subclasses.
:param item: Completion item to format. """ raise NotImplementedError
def complete(self) -> str: """Produce the completion data to send back to the shell.
By default this calls :meth:`get_completion_args`, gets the completions, then calls :meth:`format_completion` for each completion. """ 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 BashComplete(ShellComplete): """Shell completion for Bash."""
name = "bash" source_template = _SOURCE_BASH
@staticmethod def _check_version() -> None: import shutil import subprocess
bash_exe = shutil.which("bash")
if bash_exe is None: match = None else: output = subprocess.run( [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE, ) match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
if match is not None: major, minor = match.groups()
if major < "4" or major == "4" and minor < "4": echo( _( "Shell completion is not supported for Bash" " versions older than 4.4." ), err=True, ) else: echo( _("Couldn't detect Bash version, shell completion is not supported."), err=True, )
def source(self) -> str: self._check_version() return super().source()
def get_completion_args(self) -> tuple[list[str], str]: cwords = 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: CompletionItem) -> str: return f"{item.type},{item.value}"
class ZshComplete(ShellComplete): """Shell completion for Zsh."""
name = "zsh" source_template = _SOURCE_ZSH
def get_completion_args(self) -> tuple[list[str], str]: cwords = 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: CompletionItem) -> str: help_ = item.help or "_" # The zsh completion script uses `_describe` on items with help # texts (which splits the item help from the item value at the # first unescaped colon) and `compadd` on items without help # text (which uses the item value as-is and does not support # colon escaping). So escape colons in the item value if and # only if the item help is not the sentinel "_" value, as used # by the completion script. # # (The zsh completion script is potentially widely deployed, and # thus harder to fix than this method.) # # See issue #1812 and issue #2703 for further context. value = item.value.replace(":", r"\:") if help_ != "_" else item.value return f"{item.type}\n{value}\n{help_}"
class FishComplete(ShellComplete): """Shell completion for Fish."""
name = "fish" source_template = _SOURCE_FISH
def get_completion_args(self) -> tuple[list[str], str]: cwords = split_arg_string(os.environ["COMP_WORDS"]) incomplete = os.environ["COMP_CWORD"] if incomplete: incomplete = split_arg_string(incomplete)[0] args = cwords[1:]
# Fish stores the partial word in both COMP_WORDS and # COMP_CWORD, remove it from complete args. if incomplete and args and args[-1] == incomplete: args.pop()
return args, incomplete
def format_completion(self, item: CompletionItem) -> str: if item.help: return f"{item.type},{item.value}\t{item.help}"
return f"{item.type},{item.value}"
ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")
_available_shells: dict[str, type[ShellComplete]] = { "bash": BashComplete, "fish": FishComplete, "zsh": ZshComplete,}
def add_completion_class( cls: ShellCompleteType, name: str | None = None) -> ShellCompleteType: """Register a :class:`ShellComplete` subclass under the given name. The name will be provided by the completion instruction environment variable during completion.
:param cls: The completion class that will handle completion for the shell. :param name: Name to register the class under. Defaults to the class's ``name`` attribute. """ if name is None: name = cls.name
_available_shells[name] = cls
return cls
def get_completion_class(shell: str) -> type[ShellComplete] | None: """Look up a registered :class:`ShellComplete` subclass by the name provided by the completion instruction environment variable. If the name isn't registered, returns ``None``.
:param shell: Name the class is registered under. """ return _available_shells.get(shell)
def split_arg_string(string: str) -> list[str]: """Split an argument string as with :func:`shlex.split`, but don't fail if the string is incomplete. Ignores a missing closing quote or incomplete escape sequence and uses the partial token as-is.
.. code-block:: python
split_arg_string("example 'my file") ["example", "my file"]
split_arg_string("example my\\") ["example", "my"]
:param string: String to split.
.. versionchanged:: 8.2 Moved to ``shell_completion`` from ``parser``. """ import shlex
lex = shlex.shlex(string, posix=True) lex.whitespace_split = True lex.commenters = "" out = []
try: for token in lex: out.append(token) except ValueError: # Raised when end-of-string is reached in an invalid state. Use # the partial token as-is. The quote or escape character is in # lex.state, not lex.token. out.append(lex.token)
return out
def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool: """Determine if the given parameter is an argument that can still accept values.
:param ctx: Invocation context for the command represented by the parsed complete args. :param param: Argument object being checked. """ if not isinstance(param, Argument): return False
assert param.name is not None # Will be None if expose_value is False. value = ctx.params.get(param.name) return ( param.nargs == -1 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE or ( param.nargs > 1 and isinstance(value, (tuple, list)) and len(value) < param.nargs ) )
def _start_of_option(ctx: Context, value: str) -> bool: """Check if the value looks like the start of an option.""" if not value: return False
c = value[0] return c in ctx._opt_prefixes
def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool: """Determine if the given parameter is an option that needs a value.
:param args: List of complete args before the incomplete value. :param param: Option object being checked. """ if not isinstance(param, Option): return False
if param.is_flag or param.count: return False
last_option = None
for index, arg in enumerate(reversed(args)): if index + 1 > param.nargs: break
if _start_of_option(ctx, arg): last_option = arg break
return last_option is not None and last_option in param.opts
def _resolve_context( cli: Command, ctx_args: cabc.MutableMapping[str, t.Any], prog_name: str, args: list[str],) -> Context: """Produce the context hierarchy starting with the command and traversing the complete arguments. This only follows the commands, it doesn't trigger input prompts or callbacks.
:param cli: Command being called. :param prog_name: Name of the executable in the shell. :param args: List of complete args before the incomplete value. """ ctx_args["resilient_parsing"] = True with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx: args = ctx._protected_args + ctx.args
while args: command = ctx.command
if isinstance(command, Group): if not command.chain: name, cmd, args = command.resolve_command(ctx, args)
if cmd is None: return ctx
with cmd.make_context( name, args, parent=ctx, resilient_parsing=True ) as sub_ctx: ctx = sub_ctx args = ctx._protected_args + ctx.args else: sub_ctx = ctx
while args: name, cmd, args = command.resolve_command(ctx, args)
if cmd is None: return ctx
with cmd.make_context( name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False, resilient_parsing=True, ) as sub_sub_ctx: sub_ctx = sub_sub_ctx args = sub_ctx.args
ctx = sub_ctx args = [*sub_ctx._protected_args, *sub_ctx.args] else: break
return ctx
def _resolve_incomplete( ctx: Context, args: list[str], incomplete: str) -> tuple[Command | Parameter, str]: """Find the Click object that will handle the completion of the incomplete value. Return the object and the incomplete value.
:param ctx: Invocation context for the command represented by the parsed complete args. :param args: List of complete args before the incomplete value. :param incomplete: Value being completed. May be empty. """ # Different shells treat an "=" between a long option name and # value differently. Might keep the value joined, return the "=" # as a separate item, or return the split name and value. Always # split and discard the "=" to make completion easier. if incomplete == "=": incomplete = "" elif "=" in incomplete and _start_of_option(ctx, incomplete): name, _, incomplete = incomplete.partition("=") args.append(name)
# The "--" marker tells Click to stop treating values as options # even if they start with the option character. If it hasn't been # given and the incomplete arg looks like an option, the current # command will provide option name completions. if "--" not in args and _start_of_option(ctx, incomplete): return ctx.command, incomplete
params = ctx.command.get_params(ctx)
# If the last complete arg is an option name with an incomplete # value, the option will provide value completions. for param in params: if _is_incomplete_option(ctx, args, param): return param, incomplete
# It's not an option name or value. The first argument without a # parsed value will provide value completions. for param in params: if _is_incomplete_argument(ctx, param): return param, incomplete
# There were no unparsed arguments, the command may be a group that # will provide command name completions. return ctx.command, incomplete123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883from __future__ import annotations
import collections.abc as cabcimport inspectimport ioimport itertoolsimport sysimport typing as tfrom contextlib import AbstractContextManagerfrom gettext import gettext as _
from ._compat import isattyfrom ._compat import strip_ansifrom .exceptions import Abortfrom .exceptions import UsageErrorfrom .globals import resolve_color_defaultfrom .types import Choicefrom .types import convert_typefrom .types import ParamTypefrom .utils import echofrom .utils import LazyFile
if t.TYPE_CHECKING: from ._termui_impl import ProgressBar
V = t.TypeVar("V")
# The prompt functions to use. The doc tools currently override these# functions to customize how they work.visible_prompt_func: t.Callable[[str], str] = input
_ansi_colors = { "black": 30, "red": 31, "green": 32, "yellow": 33, "blue": 34, "magenta": 35, "cyan": 36, "white": 37, "reset": 39, "bright_black": 90, "bright_red": 91, "bright_green": 92, "bright_yellow": 93, "bright_blue": 94, "bright_magenta": 95, "bright_cyan": 96, "bright_white": 97,}_ansi_reset_all = "\033[0m"
def hidden_prompt_func(prompt: str) -> str: import getpass
return getpass.getpass(prompt)
def _build_prompt( text: str, suffix: str, show_default: bool = False, default: t.Any | None = None, show_choices: bool = True, type: ParamType | None = None,) -> str: prompt = text if type is not None and show_choices and isinstance(type, Choice): prompt += f" ({', '.join(map(str, type.choices))})" if default is not None and show_default: prompt = f"{prompt} [{_format_default(default)}]" return f"{prompt}{suffix}"
def _format_default(default: t.Any) -> t.Any: if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"): return default.name
return default
def prompt( text: str, default: t.Any | None = None, hide_input: bool = False, confirmation_prompt: bool | str = False, type: ParamType | t.Any | None = None, value_proc: t.Callable[[str], t.Any] | None = None, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, show_choices: bool = True,) -> t.Any: """Prompts a user for input. This is a convenience function that can be used to prompt a user for input later.
If the user aborts the input by sending an interrupt signal, this function will catch it and raise a :exc:`Abort` exception.
:param text: the text to show for the prompt. :param default: the default value to use if no input happens. If this is not given it will prompt until it's aborted. :param hide_input: if this is set to true then the input value will be hidden. :param confirmation_prompt: Prompt a second time to confirm the value. Can be set to a string instead of ``True`` to customize the message. :param type: the type to use to check the value against. :param value_proc: if this parameter is provided it's a function that is invoked instead of the type conversion to convert a value. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo. :param show_choices: Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is "Group by" then the prompt will be "Group by (day, week): ".
.. versionchanged:: 8.3.1 A space is no longer appended to the prompt.
.. versionadded:: 8.0 ``confirmation_prompt`` can be a custom string.
.. versionadded:: 7.0 Added the ``show_choices`` parameter.
.. versionadded:: 6.0 Added unicode support for cmd.exe on Windows.
.. versionadded:: 4.0 Added the `err` parameter.
"""
def prompt_func(text: str) -> str: f = hidden_prompt_func if hide_input else visible_prompt_func try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(text[:-1], nl=False, err=err) # Echo the last character to stdout to work around an issue where # readline causes backspace to clear the whole line. return f(text[-1:]) except (KeyboardInterrupt, EOFError): # getpass doesn't print a newline if the user aborts input with ^C. # Allegedly this behavior is inherited from getpass(3). # A doc bug has been filed at https://bugs.python.org/issue24711 if hide_input: echo(None, err=err) raise Abort() from None
if value_proc is None: value_proc = convert_type(type, default)
prompt = _build_prompt( text, prompt_suffix, show_default, default, show_choices, type )
if confirmation_prompt: if confirmation_prompt is True: confirmation_prompt = _("Repeat for confirmation")
confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
while True: while True: value = prompt_func(prompt) if value: break elif default is not None: value = default break try: result = value_proc(value) except UsageError as e: if hide_input: echo(_("Error: The value you entered was invalid."), err=err) else: echo(_("Error: {e.message}").format(e=e), err=err) continue if not confirmation_prompt: return result while True: value2 = prompt_func(confirmation_prompt) is_empty = not value and not value2 if value2 or is_empty: break if value == value2: return result echo(_("Error: The two entered values do not match."), err=err)
def confirm( text: str, default: bool | None = False, abort: bool = False, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False,) -> bool: """Prompts for confirmation (yes/no question).
If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception.
:param text: the question to ask. :param default: The default value to use when no input is given. If ``None``, repeat until input is given. :param abort: if this is set to `True` a negative answer aborts the exception by raising :exc:`Abort`. :param prompt_suffix: a suffix that should be added to the prompt. :param show_default: shows or hides the default value in the prompt. :param err: if set to true the file defaults to ``stderr`` instead of ``stdout``, the same as with echo.
.. versionchanged:: 8.3.1 A space is no longer appended to the prompt.
.. versionchanged:: 8.0 Repeat until input is given if ``default`` is ``None``.
.. versionadded:: 4.0 Added the ``err`` parameter. """ prompt = _build_prompt( text, prompt_suffix, show_default, "y/n" if default is None else ("Y/n" if default else "y/N"), )
while True: try: # Write the prompt separately so that we get nice # coloring through colorama on Windows echo(prompt[:-1], nl=False, err=err) # Echo the last character to stdout to work around an issue where # readline causes backspace to clear the whole line. value = visible_prompt_func(prompt[-1:]).lower().strip() except (KeyboardInterrupt, EOFError): raise Abort() from None if value in ("y", "yes"): rv = True elif value in ("n", "no"): rv = False elif default is not None and value == "": rv = default else: echo(_("Error: invalid input"), err=err) continue break if abort and not rv: raise Abort() return rv
def echo_via_pager( text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str, color: bool | None = None,) -> None: """This function takes a text and shows it via an environment specific pager on stdout.
.. versionchanged:: 3.0 Added the `color` flag.
:param text_or_generator: the text to page, or alternatively, a generator emitting the text to page. :param color: controls if the pager supports ANSI colors or not. The default is autodetection. """ color = resolve_color_default(color)
if inspect.isgeneratorfunction(text_or_generator): i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)() elif isinstance(text_or_generator, str): i = [text_or_generator] else: i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
# convert every element of i to a text type if necessary text_generator = (el if isinstance(el, str) else str(el) for el in i)
from ._termui_impl import pager
return pager(itertools.chain(text_generator, "\n"), color)
@t.overloaddef progressbar( *, length: int, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1,) -> ProgressBar[int]: ...
@t.overloaddef progressbar( iterable: cabc.Iterable[V] | None = None, length: int | None = None, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1,) -> ProgressBar[V]: ...
def progressbar( iterable: cabc.Iterable[V] | None = None, length: int | None = None, label: str | None = None, hidden: bool = False, show_eta: bool = True, show_percent: bool | None = None, show_pos: bool = False, item_show_func: t.Callable[[V | None], str | None] | None = None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file: t.TextIO | None = None, color: bool | None = None, update_min_steps: int = 1,) -> ProgressBar[V]: """This function creates an iterable context manager that can be used to iterate over something while showing a progress bar. It will either iterate over the `iterable` or `length` items (that are counted up). While iteration happens, this function will print a rendered progress bar to the given `file` (defaults to stdout) and will attempt to calculate remaining time and more. By default, this progress bar will not be rendered if the file is not a terminal.
The context manager creates the progress bar. When the context manager is entered the progress bar is already created. With every iteration over the progress bar, the iterable passed to the bar is advanced and the bar is updated. When the context manager exits, a newline is printed and the progress bar is finalized on screen.
Note: The progress bar is currently designed for use cases where the total progress can be expected to take at least several seconds. Because of this, the ProgressBar class object won't display progress that is considered too fast, and progress where the time between steps is less than a second.
No printing must happen or the progress bar will be unintentionally destroyed.
Example usage::
with progressbar(items) as bar: for item in bar: do_something_with(item)
Alternatively, if no iterable is specified, one can manually update the progress bar through the `update()` method instead of directly iterating over the progress bar. The update method accepts the number of steps to increment the bar with::
with progressbar(length=chunks.total_bytes) as bar: for chunk in chunks: process_chunk(chunk) bar.update(chunks.bytes)
The ``update()`` method also takes an optional value specifying the ``current_item`` at the new position. This is useful when used together with ``item_show_func`` to customize the output for each manual step::
with click.progressbar( length=total_size, label='Unzipping archive', item_show_func=lambda a: a.filename ) as bar: for archive in zip_file: archive.extract() bar.update(archive.size, archive)
:param iterable: an iterable to iterate over. If not provided the length is required. :param length: the number of items to iterate over. By default the progressbar will attempt to ask the iterator about its length, which might or might not work. If an iterable is also provided this parameter can be used to override the length. If an iterable is not provided the progress bar will iterate over a range of that length. :param label: the label to show next to the progress bar. :param hidden: hide the progressbar. Defaults to ``False``. When no tty is detected, it will only print the progressbar label. Setting this to ``False`` also disables that. :param show_eta: enables or disables the estimated time display. This is automatically disabled if the length cannot be determined. :param show_percent: enables or disables the percentage display. The default is `True` if the iterable has a length or `False` if not. :param show_pos: enables or disables the absolute position display. The default is `False`. :param item_show_func: A function called with the current item which can return a string to show next to the progress bar. If the function returns ``None`` nothing is shown. The current item can be ``None``, such as when entering and exiting the bar. :param fill_char: the character to use to show the filled part of the progress bar. :param empty_char: the character to use to show the non-filled part of the progress bar. :param bar_template: the format string to use as template for the bar. The parameters in it are ``label`` for the label, ``bar`` for the progress bar and ``info`` for the info section. :param info_sep: the separator between multiple info items (eta etc.) :param width: the width of the progress bar in characters, 0 means full terminal width :param file: The file to write to. If this is not a terminal then only the label is printed. :param color: controls if the terminal supports ANSI colors or not. The default is autodetection. This is only needed if ANSI codes are included anywhere in the progress bar output which is not the case by default. :param update_min_steps: Render only when this many updates have completed. This allows tuning for very fast iterators.
.. versionadded:: 8.2 The ``hidden`` argument.
.. versionchanged:: 8.0 Output is shown even if execution time is less than 0.5 seconds.
.. versionchanged:: 8.0 ``item_show_func`` shows the current item, not the previous one.
.. versionchanged:: 8.0 Labels are echoed if the output is not a TTY. Reverts a change in 7.0 that removed all output.
.. versionadded:: 8.0 The ``update_min_steps`` parameter.
.. versionadded:: 4.0 The ``color`` parameter and ``update`` method.
.. versionadded:: 2.0 """ from ._termui_impl import ProgressBar
color = resolve_color_default(color) return ProgressBar( iterable=iterable, length=length, hidden=hidden, show_eta=show_eta, show_percent=show_percent, show_pos=show_pos, item_show_func=item_show_func, fill_char=fill_char, empty_char=empty_char, bar_template=bar_template, info_sep=info_sep, file=file, label=label, width=width, color=color, update_min_steps=update_min_steps, )
def clear() -> None: """Clears the terminal screen. This will have the effect of clearing the whole visible space of the terminal and moving the cursor to the top left. This does not do anything if not connected to a terminal.
.. versionadded:: 2.0 """ if not isatty(sys.stdout): return
# ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor echo("\033[2J\033[1;1H", nl=False)
def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str: if isinstance(color, int): return f"{38 + offset};5;{color:d}"
if isinstance(color, (tuple, list)): r, g, b = color return f"{38 + offset};2;{r:d};{g:d};{b:d}"
return str(_ansi_colors[color] + offset)
def style( text: t.Any, fg: int | tuple[int, int, int] | str | None = None, bg: int | tuple[int, int, int] | str | None = None, bold: bool | None = None, dim: bool | None = None, underline: bool | None = None, overline: bool | None = None, italic: bool | None = None, blink: bool | None = None, reverse: bool | None = None, strikethrough: bool | None = None, reset: bool = True,) -> str: """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``.
Examples::
click.echo(click.style('Hello World!', fg='green')) click.echo(click.style('ATTENTION!', blink=True)) click.echo(click.style('Some things', reverse=True, fg='cyan')) click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
Supported color names:
* ``black`` (might be a gray) * ``red`` * ``green`` * ``yellow`` (might be an orange) * ``blue`` * ``magenta`` * ``cyan`` * ``white`` (might be light gray) * ``bright_black`` * ``bright_red`` * ``bright_green`` * ``bright_yellow`` * ``bright_blue`` * ``bright_magenta`` * ``bright_cyan`` * ``bright_white`` * ``reset`` (reset the color code only)
If the terminal supports it, color may also be specified as:
- An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode. - An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode.
See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information.
:param text: the string to style with ansi codes. :param fg: if provided this will become the foreground color. :param bg: if provided this will become the background color. :param bold: if provided this will enable or disable bold mode. :param dim: if provided this will enable or disable dim mode. This is badly supported. :param underline: if provided this will enable or disable underline. :param overline: if provided this will enable or disable overline. :param italic: if provided this will enable or disable italic. :param blink: if provided this will enable or disable blinking. :param reverse: if provided this will enable or disable inverse rendering (foreground becomes background and the other way round). :param strikethrough: if provided this will enable or disable striking through text. :param reset: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.
.. versionchanged:: 8.0 A non-string ``message`` is converted to a string.
.. versionchanged:: 8.0 Added support for 256 and RGB color codes.
.. versionchanged:: 8.0 Added the ``strikethrough``, ``italic``, and ``overline`` parameters.
.. versionchanged:: 7.0 Added support for bright colors.
.. versionadded:: 2.0 """ if not isinstance(text, str): text = str(text)
bits = []
if fg: try: bits.append(f"\033[{_interpret_color(fg)}m") except KeyError: raise TypeError(f"Unknown color {fg!r}") from None
if bg: try: bits.append(f"\033[{_interpret_color(bg, 10)}m") except KeyError: raise TypeError(f"Unknown color {bg!r}") from None
if bold is not None: bits.append(f"\033[{1 if bold else 22}m") if dim is not None: bits.append(f"\033[{2 if dim else 22}m") if underline is not None: bits.append(f"\033[{4 if underline else 24}m") if overline is not None: bits.append(f"\033[{53 if overline else 55}m") if italic is not None: bits.append(f"\033[{3 if italic else 23}m") if blink is not None: bits.append(f"\033[{5 if blink else 25}m") if reverse is not None: bits.append(f"\033[{7 if reverse else 27}m") if strikethrough is not None: bits.append(f"\033[{9 if strikethrough else 29}m") bits.append(text) if reset: bits.append(_ansi_reset_all) return "".join(bits)
def unstyle(text: str) -> str: """Removes ANSI styling information from a string. Usually it's not necessary to use this function as Click's echo function will automatically remove styling if necessary.
.. versionadded:: 2.0
:param text: the text to remove style information from. """ return strip_ansi(text)
def secho( message: t.Any | None = None, file: t.IO[t.AnyStr] | None = None, nl: bool = True, err: bool = False, color: bool | None = None, **styles: t.Any,) -> None: """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same::
click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green'))
All keyword arguments are forwarded to the underlying functions depending on which one they go with.
Non-string types will be converted to :class:`str`. However, :class:`bytes` are passed directly to :meth:`echo` without applying style. If you want to style bytes that represent text, call :meth:`bytes.decode` first.
.. versionchanged:: 8.0 A non-string ``message`` is converted to a string. Bytes are passed through without style applied.
.. versionadded:: 2.0 """ if message is not None and not isinstance(message, (bytes, bytearray)): message = style(message, **styles)
return echo(message, file=file, nl=nl, err=err, color=color)
@t.overloaddef edit( text: bytes | bytearray, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = False, extension: str = ".txt",) -> bytes | None: ...
@t.overloaddef edit( text: str, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt",) -> str | None: ...
@t.overloaddef edit( text: None = None, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", filename: str | cabc.Iterable[str] | None = None,) -> None: ...
def edit( text: str | bytes | bytearray | None = None, editor: str | None = None, env: cabc.Mapping[str, str] | None = None, require_save: bool = True, extension: str = ".txt", filename: str | cabc.Iterable[str] | None = None,) -> str | bytes | bytearray | None: r"""Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, `None` is returned. In case a file is edited directly the return value is always `None` and `require_save` and `extension` are ignored.
If the editor cannot be opened a :exc:`UsageError` is raised.
Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have ``\n`` as newline markers.
:param text: the text to edit. :param editor: optionally the editor to use. Defaults to automatic detection. :param env: environment variables to forward to the editor. :param require_save: if this is true, then not saving in the editor will make the return value become `None`. :param extension: the extension to tell the editor about. This defaults to `.txt` but changing this might change syntax highlighting. :param filename: if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. If the editor supports editing multiple files at once, a sequence of files may be passed as well. Invoke `click.file` once per file instead if multiple files cannot be managed at once or editing the files serially is desired.
.. versionchanged:: 8.2.0 ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str`` if the ``editor`` supports editing multiple files at once.
""" from ._termui_impl import Editor
ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
if filename is None: return ed.edit(text)
if isinstance(filename, str): filename = (filename,)
ed.edit_files(filenames=filename) return None
def launch(url: str, wait: bool = False, locate: bool = 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.
Examples::
click.launch('https://click.palletsprojects.com/') click.launch('/my/downloaded/file', locate=True)
.. versionadded:: 2.0
:param url: URL or filename of the thing to launch. :param wait: 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. :param locate: 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. """ from ._termui_impl import open_url
return open_url(url, wait=wait, locate=locate)
# If this is provided, getchar() calls into this instead. This is used# for unittesting purposes._getchar: t.Callable[[bool], str] | None = None
def getchar(echo: bool = False) -> str: """Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.
Note that this will always read from the terminal, even if something is piped into the standard input.
Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers.
.. versionadded:: 2.0
:param echo: if set to `True`, the character read will also show up on the terminal. The default is to not show it. """ global _getchar
if _getchar is None: from ._termui_impl import getchar as f
_getchar = f
return _getchar(echo)
def raw_terminal() -> AbstractContextManager[int]: from ._termui_impl import raw_terminal as f
return f()
def pause(info: str | None = None, err: bool = False) -> None: """This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch "pause" command. If the program is not run through a terminal, this command will instead do nothing.
.. versionadded:: 2.0
.. versionadded:: 4.0 Added the `err` parameter.
:param info: The message to print before pausing. Defaults to ``"Press any key to continue..."``. :param err: if set to message goes to ``stderr`` instead of ``stdout``, the same as with echo. """ if not isatty(sys.stdin) or not isatty(sys.stdout): return
if info is None: info = _("Press any key to continue...")
try: if info: echo(info, nl=False, err=err) try: getchar() except (KeyboardInterrupt, EOFError): pass finally: if info: echo(err=err)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574from __future__ import annotations
import collections.abc as cabcimport contextlibimport ioimport osimport shleximport sysimport tempfileimport typing as tfrom types import TracebackType
from . import _compatfrom . import formattingfrom . import termuifrom . import utilsfrom ._compat import _find_binary_reader
if t.TYPE_CHECKING: from _typeshed import ReadableBuffer
from .core import Command
class EchoingStdin: def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None: self._input = input self._output = output self._paused = False
def __getattr__(self, x: str) -> t.Any: return getattr(self._input, x)
def _echo(self, rv: bytes) -> bytes: if not self._paused: self._output.write(rv)
return rv
def read(self, n: int = -1) -> bytes: return self._echo(self._input.read(n))
def read1(self, n: int = -1) -> bytes: return self._echo(self._input.read1(n)) # type: ignore
def readline(self, n: int = -1) -> bytes: return self._echo(self._input.readline(n))
def readlines(self) -> list[bytes]: return [self._echo(x) for x in self._input.readlines()]
def __iter__(self) -> cabc.Iterator[bytes]: return iter(self._echo(x) for x in self._input)
def __repr__(self) -> str: return repr(self._input)
@contextlib.contextmanagerdef _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]: if stream is None: yield else: stream._paused = True yield stream._paused = False
class BytesIOCopy(io.BytesIO): """Patch ``io.BytesIO`` to let the written stream be copied to another.
.. versionadded:: 8.2 """
def __init__(self, copy_to: io.BytesIO) -> None: super().__init__() self.copy_to = copy_to
def flush(self) -> None: super().flush() self.copy_to.flush()
def write(self, b: ReadableBuffer) -> int: self.copy_to.write(b) return super().write(b)
class StreamMixer: """Mixes `<stdout>` and `<stderr>` streams.
The result is available in the ``output`` attribute.
.. versionadded:: 8.2 """
def __init__(self) -> None: self.output: io.BytesIO = io.BytesIO() self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output) self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)
class _NamedTextIOWrapper(io.TextIOWrapper): def __init__( self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any ) -> None: super().__init__(buffer, **kwargs) self._name = name self._mode = mode
def close(self) -> None: """ The buffer this object contains belongs to some other object, so prevent the default __del__ implementation from closing that buffer.
.. versionadded:: 8.3.2 """ ...
@property def name(self) -> str: return self._name
@property def mode(self) -> str: return self._mode
def make_input_stream( input: str | bytes | t.IO[t.Any] | None, charset: str) -> t.BinaryIO: # Is already an input stream. if hasattr(input, "read"): rv = _find_binary_reader(t.cast("t.IO[t.Any]", input))
if rv is not None: return rv
raise TypeError("Could not find binary reader for input stream.")
if input is None: input = b"" elif isinstance(input, str): input = input.encode(charset)
return io.BytesIO(input)
class Result: """Holds the captured result of an invoked CLI script.
:param runner: The runner that created the result :param stdout_bytes: The standard output as bytes. :param stderr_bytes: The standard error as bytes. :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would see it in its terminal. :param return_value: The value returned from the invoked command. :param exit_code: The exit code as integer. :param exception: The exception that happened if one did. :param exc_info: Exception information (exception type, exception instance, traceback type).
.. versionchanged:: 8.2 ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and ``mix_stderr`` has been removed.
.. versionadded:: 8.0 Added ``return_value``. """
def __init__( self, runner: CliRunner, stdout_bytes: bytes, stderr_bytes: bytes, output_bytes: bytes, return_value: t.Any, exit_code: int, exception: BaseException | None, exc_info: tuple[type[BaseException], BaseException, TracebackType] | None = None, ): self.runner = runner self.stdout_bytes = stdout_bytes self.stderr_bytes = stderr_bytes self.output_bytes = output_bytes self.return_value = return_value self.exit_code = exit_code self.exception = exception self.exc_info = exc_info
@property def output(self) -> str: """The terminal output as unicode string, as the user would see it.
.. versionchanged:: 8.2 No longer a proxy for ``self.stdout``. Now has its own independent stream that is mixing `<stdout>` and `<stderr>`, in the order they were written. """ return self.output_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" )
@property def stdout(self) -> str: """The standard output as unicode string.""" return self.stdout_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" )
@property def stderr(self) -> str: """The standard error as unicode string.
.. versionchanged:: 8.2 No longer raise an exception, always returns the `<stderr>` string. """ return self.stderr_bytes.decode(self.runner.charset, "replace").replace( "\r\n", "\n" )
def __repr__(self) -> str: exc_str = repr(self.exception) if self.exception else "okay" return f"<{type(self).__name__} {exc_str}>"
class CliRunner: """The CLI runner provides functionality to invoke a Click command line script for unittesting purposes in a isolated environment. This only works in single-threaded systems without any concurrency as it changes the global interpreter state.
:param charset: the character set for the input and output data. :param env: a dictionary with environment variables for overriding. :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes to `<stdout>`. This is useful for showing examples in some circumstances. Note that regular prompts will automatically echo the input. :param catch_exceptions: Whether to catch any exceptions other than ``SystemExit`` when running :meth:`~CliRunner.invoke`.
.. versionchanged:: 8.2 Added the ``catch_exceptions`` parameter.
.. versionchanged:: 8.2 ``mix_stderr`` parameter has been removed. """
def __init__( self, charset: str = "utf-8", env: cabc.Mapping[str, str | None] | None = None, echo_stdin: bool = False, catch_exceptions: bool = True, ) -> None: self.charset = charset self.env: cabc.Mapping[str, str | None] = env or {} self.echo_stdin = echo_stdin self.catch_exceptions = catch_exceptions
def get_default_prog_name(self, cli: Command) -> str: """Given a command object it will return the default program name for it. The default is the `name` attribute or ``"root"`` if not set. """ return cli.name or "root"
def make_env( self, overrides: cabc.Mapping[str, str | None] | None = None ) -> cabc.Mapping[str, str | None]: """Returns the environment overrides for invoking a script.""" rv = dict(self.env) if overrides: rv.update(overrides) return rv
@contextlib.contextmanager def isolation( self, input: str | bytes | t.IO[t.Any] | None = None, env: cabc.Mapping[str, str | None] | None = None, color: bool = False, ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]: """A context manager that sets up the isolation for invoking of a command line tool. This sets up `<stdin>` with the given input data and `os.environ` with the overrides from the given dictionary. This also rebinds some internals in Click to be mocked (like the prompt functionality).
This is automatically done in the :meth:`invoke` method.
:param input: the input stream to put into `sys.stdin`. :param env: the environment overrides as dictionary. :param color: whether the output should contain color codes. The application can still override this explicitly.
.. versionadded:: 8.2 An additional output stream is returned, which is a mix of `<stdout>` and `<stderr>` streams.
.. versionchanged:: 8.2 Always returns the `<stderr>` stream.
.. versionchanged:: 8.0 `<stderr>` is opened with ``errors="backslashreplace"`` instead of the default ``"strict"``.
.. versionchanged:: 4.0 Added the ``color`` parameter. """ bytes_input = make_input_stream(input, self.charset) echo_input = None
old_stdin = sys.stdin old_stdout = sys.stdout old_stderr = sys.stderr old_forced_width = formatting.FORCED_WIDTH formatting.FORCED_WIDTH = 80
env = self.make_env(env)
stream_mixer = StreamMixer()
if self.echo_stdin: bytes_input = echo_input = t.cast( t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout) )
sys.stdin = text_input = _NamedTextIOWrapper( bytes_input, encoding=self.charset, name="<stdin>", mode="r" )
if self.echo_stdin: # Force unbuffered reads, otherwise TextIOWrapper reads a # large chunk which is echoed early. text_input._CHUNK_SIZE = 1 # type: ignore
sys.stdout = _NamedTextIOWrapper( stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w" )
sys.stderr = _NamedTextIOWrapper( stream_mixer.stderr, encoding=self.charset, name="<stderr>", mode="w", errors="backslashreplace", )
@_pause_echo(echo_input) # type: ignore def visible_input(prompt: str | None = None) -> str: sys.stdout.write(prompt or "") try: val = next(text_input).rstrip("\r\n") except StopIteration as e: raise EOFError() from e sys.stdout.write(f"{val}\n") sys.stdout.flush() return val
@_pause_echo(echo_input) # type: ignore def hidden_input(prompt: str | None = None) -> str: sys.stdout.write(f"{prompt or ''}\n") sys.stdout.flush() try: return next(text_input).rstrip("\r\n") except StopIteration as e: raise EOFError() from e
@_pause_echo(echo_input) # type: ignore def _getchar(echo: bool) -> str: char = sys.stdin.read(1)
if echo: sys.stdout.write(char)
sys.stdout.flush() return char
default_color = color
def should_strip_ansi( stream: t.IO[t.Any] | None = None, color: bool | None = None ) -> bool: if color is None: return not default_color return not color
old_visible_prompt_func = termui.visible_prompt_func old_hidden_prompt_func = termui.hidden_prompt_func old__getchar_func = termui._getchar old_should_strip_ansi = utils.should_strip_ansi # type: ignore old__compat_should_strip_ansi = _compat.should_strip_ansi termui.visible_prompt_func = visible_input termui.hidden_prompt_func = hidden_input termui._getchar = _getchar utils.should_strip_ansi = should_strip_ansi # type: ignore _compat.should_strip_ansi = should_strip_ansi
old_env = {} try: for key, value in env.items(): old_env[key] = os.environ.get(key) if value is None: try: del os.environ[key] except Exception: pass else: os.environ[key] = value yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output) finally: for key, value in old_env.items(): if value is None: try: del os.environ[key] except Exception: pass else: os.environ[key] = value sys.stdout = old_stdout sys.stderr = old_stderr sys.stdin = old_stdin termui.visible_prompt_func = old_visible_prompt_func termui.hidden_prompt_func = old_hidden_prompt_func termui._getchar = old__getchar_func utils.should_strip_ansi = old_should_strip_ansi # type: ignore _compat.should_strip_ansi = old__compat_should_strip_ansi formatting.FORCED_WIDTH = old_forced_width
def invoke( self, cli: Command, args: str | cabc.Sequence[str] | None = None, input: str | bytes | t.IO[t.Any] | None = None, env: cabc.Mapping[str, str | None] | None = None, catch_exceptions: bool | None = None, color: bool = False, **extra: t.Any, ) -> Result: """Invokes a command in an isolated environment. The arguments are forwarded directly to the command line script, the `extra` keyword arguments are passed to the :meth:`~clickpkg.Command.main` function of the command.
This returns a :class:`Result` object.
:param cli: the command to invoke :param args: the arguments to invoke. It may be given as an iterable or a string. When given as string it will be interpreted as a Unix shell command. More details at :func:`shlex.split`. :param input: the input data for `sys.stdin`. :param env: the environment overrides. :param catch_exceptions: Whether to catch any other exceptions than ``SystemExit``. If :data:`None`, the value from :class:`CliRunner` is used. :param extra: the keyword arguments to pass to :meth:`main`. :param color: whether the output should contain color codes. The application can still override this explicitly.
.. versionadded:: 8.2 The result object has the ``output_bytes`` attribute with the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would see it in its terminal.
.. versionchanged:: 8.2 The result object always returns the ``stderr_bytes`` stream.
.. versionchanged:: 8.0 The result object has the ``return_value`` attribute with the value returned from the invoked command.
.. versionchanged:: 4.0 Added the ``color`` parameter.
.. versionchanged:: 3.0 Added the ``catch_exceptions`` parameter.
.. versionchanged:: 3.0 The result object has the ``exc_info`` attribute with the traceback if available. """ exc_info = None if catch_exceptions is None: catch_exceptions = self.catch_exceptions
with self.isolation(input=input, env=env, color=color) as outstreams: return_value = None exception: BaseException | None = None exit_code = 0
if isinstance(args, str): args = shlex.split(args)
try: prog_name = extra.pop("prog_name") except KeyError: prog_name = self.get_default_prog_name(cli)
try: return_value = cli.main(args=args or (), prog_name=prog_name, **extra) except SystemExit as e: exc_info = sys.exc_info() e_code = t.cast("int | t.Any | None", e.code)
if e_code is None: e_code = 0
if e_code != 0: exception = e
if not isinstance(e_code, int): sys.stdout.write(str(e_code)) sys.stdout.write("\n") e_code = 1
exit_code = e_code
except Exception as e: if not catch_exceptions: raise exception = e exit_code = 1 exc_info = sys.exc_info() finally: sys.stdout.flush() sys.stderr.flush() stdout = outstreams[0].getvalue() stderr = outstreams[1].getvalue() output = outstreams[2].getvalue()
return Result( runner=self, stdout_bytes=stdout, stderr_bytes=stderr, output_bytes=output, return_value=return_value, exit_code=exit_code, exception=exception, exc_info=exc_info, # type: ignore )
@contextlib.contextmanager def isolated_filesystem( self, temp_dir: str | os.PathLike[str] | None = None ) -> cabc.Iterator[str]: """A context manager that creates a temporary directory and changes the current working directory to it. This isolates tests that affect the contents of the CWD to prevent them from interfering with each other.
:param temp_dir: Create the temporary directory under this directory. If given, the created directory is not removed when exiting.
.. versionchanged:: 8.0 Added the ``temp_dir`` parameter. """ cwd = os.getcwd() dt = tempfile.mkdtemp(dir=temp_dir) os.chdir(dt)
try: yield dt finally: os.chdir(cwd)
if temp_dir is None: import shutil
try: shutil.rmtree(dt) except OSError: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209from __future__ import annotations
import collections.abc as cabcimport enumimport osimport statimport sysimport typing as tfrom datetime import datetimefrom gettext import gettext as _from gettext import ngettext
from ._compat import _get_argv_encodingfrom ._compat import open_streamfrom .exceptions import BadParameterfrom .utils import format_filenamefrom .utils import LazyFilefrom .utils import safecall
if t.TYPE_CHECKING: import typing_extensions as te
from .core import Context from .core import Parameter from .shell_completion import CompletionItem
ParamTypeValue = t.TypeVar("ParamTypeValue")
class ParamType: """Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type.
To implement a custom type, subclass and implement at least the following:
- The :attr:`name` class attribute must be set. - Calling an instance of the type with ``None`` must return ``None``. This is already implemented by default. - :meth:`convert` must convert string values to the correct type. - :meth:`convert` must accept values that are already the correct type. - It must be able to convert a value if the ``ctx`` and ``param`` arguments are ``None``. This can occur when converting prompt input. """
is_composite: t.ClassVar[bool] = False arity: t.ClassVar[int] = 1
#: the descriptive name of this type name: str
#: if a list of this type is expected and the value is pulled from a #: string environment variable, this is what splits it up. `None` #: means any whitespace. For all parameters the general rule is that #: whitespace splits them up. The exception are paths and files which #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on #: Windows). envvar_list_splitter: t.ClassVar[str | None] = None
def to_info_dict(self) -> dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation.
Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure.
.. versionadded:: 8.0 """ # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0]
# Custom subclasses might not remember to set a name. if hasattr(self, "name"): name = self.name else: name = param_type
return {"param_type": param_type, "name": name}
def __call__( self, value: t.Any, param: Parameter | None = None, ctx: Context | None = None, ) -> t.Any: if value is not None: return self.convert(value, param, ctx)
def get_metavar(self, param: Parameter, ctx: Context) -> str | None: """Returns the metavar default for this param if it provides one."""
def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None: """Optionally might return extra information about a missing parameter.
.. versionadded:: 2.0 """
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: """Convert the value to the correct type. This is not called if the value is ``None`` (the missing value).
This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.
The ``param`` and ``ctx`` arguments may be ``None`` in certain situations, such as when converting prompt input.
If the value cannot be converted, call :meth:`fail` with a descriptive message.
:param value: The value to convert. :param param: The parameter that is using this type to convert its value. May be ``None``. :param ctx: The current context that arrived at this value. May be ``None``. """ return value
def split_envvar_value(self, rv: str) -> cabc.Sequence[str]: """Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter.
If the splitter is set to `None`, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included. """ return (rv or "").split(self.envvar_list_splitter)
def fail( self, message: str, param: Parameter | None = None, ctx: Context | None = None, ) -> t.NoReturn: """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param)
def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Return a list of :class:`~click.shell_completion.CompletionItem` objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.
:param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty.
.. versionadded:: 8.0 """ return []
class CompositeParamType(ParamType): is_composite = True
@property def arity(self) -> int: # type: ignore raise NotImplementedError()
class FuncParamType(ParamType): def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None: self.name: str = func.__name__ self.func = func
def to_info_dict(self) -> dict[str, t.Any]: info_dict = super().to_info_dict() info_dict["func"] = self.func return info_dict
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: try: return self.func(value) except ValueError: try: value = str(value) except UnicodeError: value = value.decode("utf-8", "replace")
self.fail(value, param, ctx)
class UnprocessedParamType(ParamType): name = "text"
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: return value
def __repr__(self) -> str: return "UNPROCESSED"
class StringParamType(ParamType): name = "text"
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: if isinstance(value, bytes): enc = _get_argv_encoding() try: value = value.decode(enc) except UnicodeError: fs_enc = sys.getfilesystemencoding() if fs_enc != enc: try: value = value.decode(fs_enc) except UnicodeError: value = value.decode("utf-8", "replace") else: value = value.decode("utf-8", "replace") return value return str(value)
def __repr__(self) -> str: return "STRING"
class Choice(ParamType, t.Generic[ParamTypeValue]): """The choice type allows a value to be checked against a fixed set of supported values.
You may pass any iterable value which will be converted to a tuple and thus will only be iterated once.
The resulting value will always be one of the originally passed choices. See :meth:`normalize_choice` for more info on the mapping of strings to choices. See :ref:`choice-opts` for an example.
:param case_sensitive: Set to false to make choices case insensitive. Defaults to true.
.. versionchanged:: 8.2.0 Non-``str`` ``choices`` are now supported. It can additionally be any iterable. Before you were not recommended to pass anything but a list or tuple.
.. versionadded:: 8.2.0 Choice normalization can be overridden via :meth:`normalize_choice`. """
name = "choice"
def __init__( self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True ) -> None: self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices) self.case_sensitive = case_sensitive
def to_info_dict(self) -> dict[str, t.Any]: info_dict = super().to_info_dict() info_dict["choices"] = self.choices info_dict["case_sensitive"] = self.case_sensitive return info_dict
def _normalized_mapping( self, ctx: Context | None = None ) -> cabc.Mapping[ParamTypeValue, str]: """ Returns mapping where keys are the original choices and the values are the normalized values that are accepted via the command line.
This is a simple wrapper around :meth:`normalize_choice`, use that instead which is supported. """ return { choice: self.normalize_choice( choice=choice, ctx=ctx, ) for choice in self.choices }
def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str: """ Normalize a choice value, used to map a passed string to a choice. Each choice must have a unique normalized value.
By default uses :meth:`Context.token_normalize_func` and if not case sensitive, convert it to a casefolded value.
.. versionadded:: 8.2.0 """ normed_value = choice.name if isinstance(choice, enum.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
def get_metavar(self, param: Parameter, ctx: Context) -> str | None: if param.param_type_name == "option" and not param.show_choices: # type: ignore choice_metavars = [ convert_type(type(choice)).name.upper() for choice in self.choices ] choices_str = "|".join([*dict.fromkeys(choice_metavars)]) else: choices_str = "|".join( [str(i) for i in self._normalized_mapping(ctx=ctx).values()] )
# Use curly braces to indicate a required argument. if param.required and param.param_type_name == "argument": return f"{{{choices_str}}}"
# Use square braces to indicate an option or optional argument. return f"[{choices_str}]"
def get_missing_message(self, param: Parameter, ctx: Context | None) -> str: """ Message shown when no choice is passed.
.. versionchanged:: 8.2.0 Added ``ctx`` argument. """ return _("Choose from:\n\t{choices}").format( choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values()) )
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> ParamTypeValue: """ For a given value from the parser, normalize it and find its matching normalized value in the list of choices. Then return the matched "original" choice. """ normed_value = self.normalize_choice(choice=value, ctx=ctx) normalized_mapping = self._normalized_mapping(ctx=ctx)
try: return next( original for original, normalized in normalized_mapping.items() if normalized == normed_value ) except StopIteration: self.fail( self.get_invalid_choice_message(value=value, ctx=ctx), param=param, ctx=ctx, )
def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str: """Get the error message when the given choice is invalid.
:param value: The invalid value.
.. versionadded:: 8.2 """ choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values())) return ngettext( "{value!r} is not {choice}.", "{value!r} is not one of {choices}.", len(self.choices), ).format(value=value, choice=choices_str, choices=choices_str)
def __repr__(self) -> str: return f"Choice({list(self.choices)})"
def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Complete choices that start with the incomplete value.
:param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty.
.. versionadded:: 8.0 """ from click.shell_completion import CompletionItem
str_choices = map(str, self.choices)
if self.case_sensitive: matched = (c for c in str_choices if c.startswith(incomplete)) else: incomplete = incomplete.lower() matched = (c for c in str_choices if c.lower().startswith(incomplete))
return [CompletionItem(c) for c in matched]
class DateTime(ParamType): """The DateTime type converts date strings into `datetime` objects.
The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats.
When specifying *DateTime* formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results.
The format strings are processed using ``datetime.strptime``, and this consequently defines the format strings which are allowed.
Parsing is tried using each format, in order, and the first format which parses successfully is used.
:param formats: A list or tuple of date format strings, in the order in which they should be tried. Defaults to ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``, ``'%Y-%m-%d %H:%M:%S'``. """
name = "datetime"
def __init__(self, formats: cabc.Sequence[str] | None = None): self.formats: cabc.Sequence[str] = formats or [ "%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", ]
def to_info_dict(self) -> dict[str, t.Any]: info_dict = super().to_info_dict() info_dict["formats"] = self.formats return info_dict
def get_metavar(self, param: Parameter, ctx: Context) -> str | None: return f"[{'|'.join(self.formats)}]"
def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None: try: return datetime.strptime(value, format) except ValueError: return None
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: if isinstance(value, datetime): return value
for format in self.formats: converted = self._try_to_convert_date(value, format)
if converted is not None: return converted
formats_str = ", ".join(map(repr, self.formats)) self.fail( ngettext( "{value!r} does not match the format {format}.", "{value!r} does not match the formats {formats}.", len(self.formats), ).format(value=value, format=formats_str, formats=formats_str), param, ctx, )
def __repr__(self) -> str: return "DateTime"
class _NumberParamTypeBase(ParamType): _number_class: t.ClassVar[type[t.Any]]
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: try: return self._number_class(value) except ValueError: self.fail( _("{value!r} is not a valid {number_type}.").format( value=value, number_type=self.name ), param, ctx, )
class _NumberRangeBase(_NumberParamTypeBase): def __init__( self, min: float | None = None, max: float | None = None, min_open: bool = False, max_open: bool = False, clamp: bool = False, ) -> None: self.min = min self.max = max self.min_open = min_open self.max_open = max_open self.clamp = clamp
def to_info_dict(self) -> dict[str, t.Any]: info_dict = super().to_info_dict() info_dict.update( min=self.min, max=self.max, min_open=self.min_open, max_open=self.max_open, clamp=self.clamp, ) return info_dict
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: import operator
rv = super().convert(value, param, ctx) lt_min: bool = self.min is not None and ( operator.le if self.min_open else operator.lt )(rv, self.min) gt_max: bool = self.max is not None and ( operator.ge if self.max_open else operator.gt )(rv, self.max)
if self.clamp: if lt_min: return self._clamp(self.min, 1, self.min_open) # type: ignore
if gt_max: return self._clamp(self.max, -1, self.max_open) # type: ignore
if lt_min or gt_max: self.fail( _("{value} is not in the range {range}.").format( value=rv, range=self._describe_range() ), param, ctx, )
return rv
def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: """Find the valid value to clamp to bound in the given direction.
:param bound: The boundary value. :param dir: 1 or -1 indicating the direction to move. :param open: If true, the range does not include the bound. """ raise NotImplementedError
def _describe_range(self) -> str: """Describe the range for use in help text.""" if self.min is None: op = "<" if self.max_open else "<=" return f"x{op}{self.max}"
if self.max is None: op = ">" if self.min_open else ">=" return f"x{op}{self.min}"
lop = "<" if self.min_open else "<=" rop = "<" if self.max_open else "<=" return f"{self.min}{lop}x{rop}{self.max}"
def __repr__(self) -> str: clamp = " clamped" if self.clamp else "" return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
class IntParamType(_NumberParamTypeBase): name = "integer" _number_class = int
def __repr__(self) -> str: return "INT"
class IntRange(_NumberRangeBase, IntParamType): """Restrict an :data:`click.INT` value to a range of accepted values. See :ref:`ranges`.
If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range.
If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing.
.. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters. """
name = "integer range"
def _clamp( # type: ignore self, bound: int, dir: t.Literal[1, -1], open: bool ) -> int: if not open: return bound
return bound + dir
class FloatParamType(_NumberParamTypeBase): name = "float" _number_class = float
def __repr__(self) -> str: return "FLOAT"
class FloatRange(_NumberRangeBase, FloatParamType): """Restrict a :data:`click.FLOAT` value to a range of accepted values. See :ref:`ranges`.
If ``min`` or ``max`` are not passed, any value is accepted in that direction. If ``min_open`` or ``max_open`` are enabled, the corresponding boundary is not included in the range.
If ``clamp`` is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is marked ``open``.
.. versionchanged:: 8.0 Added the ``min_open`` and ``max_open`` parameters. """
name = "float range"
def __init__( self, min: float | None = None, max: float | None = None, min_open: bool = False, max_open: bool = False, clamp: bool = False, ) -> None: super().__init__( min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp )
if (min_open or max_open) and clamp: raise TypeError("Clamping is not supported for open bounds.")
def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float: if not open: return bound
# Could use math.nextafter here, but clamping an # open float range doesn't seem to be particularly useful. It's # left up to the user to write a callback to do it if needed. raise RuntimeError("Clamping is not supported for open bounds.")
class BoolParamType(ParamType): name = "boolean"
bool_states: dict[str, bool] = { "1": True, "0": False, "yes": True, "no": False, "true": True, "false": False, "on": True, "off": False, "t": True, "f": False, "y": True, "n": False, # Absence of value is considered False. "": False, } """A mapping of string values to boolean states.
Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES` and extends it.
.. caution:: String values are lower-cased, as the ``str_to_bool`` comparison function below is case-insensitive.
.. warning:: The mapping is not exhaustive, and does not cover all possible boolean strings representations. It will remains as it is to avoid endless bikeshedding.
Future work my be considered to make this mapping user-configurable from public API. """
@staticmethod def str_to_bool(value: str | bool) -> bool | None: """Convert a string to a boolean value.
If the value is already a boolean, it is returned as-is. If the value is a string, it is stripped of whitespaces and lower-cased, then checked against the known boolean states pre-defined in the `BoolParamType.bool_states` mapping above.
Returns `None` if the value does not match any known boolean state. """ if isinstance(value, bool): return value return BoolParamType.bool_states.get(value.strip().lower())
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> bool: normalized = self.str_to_bool(value) if normalized is None: self.fail( _( "{value!r} is not a valid boolean. Recognized values: {states}" ).format(value=value, states=", ".join(sorted(self.bool_states))), param, ctx, ) return normalized
def __repr__(self) -> str: return "BOOL"
class UUIDParameterType(ParamType): name = "uuid"
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: import uuid
if isinstance(value, uuid.UUID): return value
value = value.strip()
try: return uuid.UUID(value) except ValueError: self.fail( _("{value!r} is not a valid UUID.").format(value=value), param, ctx )
def __repr__(self) -> str: return "UUID"
class File(ParamType): """Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working).
Files can be opened for reading or writing. The special value ``-`` indicates stdin or stdout depending on the mode.
By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding.
The `lazy` flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, `lazy` otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed.
Files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.
See :ref:`file-args` for more information.
.. versionchanged:: 2.0 Added the ``atomic`` parameter. """
name = "filename" envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
def __init__( self, mode: str = "r", encoding: str | None = None, errors: str | None = "strict", lazy: bool | None = None, atomic: bool = False, ) -> None: self.mode = mode self.encoding = encoding self.errors = errors self.lazy = lazy self.atomic = atomic
def to_info_dict(self) -> dict[str, t.Any]: info_dict = super().to_info_dict() info_dict.update(mode=self.mode, encoding=self.encoding) return info_dict
def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool: if self.lazy is not None: return self.lazy if os.fspath(value) == "-": return False elif "w" in self.mode: return True return False
def convert( self, value: str | os.PathLike[str] | t.IO[t.Any], param: Parameter | None, ctx: Context | None, ) -> t.IO[t.Any]: if _is_file_like(value): return value
value = t.cast("str | os.PathLike[str]", value)
try: lazy = self.resolve_lazy_flag(value)
if lazy: lf = LazyFile( value, self.mode, self.encoding, self.errors, atomic=self.atomic )
if ctx is not None: ctx.call_on_close(lf.close_intelligently)
return t.cast("t.IO[t.Any]", lf)
f, should_close = open_stream( value, self.mode, self.encoding, self.errors, atomic=self.atomic )
# If a context is provided, we automatically close the file # at the end of the context execution (or flush out). If a # context does not exist, it's the caller's responsibility to # properly close the file. This for instance happens when the # type is used with prompts. if ctx is not None: if should_close: ctx.call_on_close(safecall(f.close)) else: ctx.call_on_close(safecall(f.flush))
return f except OSError as e: self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)
def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Return a special completion marker that tells the completion system to use the shell to provide file path completions.
:param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty.
.. versionadded:: 8.0 """ from click.shell_completion import CompletionItem
return [CompletionItem(incomplete, type="file")]
def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]: return hasattr(value, "read") or hasattr(value, "write")
class Path(ParamType): """The ``Path`` type is similar to the :class:`File` type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions.
:param exists: The file or directory needs to exist for the value to be valid. If this is not set to ``True``, and the file does not exist, then all further checks are silently skipped. :param file_okay: Allow a file as a value. :param dir_okay: Allow a directory as a value. :param readable: if true, a readable check is performed. :param writable: if true, a writable check is performed. :param executable: if true, an executable check is performed. :param resolve_path: Make the value absolute and resolve any symlinks. A ``~`` is not expanded, as this is supposed to be done by the shell only. :param allow_dash: Allow a single dash as a value, which indicates a standard stream (but does not open it). Use :func:`~click.open_file` to handle opening this value. :param path_type: Convert the incoming path value to this type. If ``None``, keep Python's default, which is ``str``. Useful to convert to :class:`pathlib.Path`.
.. versionchanged:: 8.1 Added the ``executable`` parameter.
.. versionchanged:: 8.0 Allow passing ``path_type=pathlib.Path``.
.. versionchanged:: 6.0 Added the ``allow_dash`` parameter. """
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
def __init__( self, 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: type[t.Any] | None = None, executable: bool = False, ): self.exists = exists self.file_okay = file_okay self.dir_okay = dir_okay self.readable = readable self.writable = writable self.executable = executable self.resolve_path = resolve_path self.allow_dash = allow_dash self.type = path_type
if self.file_okay and not self.dir_okay: self.name: str = _("file") elif self.dir_okay and not self.file_okay: self.name = _("directory") else: self.name = _("path")
def to_info_dict(self) -> dict[str, t.Any]: info_dict = super().to_info_dict() info_dict.update( exists=self.exists, file_okay=self.file_okay, dir_okay=self.dir_okay, writable=self.writable, readable=self.readable, allow_dash=self.allow_dash, ) return info_dict
def coerce_path_result( self, value: str | os.PathLike[str] ) -> str | bytes | os.PathLike[str]: if self.type is not None and not isinstance(value, self.type): if self.type is str: return os.fsdecode(value) elif self.type is bytes: return os.fsencode(value) else: return t.cast("os.PathLike[str]", self.type(value))
return value
def convert( self, value: str | os.PathLike[str], param: Parameter | None, ctx: Context | None, ) -> str | bytes | os.PathLike[str]: rv = value
is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")
if not is_dash: if self.resolve_path: rv = os.path.realpath(rv)
try: st = os.stat(rv) except OSError: if not self.exists: return self.coerce_path_result(rv) self.fail( _("{name} {filename!r} does not exist.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, )
if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( _("{name} {filename!r} is a file.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( _("{name} {filename!r} is a directory.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, )
if self.readable and not os.access(rv, os.R_OK): self.fail( _("{name} {filename!r} is not readable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, )
if self.writable and not os.access(rv, os.W_OK): self.fail( _("{name} {filename!r} is not writable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, )
if self.executable and not os.access(value, os.X_OK): self.fail( _("{name} {filename!r} is not executable.").format( name=self.name.title(), filename=format_filename(value) ), param, ctx, )
return self.coerce_path_result(rv)
def shell_complete( self, ctx: Context, param: Parameter, incomplete: str ) -> list[CompletionItem]: """Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths.
:param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty.
.. versionadded:: 8.0 """ from click.shell_completion import CompletionItem
type = "dir" if self.dir_okay and not self.file_okay else "file" return [CompletionItem(incomplete, type=type)]
class Tuple(CompositeParamType): """The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when `nargs` is set to a fixed count and different types should be used for different items. In this case the :class:`Tuple` type can be used. This type can only be used if `nargs` is set to a fixed number.
For more information see :ref:`tuple-type`.
This can be selected by using a Python tuple literal as a type.
:param types: a list of types that should be used for the tuple items. """
def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None: self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]
def to_info_dict(self) -> dict[str, t.Any]: info_dict = super().to_info_dict() info_dict["types"] = [t.to_info_dict() for t in self.types] return info_dict
@property def name(self) -> str: # type: ignore return f"<{' '.join(ty.name for ty in self.types)}>"
@property def arity(self) -> int: # type: ignore return len(self.types)
def convert( self, value: t.Any, param: Parameter | None, ctx: Context | None ) -> t.Any: len_type = len(self.types) len_value = len(value)
if len_value != len_type: self.fail( ngettext( "{len_type} values are required, but {len_value} was given.", "{len_type} values are required, but {len_value} were given.", len_value, ).format(len_type=len_type, len_value=len_value), param=param, ctx=ctx, )
return tuple( ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False) )
def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType: """Find the most appropriate :class:`ParamType` for the given Python type. If the type isn't provided, it can be inferred from a default value. """ guessed_type = False
if ty is None and default is not None: if isinstance(default, (tuple, list)): # If the default is empty, ty will remain None and will # return STRING. if default: item = default[0]
# A tuple of tuples needs to detect the inner types. # Can't call convert recursively because that would # incorrectly unwind the tuple to a single type. if isinstance(item, (tuple, list)): ty = tuple(map(type, item)) else: ty = type(item) else: ty = type(default)
guessed_type = True
if isinstance(ty, tuple): return Tuple(ty)
if isinstance(ty, ParamType): return ty
if ty is str or ty is None: return STRING
if ty is int: return INT
if ty is float: return FLOAT
if ty is bool: return BOOL
if guessed_type: return STRING
if __debug__: try: if issubclass(ty, ParamType): raise AssertionError( f"Attempted to use an uninstantiated parameter type ({ty})." ) except TypeError: # ty is an instance (correct), so issubclass fails. pass
return FuncParamType(ty)
#: A dummy parameter type that just does nothing. From a user's#: perspective this appears to just be the same as `STRING` but#: internally no string conversion takes place if the input was bytes.#: This is usually useful when working with file paths as they can#: appear in bytes and unicode.#:#: For path related uses the :class:`Path` type is a better choice but#: there are situations where an unprocessed type is useful which is why#: it is is provided.#:#: .. versionadded:: 4.0UNPROCESSED = UnprocessedParamType()
#: A unicode string parameter type which is the implicit default. This#: can also be selected by using ``str`` as type.STRING = StringParamType()
#: An integer parameter. This can also be selected by using ``int`` as#: type.INT = IntParamType()
#: A floating point value parameter. This can also be selected by using#: ``float`` as type.FLOAT = FloatParamType()
#: A boolean parameter. This is the default for boolean flags. This can#: also be selected by using ``bool`` as a type.BOOL = BoolParamType()
#: A UUID parameter.UUID = UUIDParameterType()
class OptionHelpExtra(t.TypedDict, total=False): envvars: tuple[str, ...] default: str range: str required: str123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627from __future__ import annotations
import collections.abc as cabcimport osimport reimport sysimport typing as tfrom functools import update_wrapperfrom types import ModuleTypefrom types import TracebackType
from ._compat import _default_text_stderrfrom ._compat import _default_text_stdoutfrom ._compat import _find_binary_writerfrom ._compat import auto_wrap_for_ansifrom ._compat import binary_streamsfrom ._compat import open_streamfrom ._compat import should_strip_ansifrom ._compat import strip_ansifrom ._compat import text_streamsfrom ._compat import WINfrom .globals import resolve_color_default
if t.TYPE_CHECKING: import typing_extensions as te
P = te.ParamSpec("P")
R = t.TypeVar("R")
def _posixify(name: str) -> str: return "-".join(name.split()).lower()
def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]: """Wraps a function so that it swallows exceptions."""
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None: try: return func(*args, **kwargs) except Exception: pass return None
return update_wrapper(wrapper, func)
def make_str(value: t.Any) -> str: """Converts a value into a valid string.""" if isinstance(value, bytes): try: return value.decode(sys.getfilesystemencoding()) except UnicodeError: return value.decode("utf-8", "replace") return str(value)
def make_default_short_help(help: str, max_length: int = 45) -> str: """Returns a condensed version of help string.""" # Consider only the first paragraph. paragraph_end = help.find("\n\n")
if paragraph_end != -1: help = help[:paragraph_end]
# Collapse newlines, tabs, and spaces. words = help.split()
if not words: return ""
# The first paragraph started with a "no rewrap" marker, ignore it. if words[0] == "\b": words = words[1:]
total_length = 0 last_index = len(words) - 1
for i, word in enumerate(words): total_length += len(word) + (i > 0)
if total_length > max_length: # too long, truncate break
if word[-1] == ".": # sentence end, truncate without "..." return " ".join(words[: i + 1])
if total_length == max_length and i != last_index: break # not at sentence end, truncate with "..." else: return " ".join(words) # no truncation needed
# Account for the length of the suffix. total_length += len("...")
# remove words until the length is short enough while i > 0: total_length -= len(words[i]) + (i > 0)
if total_length <= max_length: break
i -= 1
return " ".join(words[:i]) + "..."
class LazyFile: """A lazy file works like a regular file but it does not fully open the file but it does perform some basic checks early to see if the filename parameter does make sense. This is useful for safely opening files for writing. """
def __init__( self, filename: str | os.PathLike[str], mode: str = "r", encoding: str | None = None, errors: str | None = "strict", atomic: bool = False, ): self.name: str = os.fspath(filename) self.mode = mode self.encoding = encoding self.errors = errors self.atomic = atomic self._f: t.IO[t.Any] | None self.should_close: bool
if self.name == "-": self._f, self.should_close = open_stream(filename, mode, encoding, errors) else: if "r" in mode: # Open and close the file in case we're opening it for # reading so that we can catch at least some errors in # some cases early. open(filename, mode).close() self._f = None self.should_close = True
def __getattr__(self, name: str) -> t.Any: return getattr(self.open(), name)
def __repr__(self) -> str: if self._f is not None: return repr(self._f) return f"<unopened file '{format_filename(self.name)}' {self.mode}>"
def open(self) -> t.IO[t.Any]: """Opens the file if it's not yet open. This call might fail with a :exc:`FileError`. Not handling this error will produce an error that Click shows. """ if self._f is not None: return self._f try: rv, self.should_close = open_stream( self.name, self.mode, self.encoding, self.errors, atomic=self.atomic ) except OSError as e: from .exceptions import FileError
raise FileError(self.name, hint=e.strerror) from e self._f = rv return rv
def close(self) -> None: """Closes the underlying file, no matter what.""" if self._f is not None: self._f.close()
def close_intelligently(self) -> None: """This function only closes the file if it was opened by the lazy file wrapper. For instance this will never close stdin. """ if self.should_close: self.close()
def __enter__(self) -> LazyFile: return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.close_intelligently()
def __iter__(self) -> cabc.Iterator[t.AnyStr]: self.open() return iter(self._f) # type: ignore
class KeepOpenFile: def __init__(self, file: t.IO[t.Any]) -> None: self._file: t.IO[t.Any] = file
def __getattr__(self, name: str) -> t.Any: return getattr(self._file, name)
def __enter__(self) -> KeepOpenFile: return self
def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: pass
def __repr__(self) -> str: return repr(self._file)
def __iter__(self) -> cabc.Iterator[t.AnyStr]: return iter(self._file)
def echo( message: t.Any | None = None, file: t.IO[t.Any] | None = None, nl: bool = True, err: bool = False, color: bool | None = None,) -> None: """Print a message and newline to stdout or a file. This should be used instead of :func:`print` because it provides better support for different data, files, and environments.
Compared to :func:`print`, this does the following:
- Ensures that the output encoding is not misconfigured on Linux. - Supports Unicode in the Windows console. - Supports writing to binary outputs, and supports writing bytes to text outputs. - Supports colors and styles on Windows. - Removes ANSI color and style codes if the output does not look like an interactive terminal. - Always flushes the output.
:param message: The string or bytes to output. Other objects are converted to strings. :param file: The file to write to. Defaults to ``stdout``. :param err: Write to ``stderr`` instead of ``stdout``. :param nl: Print a newline after the message. Enabled by default. :param color: Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal.
.. versionchanged:: 6.0 Support Unicode output on the Windows console. Click does not modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()`` will still not support Unicode.
.. versionchanged:: 4.0 Added the ``color`` parameter.
.. versionadded:: 3.0 Added the ``err`` parameter.
.. versionchanged:: 2.0 Support colors on Windows if colorama is installed. """ if file is None: if err: file = _default_text_stderr() else: file = _default_text_stdout()
# There are no standard streams attached to write to. For example, # pythonw on Windows. if file is None: return
# Convert non bytes/text into the native string type. if message is not None and not isinstance(message, (str, bytes, bytearray)): out: str | bytes | bytearray | None = str(message) else: out = message
if nl: out = out or "" if isinstance(out, str): out += "\n" else: out += b"\n"
if not out: file.flush() return
# If there is a message and the value looks like bytes, we manually # need to find the binary stream and write the message in there. # This is done separately so that most stream types will work as you # would expect. Eg: you can write to StringIO for other cases. if isinstance(out, (bytes, bytearray)): binary_file = _find_binary_writer(file)
if binary_file is not None: file.flush() binary_file.write(out) binary_file.flush() return
# ANSI style code support. For no message or bytes, nothing happens. # When outputting to a file instead of a terminal, strip codes. else: color = resolve_color_default(color)
if should_strip_ansi(file, color): out = strip_ansi(out) elif WIN: if auto_wrap_for_ansi is not None: file = auto_wrap_for_ansi(file, color) # type: ignore elif not color: out = strip_ansi(out)
file.write(out) # type: ignore file.flush()
def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO: """Returns a system stream for byte processing.
:param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` """ opener = binary_streams.get(name) if opener is None: raise TypeError(f"Unknown standard stream '{name}'") return opener()
def get_text_stream( name: t.Literal["stdin", "stdout", "stderr"], encoding: str | None = None, errors: str | None = "strict",) -> t.TextIO: """Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from :func:`get_binary_stream` but it also can take shortcuts for already correctly configured streams.
:param name: the name of the stream to open. Valid names are ``'stdin'``, ``'stdout'`` and ``'stderr'`` :param encoding: overrides the detected default encoding. :param errors: overrides the default error mode. """ opener = text_streams.get(name) if opener is None: raise TypeError(f"Unknown standard stream '{name}'") return opener(encoding, errors)
def open_file( filename: str | os.PathLike[str], mode: str = "r", encoding: str | None = None, errors: str | None = "strict", lazy: bool = False, atomic: bool = False,) -> t.IO[t.Any]: """Open a file, with extra behavior to handle ``'-'`` to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the :class:`~click.File` param type.
If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream:
.. code-block:: python
with open_file(filename) as f: ...
:param filename: The name or Path of the file to open, or ``'-'`` for ``stdin``/``stdout``. :param mode: The mode in which to open the file. :param encoding: The encoding to decode or encode a file opened in text mode. :param errors: The error handling mode. :param lazy: Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again. :param atomic: Write to a temporary file and replace the given file on close.
.. versionadded:: 3.0 """ if lazy: return t.cast( "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic) )
f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
if not should_close: f = t.cast("t.IO[t.Any]", KeepOpenFile(f))
return f
def format_filename( filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], shorten: bool = False,) -> str: """Format a filename as a string for display. Ensures the filename can be displayed by replacing any invalid bytes or surrogate escapes in the name with the replacement character ``�``.
Invalid bytes or surrogate escapes will raise an error when written to a stream with ``errors="strict"``. This will typically happen with ``stdout`` when the locale is something like ``en_GB.UTF-8``.
Many scenarios *are* safe to write surrogates though, due to PEP 538 and PEP 540, including:
- Writing to ``stderr``, which uses ``errors="backslashreplace"``. - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens stdout and stderr with ``errors="surrogateescape"``. - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``. - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``. Python opens stdout and stderr with ``errors="surrogateescape"``.
:param filename: formats a filename for UI display. This will also convert the filename into unicode without failing. :param shorten: this optionally shortens the filename to strip of the path that leads up to it. """ if shorten: filename = os.path.basename(filename) else: filename = os.fspath(filename)
if isinstance(filename, bytes): filename = filename.decode(sys.getfilesystemencoding(), "replace") else: filename = filename.encode("utf-8", "surrogateescape").decode( "utf-8", "replace" )
return filename
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str: r"""Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.
To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be returned:
Mac OS X: ``~/Library/Application Support/Foo Bar`` Mac OS X (POSIX): ``~/.foo-bar`` Unix: ``~/.config/foo-bar`` Unix (POSIX): ``~/.foo-bar`` Windows (roaming): ``C:\Users\<user>\AppData\Roaming\Foo Bar`` Windows (not roaming): ``C:\Users\<user>\AppData\Local\Foo Bar``
.. versionadded:: 2.0
:param app_name: the application name. This should be properly capitalized and can contain whitespace. :param roaming: controls if the folder should be roaming or not on Windows. Has no effect otherwise. :param force_posix: if this is set to `True` then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin's application support folder. """ if WIN: key = "APPDATA" if roaming else "LOCALAPPDATA" folder = os.environ.get(key) if folder is None: folder = os.path.expanduser("~") return os.path.join(folder, app_name) if force_posix: return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}")) if sys.platform == "darwin": return os.path.join( os.path.expanduser("~/Library/Application Support"), app_name ) return os.path.join( os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")), _posixify(app_name), )
class PacifyFlushWrapper: """This wrapper is used to catch and suppress BrokenPipeErrors resulting from ``.flush()`` being called on broken pipe during the shutdown/final-GC of the Python interpreter. Notably ``.flush()`` is always called on ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any other cleanup code, and the case where the underlying file is not a broken pipe, all calls and attributes are proxied. """
def __init__(self, wrapped: t.IO[t.Any]) -> None: self.wrapped = wrapped
def flush(self) -> None: try: self.wrapped.flush() except OSError as e: import errno
if e.errno != errno.EPIPE: raise
def __getattr__(self, attr: str) -> t.Any: return getattr(self.wrapped, attr)
def _detect_program_name( path: str | None = None, _main: ModuleType | None = None) -> str: """Determine the command used to run the program, for use in help text. If a file or entry point was executed, the file name is returned. If ``python -m`` was used to execute a module or package, ``python -m name`` is returned.
This doesn't try to be too precise, the goal is to give a concise name for help text. Files are only shown as their name without the path. ``python`` is only shown for modules, and the full path to ``sys.executable`` is not shown.
:param path: The Python file being executed. Python puts this in ``sys.argv[0]``, which is used by default. :param _main: The ``__main__`` module. This should only be passed during internal testing.
.. versionadded:: 8.0 Based on command args detection in the Werkzeug reloader.
:meta private: """ if _main is None: _main = sys.modules["__main__"]
if not path: path = sys.argv[0]
# The value of __package__ indicates how Python was called. It may # not exist if a setuptools script is installed as an egg. It may be # set incorrectly for entry points created with pip on Windows. # It is set to "" inside a Shiv or PEX zipapp. if getattr(_main, "__package__", None) in {None, ""} or ( os.name == "nt" and _main.__package__ == "" and not os.path.exists(path) and os.path.exists(f"{path}.exe") ): # Executed a file, like "python app.py". return os.path.basename(path)
# Executed a module, like "python -m example". # Rewritten by Python from "-m script" to "/path/to/script.py". # Need to look at main module to determine how it was executed. py_module = t.cast(str, _main.__package__) name = os.path.splitext(os.path.basename(path))[0]
# A submodule like "example.cli". if name != "__main__": py_module = f"{py_module}.{name}"
return f"python -m {py_module.lstrip('.')}"
def _expand_args( args: cabc.Iterable[str], *, user: bool = True, env: bool = True, glob_recursive: bool = True,) -> list[str]: """Simulate Unix shell expansion with Python functions.
See :func:`glob.glob`, :func:`os.path.expanduser`, and :func:`os.path.expandvars`.
This is intended for use on Windows, where the shell does not do any expansion. It may not exactly match what a Unix shell would do.
:param args: List of command line arguments to expand. :param user: Expand user home directory. :param env: Expand environment variables. :param glob_recursive: ``**`` matches directories recursively.
.. versionchanged:: 8.1 Invalid glob patterns are treated as empty expansions rather than raising an error.
.. versionadded:: 8.0
:meta private: """ from glob import glob
out = []
for arg in args: if user: arg = os.path.expanduser(arg)
if env: arg = os.path.expandvars(arg)
try: matches = glob(arg, recursive=glob_recursive) except re.error: matches = []
if not matches: out.append(arg) else: out.extend(matches)
return out1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230),# containing no networking code at all, loosely modelled on hyper-h2's generic# implementation of HTTP/2 (and in particular the h2.connection.H2Connection# class). There's still a bunch of subtle details you need to get right if you# want to make this actually useful, because it doesn't implement all the# semantics to check that what you're asking to write to the wire is sensible,# but at least it gets you out of dealing with the wire itself.
from h11._connection import Connection, NEED_DATA, PAUSEDfrom h11._events import ( ConnectionClosed, Data, EndOfMessage, Event, InformationalResponse, Request, Response,)from h11._state import ( CLIENT, CLOSED, DONE, ERROR, IDLE, MIGHT_SWITCH_PROTOCOL, MUST_CLOSE, SEND_BODY, SEND_RESPONSE, SERVER, SWITCHED_PROTOCOL,)from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolErrorfrom h11._version import __version__
PRODUCT_ID = "python-h11/" + __version__
__all__ = ( "Connection", "NEED_DATA", "PAUSED", "ConnectionClosed", "Data", "EndOfMessage", "Event", "InformationalResponse", "Request", "Response", "CLIENT", "CLOSED", "DONE", "ERROR", "IDLE", "MUST_CLOSE", "SEND_BODY", "SEND_RESPONSE", "SERVER", "SWITCHED_PROTOCOL", "ProtocolError", "LocalProtocolError", "RemoteProtocolError",)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# We use native strings for all the re patterns, to take advantage of string# formatting, and then convert to bytestrings when compiling the final re# objects.
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace# OWS = *( SP / HTAB )# ; optional whitespaceOWS = r"[ \t]*"
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators# token = 1*tchar## tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"# / DIGIT / ALPHA# ; any VCHAR, except delimiterstoken = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+"
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields# field-name = tokenfield_name = token
# The standard says:## field-value = *( field-content / obs-fold )# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]# field-vchar = VCHAR / obs-text# obs-fold = CRLF 1*( SP / HTAB )# ; obsolete line folding# ; see Section 3.2.4## https://tools.ietf.org/html/rfc5234#appendix-B.1## VCHAR = %x21-7E# ; visible (printing) characters## https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string# obs-text = %x80-FF## However, the standard definition of field-content is WRONG! It disallows# fields containing a single visible character surrounded by whitespace,# e.g. "foo a bar".## See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189## So our definition of field_content attempts to fix it up...## Also, we allow lots of control characters, because apparently people assume# that they're legal in practice (e.g., google analytics makes cookies with# \x01 in them!):# https://github.com/python-hyper/h11/issues/57# We still don't allow NUL or whitespace, because those are often treated as# meta-characters and letting them through can lead to nasty issues like SSRF.vchar = r"[\x21-\x7e]"vchar_or_obs_text = r"[^\x00\s]"field_vchar = vchar_or_obs_textfield_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals())
# We handle obs-fold at a different level, and our fixed-up field_content# already grows to swallow the whole value, so ? instead of *field_value = r"({field_content})?".format(**globals())
# header-field = field-name ":" OWS field-value OWSheader_field = ( r"(?P<field_name>{field_name})" r":" r"{OWS}" r"(?P<field_value>{field_value})" r"{OWS}".format(**globals()))
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line## request-line = method SP request-target SP HTTP-version CRLF# method = token# HTTP-version = HTTP-name "/" DIGIT "." DIGIT# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive## request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full# URL, host+port (for connect), or even "*", but in any case we are guaranteed# that it contists of the visible printing characters.method = tokenrequest_target = r"{vchar}+".format(**globals())http_version = r"HTTP/(?P<http_version>[0-9]\.[0-9])"request_line = ( r"(?P<method>{method})" r" " r"(?P<target>{request_target})" r" " r"{http_version}".format(**globals()))
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line## status-line = HTTP-version SP status-code SP reason-phrase CRLF# status-code = 3DIGIT# reason-phrase = *( HTAB / SP / VCHAR / obs-text )status_code = r"[0-9]{3}"reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals())status_line = ( r"{http_version}" r" " r"(?P<status_code>{status_code})" # However, there are apparently a few too many servers out there that just # leave out the reason phrase: # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036 # https://github.com/seanmonstar/httparse/issues/29 # so make it optional. ?: is a non-capturing group. r"(?: (?P<reason>{reason_phrase}))?".format(**globals()))
HEXDIG = r"[0-9A-Fa-f]"# Actually## chunk-size = 1*HEXDIG## but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20chunk_size = r"({HEXDIG}){{1,20}}".format(**globals())# Actually## chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )## but we aren't parsing the things so we don't really care.chunk_ext = r";.*"chunk_header = ( r"(?P<chunk_size>{chunk_size})" r"(?P<chunk_ext>{chunk_ext})?" r"{OWS}\r\n".format( **globals() ) # Even though the specification does not allow for extra whitespaces, # we are lenient with trailing whitespaces because some servers on the wild use it.)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659# This contains the main Connection class. Everything in h11 revolves around# this.from typing import ( Any, Callable, cast, Dict, List, Optional, overload, Tuple, Type, Union,)
from ._events import ( ConnectionClosed, Data, EndOfMessage, Event, InformationalResponse, Request, Response,)from ._headers import get_comma_header, has_expect_100_continue, set_comma_headerfrom ._readers import READERS, ReadersTypefrom ._receivebuffer import ReceiveBufferfrom ._state import ( _SWITCH_CONNECT, _SWITCH_UPGRADE, CLIENT, ConnectionState, DONE, ERROR, MIGHT_SWITCH_PROTOCOL, SEND_BODY, SERVER, SWITCHED_PROTOCOL,)from ._util import ( # Import the internal things we need LocalProtocolError, RemoteProtocolError, Sentinel,)from ._writers import WRITERS, WritersType
# Everything in __all__ gets re-exported as part of the h11 public API.__all__ = ["Connection", "NEED_DATA", "PAUSED"]
class NEED_DATA(Sentinel, metaclass=Sentinel): pass
class PAUSED(Sentinel, metaclass=Sentinel): pass
# If we ever have this much buffered without it making a complete parseable# event, we error out. The only time we really buffer is when reading the# request/response line + headers together, so this is effectively the limit on# the size of that.## Some precedents for defaults:# - node.js: 80 * 1024# - tomcat: 8 * 1024# - IIS: 16 * 1024# - Apache: <8 KiB per line>DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024
# RFC 7230's rules for connection lifecycles:# - If either side says they want to close the connection, then the connection# must close.# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive# (and even this is a mess -- e.g. if you're implementing a proxy then# sending Connection: keep-alive is forbidden).## We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So# our rule is:# - If someone says Connection: close, we will close# - If someone uses HTTP/1.0, we will close.def _keep_alive(event: Union[Request, Response]) -> bool: connection = get_comma_header(event.headers, b"connection") if b"close" in connection: return False if getattr(event, "http_version", b"1.1") < b"1.1": return False return True
def _body_framing( request_method: bytes, event: Union[Request, Response]) -> Tuple[str, Union[Tuple[()], Tuple[int]]]: # Called when we enter SEND_BODY to figure out framing information for # this body. # # These are the only two events that can trigger a SEND_BODY state: assert type(event) in (Request, Response) # Returns one of: # # ("content-length", count) # ("chunked", ()) # ("http/1.0", ()) # # which are (lookup key, *args) for constructing body reader/writer # objects. # # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3 # # Step 1: some responses always have an empty body, regardless of what the # headers say. if type(event) is Response: if ( event.status_code in (204, 304) or request_method == b"HEAD" or (request_method == b"CONNECT" and 200 <= event.status_code < 300) ): return ("content-length", (0,)) # Section 3.3.3 also lists another case -- responses with status_code # < 200. For us these are InformationalResponses, not Responses, so # they can't get into this function in the first place. assert event.status_code >= 200
# Step 2: check for Transfer-Encoding (T-E beats C-L): transfer_encodings = get_comma_header(event.headers, b"transfer-encoding") if transfer_encodings: assert transfer_encodings == [b"chunked"] return ("chunked", ())
# Step 3: check for Content-Length content_lengths = get_comma_header(event.headers, b"content-length") if content_lengths: return ("content-length", (int(content_lengths[0]),))
# Step 4: no applicable headers; fallback/default depends on type if type(event) is Request: return ("content-length", (0,)) else: return ("http/1.0", ())
################################################################## The main Connection class#################################################################
class Connection: """An object encapsulating the state of an HTTP connection.
Args: our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If you're implementing a server, pass :data:`h11.SERVER`.
max_incomplete_event_size (int): The maximum number of bytes we're willing to buffer of an incomplete event. In practice this mostly sets a limit on the maximum size of the request/response line + headers. If this is exceeded, then :meth:`next_event` will raise :exc:`RemoteProtocolError`.
"""
def __init__( self, our_role: Type[Sentinel], max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, ) -> None: self._max_incomplete_event_size = max_incomplete_event_size # State and role tracking if our_role not in (CLIENT, SERVER): raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}") self.our_role = our_role self.their_role: Type[Sentinel] if our_role is CLIENT: self.their_role = SERVER else: self.their_role = CLIENT self._cstate = ConnectionState()
# Callables for converting data->events or vice-versa given the # current state self._writer = self._get_io_object(self.our_role, None, WRITERS) self._reader = self._get_io_object(self.their_role, None, READERS)
# Holds any unprocessed received data self._receive_buffer = ReceiveBuffer() # If this is true, then it indicates that the incoming connection was # closed *after* the end of whatever's in self._receive_buffer: self._receive_buffer_closed = False
# Extra bits of state that don't fit into the state machine. # # These two are only used to interpret framing headers for figuring # out how to read/write response bodies. their_http_version is also # made available as a convenient public API. self.their_http_version: Optional[bytes] = None self._request_method: Optional[bytes] = None # This is pure flow-control and doesn't at all affect the set of legal # transitions, so no need to bother ConnectionState with it: self.client_is_waiting_for_100_continue = False
@property def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]: """A dictionary like::
{CLIENT: <client state>, SERVER: <server state>}
See :ref:`state-machine` for details.
""" return dict(self._cstate.states)
@property def our_state(self) -> Type[Sentinel]: """The current state of whichever role we are playing. See :ref:`state-machine` for details. """ return self._cstate.states[self.our_role]
@property def their_state(self) -> Type[Sentinel]: """The current state of whichever role we are NOT playing. See :ref:`state-machine` for details. """ return self._cstate.states[self.their_role]
@property def they_are_waiting_for_100_continue(self) -> bool: return self.their_role is CLIENT and self.client_is_waiting_for_100_continue
def start_next_cycle(self) -> None: """Attempt to reset our connection state for a new request/response cycle.
If both client and server are in :data:`DONE` state, then resets them both to :data:`IDLE` state in preparation for a new request/response cycle on this same connection. Otherwise, raises a :exc:`LocalProtocolError`.
See :ref:`keepalive-and-pipelining`.
""" old_states = dict(self._cstate.states) self._cstate.start_next_cycle() self._request_method = None # self.their_http_version gets left alone, since it presumably lasts # beyond a single request/response cycle assert not self.client_is_waiting_for_100_continue self._respond_to_state_changes(old_states)
def _process_error(self, role: Type[Sentinel]) -> None: old_states = dict(self._cstate.states) self._cstate.process_error(role) self._respond_to_state_changes(old_states)
def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]: if type(event) is InformationalResponse and event.status_code == 101: return _SWITCH_UPGRADE if type(event) is Response: if ( _SWITCH_CONNECT in self._cstate.pending_switch_proposals and 200 <= event.status_code < 300 ): return _SWITCH_CONNECT return None
# All events go through here def _process_event(self, role: Type[Sentinel], event: Event) -> None: # First, pass the event through the state machine to make sure it # succeeds. old_states = dict(self._cstate.states) if role is CLIENT and type(event) is Request: if event.method == b"CONNECT": self._cstate.process_client_switch_proposal(_SWITCH_CONNECT) if get_comma_header(event.headers, b"upgrade"): self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE) server_switch_event = None if role is SERVER: server_switch_event = self._server_switch_event(event) self._cstate.process_event(role, type(event), server_switch_event)
# Then perform the updates triggered by it.
if type(event) is Request: self._request_method = event.method
if role is self.their_role and type(event) in ( Request, Response, InformationalResponse, ): event = cast(Union[Request, Response, InformationalResponse], event) self.their_http_version = event.http_version
# Keep alive handling # # RFC 7230 doesn't really say what one should do if Connection: close # shows up on a 1xx InformationalResponse. I think the idea is that # this is not supposed to happen. In any case, if it does happen, we # ignore it. if type(event) in (Request, Response) and not _keep_alive( cast(Union[Request, Response], event) ): self._cstate.process_keep_alive_disabled()
# 100-continue if type(event) is Request and has_expect_100_continue(event): self.client_is_waiting_for_100_continue = True if type(event) in (InformationalResponse, Response): self.client_is_waiting_for_100_continue = False if role is CLIENT and type(event) in (Data, EndOfMessage): self.client_is_waiting_for_100_continue = False
self._respond_to_state_changes(old_states, event)
def _get_io_object( self, role: Type[Sentinel], event: Optional[Event], io_dict: Union[ReadersType, WritersType], ) -> Optional[Callable[..., Any]]: # event may be None; it's only used when entering SEND_BODY state = self._cstate.states[role] if state is SEND_BODY: # Special case: the io_dict has a dict of reader/writer factories # that depend on the request/response framing. framing_type, args = _body_framing( cast(bytes, self._request_method), cast(Union[Request, Response], event) ) return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index] else: # General case: the io_dict just has the appropriate reader/writer # for this state return io_dict.get((role, state)) # type: ignore[return-value]
# This must be called after any action that might have caused # self._cstate.states to change. def _respond_to_state_changes( self, old_states: Dict[Type[Sentinel], Type[Sentinel]], event: Optional[Event] = None, ) -> None: # Update reader/writer if self.our_state != old_states[self.our_role]: self._writer = self._get_io_object(self.our_role, event, WRITERS) if self.their_state != old_states[self.their_role]: self._reader = self._get_io_object(self.their_role, event, READERS)
@property def trailing_data(self) -> Tuple[bytes, bool]: """Data that has been received, but not yet processed, represented as a tuple with two elements, where the first is a byte-string containing the unprocessed data itself, and the second is a bool that is True if the receive connection was closed.
See :ref:`switching-protocols` for discussion of why you'd want this. """ return (bytes(self._receive_buffer), self._receive_buffer_closed)
def receive_data(self, data: bytes) -> None: """Add data to our internal receive buffer.
This does not actually do any processing on the data, just stores it. To trigger processing, you have to call :meth:`next_event`.
Args: data (:term:`bytes-like object`): The new data that was just received.
Special case: If *data* is an empty byte-string like ``b""``, then this indicates that the remote side has closed the connection (end of file). Normally this is convenient, because standard Python APIs like :meth:`file.read` or :meth:`socket.recv` use ``b""`` to indicate end-of-file, while other failures to read are indicated using other mechanisms like raising :exc:`TimeoutError`. When using such an API you can just blindly pass through whatever you get from ``read`` to :meth:`receive_data`, and everything will work.
But, if you have an API where reading an empty string is a valid non-EOF condition, then you need to be aware of this and make sure to check for such strings and avoid passing them to :meth:`receive_data`.
Returns: Nothing, but after calling this you should call :meth:`next_event` to parse the newly received data.
Raises: RuntimeError: Raised if you pass an empty *data*, indicating EOF, and then pass a non-empty *data*, indicating more data that somehow arrived after the EOF.
(Calling ``receive_data(b"")`` multiple times is fine, and equivalent to calling it once.)
""" if data: if self._receive_buffer_closed: raise RuntimeError("received close, then received more data?") self._receive_buffer += data else: self._receive_buffer_closed = True
def _extract_next_receive_event( self, ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: state = self.their_state # We don't pause immediately when they enter DONE, because even in # DONE state we can still process a ConnectionClosed() event. But # if we have data in our buffer, then we definitely aren't getting # a ConnectionClosed() immediately and we need to pause. if state is DONE and self._receive_buffer: return PAUSED if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: return PAUSED assert self._reader is not None event = self._reader(self._receive_buffer) if event is None: if not self._receive_buffer and self._receive_buffer_closed: # In some unusual cases (basically just HTTP/1.0 bodies), EOF # triggers an actual protocol event; in that case, we want to # return that event, and then the state will change and we'll # get called again to generate the actual ConnectionClosed(). if hasattr(self._reader, "read_eof"): event = self._reader.read_eof() else: event = ConnectionClosed() if event is None: event = NEED_DATA return event # type: ignore[no-any-return]
def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: """Parse the next event out of our receive buffer, update our internal state, and return it.
This is a mutating operation -- think of it like calling :func:`next` on an iterator.
Returns: : One of three things:
1) An event object -- see :ref:`events`.
2) The special constant :data:`NEED_DATA`, which indicates that you need to read more data from your socket and pass it to :meth:`receive_data` before this method will be able to return any more events.
3) The special constant :data:`PAUSED`, which indicates that we are not in a state where we can process incoming data (usually because the peer has finished their part of the current request/response cycle, and you have not yet called :meth:`start_next_cycle`). See :ref:`flow-control` for details.
Raises: RemoteProtocolError: The peer has misbehaved. You should close the connection (possibly after sending some kind of 4xx response).
Once this method returns :class:`ConnectionClosed` once, then all subsequent calls will also return :class:`ConnectionClosed`.
If this method raises any exception besides :exc:`RemoteProtocolError` then that's a bug -- if it happens please file a bug report!
If this method raises any exception then it also sets :attr:`Connection.their_state` to :data:`ERROR` -- see :ref:`error-handling` for discussion.
"""
if self.their_state is ERROR: raise RemoteProtocolError("Can't receive data when peer state is ERROR") try: event = self._extract_next_receive_event() if event not in [NEED_DATA, PAUSED]: self._process_event(self.their_role, cast(Event, event)) if event is NEED_DATA: if len(self._receive_buffer) > self._max_incomplete_event_size: # 431 is "Request header fields too large" which is pretty # much the only situation where we can get here raise RemoteProtocolError( "Receive buffer too long", error_status_hint=431 ) if self._receive_buffer_closed: # We're still trying to complete some event, but that's # never going to happen because no more data is coming raise RemoteProtocolError("peer unexpectedly closed connection") return event except BaseException as exc: self._process_error(self.their_role) if isinstance(exc, LocalProtocolError): exc._reraise_as_remote_protocol_error() else: raise
@overload def send(self, event: ConnectionClosed) -> None: ...
@overload def send( self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage] ) -> bytes: ...
@overload def send(self, event: Event) -> Optional[bytes]: ...
def send(self, event: Event) -> Optional[bytes]: """Convert a high-level event into bytes that can be sent to the peer, while updating our internal state machine.
Args: event: The :ref:`event <events>` to send.
Returns: If ``type(event) is ConnectionClosed``, then returns ``None``. Otherwise, returns a :term:`bytes-like object`.
Raises: LocalProtocolError: Sending this event at this time would violate our understanding of the HTTP/1.1 protocol.
If this method raises any exception then it also sets :attr:`Connection.our_state` to :data:`ERROR` -- see :ref:`error-handling` for discussion.
""" data_list = self.send_with_data_passthrough(event) if data_list is None: return None else: return b"".join(data_list)
def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]: """Identical to :meth:`send`, except that in situations where :meth:`send` returns a single :term:`bytes-like object`, this instead returns a list of them -- and when sending a :class:`Data` event, this list is guaranteed to contain the exact object you passed in as :attr:`Data.data`. See :ref:`sendfile` for discussion.
""" if self.our_state is ERROR: raise LocalProtocolError("Can't send data when our state is ERROR") try: if type(event) is Response: event = self._clean_up_response_headers_for_sending(event) # We want to call _process_event before calling the writer, # because if someone tries to do something invalid then this will # give a sensible error message, while our writers all just assume # they will only receive valid events. But, _process_event might # change self._writer. So we have to do a little dance: writer = self._writer self._process_event(self.our_role, event) if type(event) is ConnectionClosed: return None else: # In any situation where writer is None, process_event should # have raised ProtocolError assert writer is not None data_list: List[bytes] = [] writer(event, data_list.append) return data_list except: self._process_error(self.our_role) raise
def send_failed(self) -> None: """Notify the state machine that we failed to send the data it gave us.
This causes :attr:`Connection.our_state` to immediately become :data:`ERROR` -- see :ref:`error-handling` for discussion.
""" self._process_error(self.our_role)
# When sending a Response, we take responsibility for a few things: # # - Sometimes you MUST set Connection: close. We take care of those # times. (You can also set it yourself if you want, and if you do then # we'll respect that and close the connection at the right time. But you # don't have to worry about that unless you want to.) # # - The user has to set Content-Length if they want it. Otherwise, for # responses that have bodies (e.g. not HEAD), then we will automatically # select the right mechanism for streaming a body of unknown length, # which depends on depending on the peer's HTTP version. # # This function's *only* responsibility is making sure headers are set up # right -- everything downstream just looks at the headers. There are no # side channels. def _clean_up_response_headers_for_sending(self, response: Response) -> Response: assert type(response) is Response
headers = response.headers need_close = False
# HEAD requests need some special handling: they always act like they # have Content-Length: 0, and that's how _body_framing treats # them. But their headers are supposed to match what we would send if # the request was a GET. (Technically there is one deviation allowed: # we're allowed to leave out the framing headers -- see # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as # easy to get them right.) method_for_choosing_headers = cast(bytes, self._request_method) if method_for_choosing_headers == b"HEAD": method_for_choosing_headers = b"GET" framing_type, _ = _body_framing(method_for_choosing_headers, response) if framing_type in ("chunked", "http/1.0"): # This response has a body of unknown length. # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked # If our peer is HTTP/1.0, we use no framing headers, and close the # connection afterwards. # # Make sure to clear Content-Length (in principle user could have # set both and then we ignored Content-Length b/c # Transfer-Encoding overwrote it -- this would be naughty of them, # but the HTTP spec says that if our peer does this then we have # to fix it instead of erroring out, so we'll accord the user the # same respect). headers = set_comma_header(headers, b"content-length", []) if self.their_http_version is None or self.their_http_version < b"1.1": # Either we never got a valid request and are sending back an # error (their_http_version is None), so we assume the worst; # or else we did get a valid HTTP/1.0 request, so we know that # they don't understand chunked encoding. headers = set_comma_header(headers, b"transfer-encoding", []) # This is actually redundant ATM, since currently we # unconditionally disable keep-alive when talking to HTTP/1.0 # peers. But let's be defensive just in case we add # Connection: keep-alive support later: if self._request_method != b"HEAD": need_close = True else: headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"])
if not self._cstate.keep_alive or need_close: # Make sure Connection: close is set connection = set(get_comma_header(headers, b"connection")) connection.discard(b"keep-alive") connection.add(b"close") headers = set_comma_header(headers, b"connection", sorted(connection))
return Response( headers=headers, status_code=response.status_code, http_version=response.http_version, reason=response.reason, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369# High level events that make up HTTP/1.1 conversations. Loosely inspired by# the corresponding events in hyper-h2:## http://python-hyper.org/h2/en/stable/api.html#events## Don't subclass these. Stuff will break.
import refrom abc import ABCfrom dataclasses import dataclassfrom typing import List, Tuple, Union
from ._abnf import method, request_targetfrom ._headers import Headers, normalize_and_validatefrom ._util import bytesify, LocalProtocolError, validate
# Everything in __all__ gets re-exported as part of the h11 public API.__all__ = [ "Event", "Request", "InformationalResponse", "Response", "Data", "EndOfMessage", "ConnectionClosed",]
method_re = re.compile(method.encode("ascii"))request_target_re = re.compile(request_target.encode("ascii"))
class Event(ABC): """ Base class for h11 events. """
__slots__ = ()
@dataclass(init=False, frozen=True)class Request(Event): """The beginning of an HTTP request.
Fields:
.. attribute:: method
An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte string. :term:`Bytes-like objects <bytes-like object>` and native strings containing only ascii characters will be automatically converted to byte strings.
.. attribute:: target
The target of an HTTP request, e.g. ``b"/index.html"``, or one of the more exotic formats described in `RFC 7320, section 5.3 <https://tools.ietf.org/html/rfc7230#section-5.3>`_. Always a byte string. :term:`Bytes-like objects <bytes-like object>` and native strings containing only ascii characters will be automatically converted to byte strings.
.. attribute:: headers
Request headers, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
.. attribute:: http_version
The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details.
"""
__slots__ = ("method", "headers", "target", "http_version")
method: bytes headers: Headers target: bytes http_version: bytes
def __init__( self, *, method: Union[bytes, str], headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], target: Union[bytes, str], http_version: Union[bytes, str] = b"1.1", _parsed: bool = False, ) -> None: super().__init__() if isinstance(headers, Headers): object.__setattr__(self, "headers", headers) else: object.__setattr__( self, "headers", normalize_and_validate(headers, _parsed=_parsed) ) if not _parsed: object.__setattr__(self, "method", bytesify(method)) object.__setattr__(self, "target", bytesify(target)) object.__setattr__(self, "http_version", bytesify(http_version)) else: object.__setattr__(self, "method", method) object.__setattr__(self, "target", target) object.__setattr__(self, "http_version", http_version)
# "A server MUST respond with a 400 (Bad Request) status code to any # HTTP/1.1 request message that lacks a Host header field and to any # request message that contains more than one Host header field or a # Host header field with an invalid field-value." # -- https://tools.ietf.org/html/rfc7230#section-5.4 host_count = 0 for name, value in self.headers: if name == b"host": host_count += 1 if self.http_version == b"1.1" and host_count == 0: raise LocalProtocolError("Missing mandatory Host: header") if host_count > 1: raise LocalProtocolError("Found multiple Host: headers")
validate(method_re, self.method, "Illegal method characters") validate(request_target_re, self.target, "Illegal target characters")
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class _ResponseBase(Event): __slots__ = ("headers", "http_version", "reason", "status_code")
headers: Headers http_version: bytes reason: bytes status_code: int
def __init__( self, *, headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]], status_code: int, http_version: Union[bytes, str] = b"1.1", reason: Union[bytes, str] = b"", _parsed: bool = False, ) -> None: super().__init__() if isinstance(headers, Headers): object.__setattr__(self, "headers", headers) else: object.__setattr__( self, "headers", normalize_and_validate(headers, _parsed=_parsed) ) if not _parsed: object.__setattr__(self, "reason", bytesify(reason)) object.__setattr__(self, "http_version", bytesify(http_version)) if not isinstance(status_code, int): raise LocalProtocolError("status code must be integer") # Because IntEnum objects are instances of int, but aren't # duck-compatible (sigh), see gh-72. object.__setattr__(self, "status_code", int(status_code)) else: object.__setattr__(self, "reason", reason) object.__setattr__(self, "http_version", http_version) object.__setattr__(self, "status_code", status_code)
self.__post_init__()
def __post_init__(self) -> None: pass
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class InformationalResponse(_ResponseBase): """An HTTP informational response.
Fields:
.. attribute:: status_code
The status code of this response, as an integer. For an :class:`InformationalResponse`, this is always in the range [100, 200).
.. attribute:: headers
Request headers, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
.. attribute:: http_version
The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details.
.. attribute:: reason
The reason phrase of this response, as a byte string. For example: ``b"OK"``, or ``b"Not Found"``.
"""
def __post_init__(self) -> None: if not (100 <= self.status_code < 200): raise LocalProtocolError( "InformationalResponse status_code should be in range " "[100, 200), not {}".format(self.status_code) )
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class Response(_ResponseBase): """The beginning of an HTTP response.
Fields:
.. attribute:: status_code
The status code of this response, as an integer. For an :class:`Response`, this is always in the range [200, 1000).
.. attribute:: headers
Request headers, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
.. attribute:: http_version
The HTTP protocol version, represented as a byte string like ``b"1.1"``. See :ref:`the HTTP version normalization rules <http_version-format>` for details.
.. attribute:: reason
The reason phrase of this response, as a byte string. For example: ``b"OK"``, or ``b"Not Found"``.
"""
def __post_init__(self) -> None: if not (200 <= self.status_code < 1000): raise LocalProtocolError( "Response status_code should be in range [200, 1000), not {}".format( self.status_code ) )
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(init=False, frozen=True)class Data(Event): """Part of an HTTP message body.
Fields:
.. attribute:: data
A :term:`bytes-like object` containing part of a message body. Or, if using the ``combine=False`` argument to :meth:`Connection.send`, then any object that your socket writing code knows what to do with, and for which calling :func:`len` returns the number of bytes that will be written -- see :ref:`sendfile` for details.
.. attribute:: chunk_start
A marker that indicates whether this data object is from the start of a chunked transfer encoding chunk. This field is ignored when when a Data event is provided to :meth:`Connection.send`: it is only valid on events emitted from :meth:`Connection.next_event`. You probably shouldn't use this attribute at all; see :ref:`chunk-delimiters-are-bad` for details.
.. attribute:: chunk_end
A marker that indicates whether this data object is the last for a given chunked transfer encoding chunk. This field is ignored when when a Data event is provided to :meth:`Connection.send`: it is only valid on events emitted from :meth:`Connection.next_event`. You probably shouldn't use this attribute at all; see :ref:`chunk-delimiters-are-bad` for details.
"""
__slots__ = ("data", "chunk_start", "chunk_end")
data: bytes chunk_start: bool chunk_end: bool
def __init__( self, data: bytes, chunk_start: bool = False, chunk_end: bool = False ) -> None: object.__setattr__(self, "data", data) object.__setattr__(self, "chunk_start", chunk_start) object.__setattr__(self, "chunk_end", chunk_end)
# This is an unhashable type. __hash__ = None # type: ignore
# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that# are forbidden to be sent in a trailer, since processing them as if they were# present in the header section might bypass external security filters."# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part# Unfortunately, the list of forbidden fields is long and vague :-/@dataclass(init=False, frozen=True)class EndOfMessage(Event): """The end of an HTTP message.
Fields:
.. attribute:: headers
Default value: ``[]``
Any trailing headers attached to this message, represented as a list of (name, value) pairs. See :ref:`the header normalization rules <headers-format>` for details.
Must be empty unless ``Transfer-Encoding: chunked`` is in use.
"""
__slots__ = ("headers",)
headers: Headers
def __init__( self, *, headers: Union[ Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None ] = None, _parsed: bool = False, ) -> None: super().__init__() if headers is None: headers = Headers([]) elif not isinstance(headers, Headers): headers = normalize_and_validate(headers, _parsed=_parsed)
object.__setattr__(self, "headers", headers)
# This is an unhashable type. __hash__ = None # type: ignore
@dataclass(frozen=True)class ConnectionClosed(Event): """This event indicates that the sender has closed their outgoing connection.
Note that this does not necessarily mean that they can't *receive* further data, because TCP connections are composed to two one-way channels which can be closed independently. See :ref:`closing` for details.
No fields. """
pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282import refrom typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
from ._abnf import field_name, field_valuefrom ._util import bytesify, LocalProtocolError, validate
if TYPE_CHECKING: from ._events import Request
try: from typing import Literalexcept ImportError: from typing_extensions import Literal # type: ignore
CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1
# Facts# -----## Headers are:# keys: case-insensitive ascii# values: mixture of ascii and raw bytes## "Historically, HTTP has allowed field content with text in the ISO-8859-1# charset [ISO-8859-1], supporting other charsets only through use of# [RFC2047] encoding. In practice, most HTTP header field values use only a# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD# limit their field values to US-ASCII octets. A recipient SHOULD treat other# octets in field content (obs-text) as opaque data."# And it deprecates all non-ascii values## Leading/trailing whitespace in header names is forbidden## Values get leading/trailing whitespace stripped## Content-Disposition actually needs to contain unicode semantically; to# accomplish this it has a terrifically weird way of encoding the filename# itself as ascii (and even this still has lots of cross-browser# incompatibilities)## Order is important:# "a proxy MUST NOT change the order of these field values when forwarding a# message"# (and there are several headers where the order indicates a preference)## Multiple occurences of the same header:# "A sender MUST NOT generate multiple header fields with the same field name# in a message unless either the entire field value for that header field is# defined as a comma-separated list [or the header is Set-Cookie which gets a# special exception]" - RFC 7230. (cookies are in RFC 6265)## So every header aside from Set-Cookie can be merged by b", ".join if it# occurs repeatedly. But, of course, they can't necessarily be split by# .split(b","), because quoting.## Given all this mess (case insensitive, duplicates allowed, order is# important, ...), there doesn't appear to be any standard way to handle# headers in Python -- they're almost like dicts, but... actually just# aren't. For now we punt and just use a super simple representation: headers# are a list of pairs## [(name1, value1), (name2, value2), ...]## where all entries are bytestrings, names are lowercase and have no# leading/trailing whitespace, and values are bytestrings with no# leading/trailing whitespace. Searching and updating are done via naive O(n)# methods.## Maybe a dict-of-lists would be better?
_content_length_re = re.compile(rb"[0-9]+")_field_name_re = re.compile(field_name.encode("ascii"))_field_value_re = re.compile(field_value.encode("ascii"))
class Headers(Sequence[Tuple[bytes, bytes]]): """ A list-like interface that allows iterating over headers as byte-pairs of (lowercased-name, value).
Internally we actually store the representation as three-tuples, including both the raw original casing, in order to preserve casing over-the-wire, and the lowercased name, for case-insensitive comparisions.
r = Request( method="GET", target="/", headers=[("Host", "example.org"), ("Connection", "keep-alive")], http_version="1.1", ) assert r.headers == [ (b"host", b"example.org"), (b"connection", b"keep-alive") ] assert r.headers.raw_items() == [ (b"Host", b"example.org"), (b"Connection", b"keep-alive") ] """
__slots__ = "_full_items"
def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None: self._full_items = full_items
def __bool__(self) -> bool: return bool(self._full_items)
def __eq__(self, other: object) -> bool: return list(self) == list(other) # type: ignore
def __len__(self) -> int: return len(self._full_items)
def __repr__(self) -> str: return "<Headers(%s)>" % repr(list(self))
def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override] _, name, value = self._full_items[idx] return (name, value)
def raw_items(self) -> List[Tuple[bytes, bytes]]: return [(raw_name, value) for raw_name, _, value in self._full_items]
HeaderTypes = Union[ List[Tuple[bytes, bytes]], List[Tuple[bytes, str]], List[Tuple[str, bytes]], List[Tuple[str, str]],]
@overloaddef normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers: ...
@overloaddef normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers: ...
@overloaddef normalize_and_validate( headers: Union[Headers, HeaderTypes], _parsed: bool = False) -> Headers: ...
def normalize_and_validate( headers: Union[Headers, HeaderTypes], _parsed: bool = False) -> Headers: new_headers = [] seen_content_length = None saw_transfer_encoding = False for name, value in headers: # For headers coming out of the parser, we can safely skip some steps, # because it always returns bytes and has already run these regexes # over the data: if not _parsed: name = bytesify(name) value = bytesify(value) validate(_field_name_re, name, "Illegal header name {!r}", name) validate(_field_value_re, value, "Illegal header value {!r}", value) assert isinstance(name, bytes) assert isinstance(value, bytes)
raw_name = name name = name.lower() if name == b"content-length": lengths = {length.strip() for length in value.split(b",")} if len(lengths) != 1: raise LocalProtocolError("conflicting Content-Length headers") value = lengths.pop() validate(_content_length_re, value, "bad Content-Length") if len(value) > CONTENT_LENGTH_MAX_DIGITS: raise LocalProtocolError("bad Content-Length") if seen_content_length is None: seen_content_length = value new_headers.append((raw_name, name, value)) elif seen_content_length != value: raise LocalProtocolError("conflicting Content-Length headers") elif name == b"transfer-encoding": # "A server that receives a request message with a transfer coding # it does not understand SHOULD respond with 501 (Not # Implemented)." # https://tools.ietf.org/html/rfc7230#section-3.3.1 if saw_transfer_encoding: raise LocalProtocolError( "multiple Transfer-Encoding headers", error_status_hint=501 ) # "All transfer-coding names are case-insensitive" # -- https://tools.ietf.org/html/rfc7230#section-4 value = value.lower() if value != b"chunked": raise LocalProtocolError( "Only Transfer-Encoding: chunked is supported", error_status_hint=501, ) saw_transfer_encoding = True new_headers.append((raw_name, name, value)) else: new_headers.append((raw_name, name, value)) return Headers(new_headers)
def get_comma_header(headers: Headers, name: bytes) -> List[bytes]: # Should only be used for headers whose value is a list of # comma-separated, case-insensitive values. # # The header name `name` is expected to be lower-case bytes. # # Connection: meets these criteria (including cast insensitivity). # # Content-Length: technically is just a single value (1*DIGIT), but the # standard makes reference to implementations that do multiple values, and # using this doesn't hurt. Ditto, case insensitivity doesn't things either # way. # # Transfer-Encoding: is more complex (allows for quoted strings), so # splitting on , is actually wrong. For example, this is legal: # # Transfer-Encoding: foo; options="1,2", chunked # # and should be parsed as # # foo; options="1,2" # chunked # # but this naive function will parse it as # # foo; options="1 # 2" # chunked # # However, this is okay because the only thing we are going to do with # any Transfer-Encoding is reject ones that aren't just "chunked", so # both of these will be treated the same anyway. # # Expect: the only legal value is the literal string # "100-continue". Splitting on commas is harmless. Case insensitive. # out: List[bytes] = [] for _, found_name, found_raw_value in headers._full_items: if found_name == name: found_raw_value = found_raw_value.lower() for found_split_value in found_raw_value.split(b","): found_split_value = found_split_value.strip() if found_split_value: out.append(found_split_value) return out
def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers: # The header name `name` is expected to be lower-case bytes. # # Note that when we store the header we use title casing for the header # names, in order to match the conventional HTTP header style. # # Simply calling `.title()` is a blunt approach, but it's correct # here given the cases where we're using `set_comma_header`... # # Connection, Content-Length, Transfer-Encoding. new_headers: List[Tuple[bytes, bytes]] = [] for found_raw_name, found_name, found_raw_value in headers._full_items: if found_name != name: new_headers.append((found_raw_name, found_raw_value)) for new_value in new_values: new_headers.append((name.title(), new_value)) return normalize_and_validate(new_headers)
def has_expect_100_continue(request: "Request") -> bool: # https://tools.ietf.org/html/rfc7231#section-5.1.1 # "A server that receives a 100-continue expectation in an HTTP/1.0 request # MUST ignore that expectation." if request.http_version < b"1.1": return False expect = get_comma_header(request.headers, b"expect") return b"100-continue" in expect.cache/pip/http-v2/a/3/2/f/7/a32f793a951b4bb55e15bb0126f9c9127aab8cec4ba5607016d8841e.bodyAdded+3
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/METADATAAdded+412
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/RECORDAdded+22
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/WHEELAdded+4
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/entry_points.txtAdded+5
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/licenses/LICENSEAdded+21
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__init__.pyAdded+39
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__main__.pyAdded+3
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_classes.pyAdded+199
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_shared.pyAdded+252
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_types.pyAdded+27
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_typing.pyAdded+73
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/cli.pyAdded+317
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/colors.pyAdded+20
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/completion.pyAdded+146
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/core.pyAdded+821
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/main.pyAdded+2013
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/models.pyAdded+651
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/params.pyAdded+1831
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/py.typedAdded
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/rich_utils.pyAdded+753
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/testing.pyAdded+30
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/utils.pyAdded+197
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/METADATAAdded+84
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/RECORDAdded+22
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/WHEELAdded+4
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/licenses/LICENSE.txtAdded+28
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/__init__.pyAdded+123
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_compat.pyAdded+622
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_termui_impl.pyAdded+852
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_textwrap.pyAdded+51
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_utils.pyAdded+36
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_winconsole.pyAdded+296
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/core.pyAdded
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/decorators.pyAdded+551
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/exceptions.pyAdded+308
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/formatting.pyAdded+301
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/globals.pyAdded+67
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/parser.pyAdded+532
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/py.typedAdded
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/shell_completion.pyAdded+667
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/termui.pyAdded+883
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/testing.pyAdded+574
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/types.pyAdded+1209
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/utils.pyAdded+627
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/__init__.pyAdded+62
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_abnf.pyAdded+132
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_connection.pyAdded+659
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_events.pyAdded+369
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_headers.pyAdded+282