Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .cache/pip/http-v2/a/3/2/f/7/a32f793a951b4bb55e15bb0126f9c9127aab8cec4ba5607016d8841e.body +3 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/METADATA +412 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/RECORD +22 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/WHEEL +4 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/entry_points.txt +5 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/licenses/LICENSE +21 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__init__.py +39 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__main__.py +3 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_classes.py +199 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_shared.py +252 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_types.py +27 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_typing.py +73 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/cli.py +317 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/colors.py +20 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/completion.py +146 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/core.py +821 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/main.py +2013 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/models.py +651 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/params.py +1831 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/py.typed +0 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/rich_utils.py +753 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/testing.py +30 -0
- .cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/utils.py +197 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/METADATA +84 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/RECORD +22 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/WHEEL +4 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/licenses/LICENSE.txt +28 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/__init__.py +123 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_compat.py +622 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_termui_impl.py +852 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_textwrap.py +51 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_utils.py +36 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_winconsole.py +296 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/core.py +0 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/decorators.py +551 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/exceptions.py +308 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/formatting.py +301 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/globals.py +67 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/parser.py +532 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/py.typed +0 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/shell_completion.py +667 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/termui.py +883 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/testing.py +574 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/types.py +1209 -0
- .cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/utils.py +627 -0
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/__init__.py +62 -0
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_abnf.py +132 -0
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_connection.py +659 -0
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_events.py +369 -0
- .cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_headers.py +282 -0
.cache/pip/http-v2/a/3/2/f/7/a32f793a951b4bb55e15bb0126f9c9127aab8cec4ba5607016d8841e.body
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:149f7d84afca659d1a97e39a4778794a2f83bf344c5ee5134e09995086cc2392
|
| 3 |
+
size 4988768
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: typer
|
| 3 |
+
Version: 0.24.1
|
| 4 |
+
Summary: Typer, build great CLIs. Easy to code. Based on Python type hints.
|
| 5 |
+
Author-Email: =?utf-8?q?Sebasti=C3=A1n_Ram=C3=ADrez?= <tiangolo@gmail.com>
|
| 6 |
+
License-Expression: MIT
|
| 7 |
+
License-File: LICENSE
|
| 8 |
+
Classifier: Intended Audience :: Information Technology
|
| 9 |
+
Classifier: Intended Audience :: System Administrators
|
| 10 |
+
Classifier: Operating System :: OS Independent
|
| 11 |
+
Classifier: Programming Language :: Python :: 3
|
| 12 |
+
Classifier: Programming Language :: Python
|
| 13 |
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
| 14 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 15 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 16 |
+
Classifier: Topic :: Software Development
|
| 17 |
+
Classifier: Typing :: Typed
|
| 18 |
+
Classifier: Development Status :: 4 - Beta
|
| 19 |
+
Classifier: Intended Audience :: Developers
|
| 20 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 24 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 25 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 26 |
+
Project-URL: Homepage, https://github.com/fastapi/typer
|
| 27 |
+
Project-URL: Documentation, https://typer.tiangolo.com
|
| 28 |
+
Project-URL: Repository, https://github.com/fastapi/typer
|
| 29 |
+
Project-URL: Issues, https://github.com/fastapi/typer/issues
|
| 30 |
+
Project-URL: Changelog, https://typer.tiangolo.com/release-notes/
|
| 31 |
+
Requires-Python: >=3.10
|
| 32 |
+
Requires-Dist: click>=8.2.1
|
| 33 |
+
Requires-Dist: shellingham>=1.3.0
|
| 34 |
+
Requires-Dist: rich>=12.3.0
|
| 35 |
+
Requires-Dist: annotated-doc>=0.0.2
|
| 36 |
+
Description-Content-Type: text/markdown
|
| 37 |
+
|
| 38 |
+
<p align="center">
|
| 39 |
+
<a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>
|
| 40 |
+
|
| 41 |
+
</p>
|
| 42 |
+
<p align="center">
|
| 43 |
+
<em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>
|
| 44 |
+
</p>
|
| 45 |
+
<p align="center">
|
| 46 |
+
<a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank">
|
| 47 |
+
<img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">
|
| 48 |
+
</a>
|
| 49 |
+
<a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish" target="_blank">
|
| 50 |
+
<img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish">
|
| 51 |
+
</a>
|
| 52 |
+
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer" target="_blank">
|
| 53 |
+
<img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage">
|
| 54 |
+
<a href="https://pypi.org/project/typer" target="_blank">
|
| 55 |
+
<img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">
|
| 56 |
+
</a>
|
| 57 |
+
</p>
|
| 58 |
+
|
| 59 |
+
---
|
| 60 |
+
|
| 61 |
+
**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com</a>
|
| 62 |
+
|
| 63 |
+
**Source Code**: <a href="https://github.com/fastapi/typer" target="_blank">https://github.com/fastapi/typer</a>
|
| 64 |
+
|
| 65 |
+
---
|
| 66 |
+
|
| 67 |
+
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.
|
| 68 |
+
|
| 69 |
+
It's also a command line tool to run scripts, automatically converting them to CLI applications.
|
| 70 |
+
|
| 71 |
+
The key features are:
|
| 72 |
+
|
| 73 |
+
* **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.
|
| 74 |
+
* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.
|
| 75 |
+
* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.
|
| 76 |
+
* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.
|
| 77 |
+
* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.
|
| 78 |
+
* **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.
|
| 79 |
+
|
| 80 |
+
## 2026 February - Typer developer survey
|
| 81 |
+
|
| 82 |
+
Help us define Typer's future by filling the <a href="https://forms.gle/nYvutPrVkmBQZLas7" class="external-link" target="_blank">Typer developer survey</a>. ✨
|
| 83 |
+
|
| 84 |
+
## FastAPI of CLIs
|
| 85 |
+
|
| 86 |
+
**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.
|
| 87 |
+
|
| 88 |
+
## Installation
|
| 89 |
+
|
| 90 |
+
Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:
|
| 91 |
+
|
| 92 |
+
<div class="termy">
|
| 93 |
+
|
| 94 |
+
```console
|
| 95 |
+
$ pip install typer
|
| 96 |
+
---> 100%
|
| 97 |
+
Successfully installed typer rich shellingham
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
</div>
|
| 101 |
+
|
| 102 |
+
## Example
|
| 103 |
+
|
| 104 |
+
### The absolute minimum
|
| 105 |
+
|
| 106 |
+
* Create a file `main.py` with:
|
| 107 |
+
|
| 108 |
+
```Python
|
| 109 |
+
def main(name: str):
|
| 110 |
+
print(f"Hello {name}")
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.
|
| 114 |
+
|
| 115 |
+
### Run it
|
| 116 |
+
|
| 117 |
+
Run your application with the `typer` command:
|
| 118 |
+
|
| 119 |
+
<div class="termy">
|
| 120 |
+
|
| 121 |
+
```console
|
| 122 |
+
// Run your application
|
| 123 |
+
$ typer main.py run
|
| 124 |
+
|
| 125 |
+
// You get a nice error, you are missing NAME
|
| 126 |
+
Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
|
| 127 |
+
Try 'typer [PATH_OR_MODULE] run --help' for help.
|
| 128 |
+
╭─ Error ───────────────────────────────────────────╮
|
| 129 |
+
│ Missing argument 'NAME'. │
|
| 130 |
+
╰───────────────────────────────────────────────────╯
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
// You get a --help for free
|
| 134 |
+
$ typer main.py run --help
|
| 135 |
+
|
| 136 |
+
Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME
|
| 137 |
+
|
| 138 |
+
Run the provided Typer app.
|
| 139 |
+
|
| 140 |
+
╭─ Arguments ───────────────────────────────────────╮
|
| 141 |
+
│ * name TEXT [default: None] [required] |
|
| 142 |
+
╰───────────────────────────────────────────────────╯
|
| 143 |
+
╭─ Options ─────────────────────────────────────────╮
|
| 144 |
+
│ --help Show this message and exit. │
|
| 145 |
+
╰───────────────────────────────────────────────────╯
|
| 146 |
+
|
| 147 |
+
// Now pass the NAME argument
|
| 148 |
+
$ typer main.py run Camila
|
| 149 |
+
|
| 150 |
+
Hello Camila
|
| 151 |
+
|
| 152 |
+
// It works! 🎉
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
</div>
|
| 156 |
+
|
| 157 |
+
This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.
|
| 158 |
+
|
| 159 |
+
**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.
|
| 160 |
+
|
| 161 |
+
## Use Typer in your code
|
| 162 |
+
|
| 163 |
+
Now let's start using Typer in your own code, update `main.py` with:
|
| 164 |
+
|
| 165 |
+
```Python
|
| 166 |
+
import typer
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def main(name: str):
|
| 170 |
+
print(f"Hello {name}")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
typer.run(main)
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
Now you could run it with Python directly:
|
| 178 |
+
|
| 179 |
+
<div class="termy">
|
| 180 |
+
|
| 181 |
+
```console
|
| 182 |
+
// Run your application
|
| 183 |
+
$ python main.py
|
| 184 |
+
|
| 185 |
+
// You get a nice error, you are missing NAME
|
| 186 |
+
Usage: main.py [OPTIONS] NAME
|
| 187 |
+
Try 'main.py --help' for help.
|
| 188 |
+
╭─ Error ───────────────────────────────────────────╮
|
| 189 |
+
│ Missing argument 'NAME'. │
|
| 190 |
+
╰───────────────────────────────────────────────────╯
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
// You get a --help for free
|
| 194 |
+
$ python main.py --help
|
| 195 |
+
|
| 196 |
+
Usage: main.py [OPTIONS] NAME
|
| 197 |
+
|
| 198 |
+
╭─ Arguments ───────────────────────────────────────╮
|
| 199 |
+
│ * name TEXT [default: None] [required] |
|
| 200 |
+
╰───────────────────────────────────────────────────╯
|
| 201 |
+
╭─ Options ─────────────────────────────────────────╮
|
| 202 |
+
│ --help Show this message and exit. │
|
| 203 |
+
╰───────────────────────────────────────────────────╯
|
| 204 |
+
|
| 205 |
+
// Now pass the NAME argument
|
| 206 |
+
$ python main.py Camila
|
| 207 |
+
|
| 208 |
+
Hello Camila
|
| 209 |
+
|
| 210 |
+
// It works! 🎉
|
| 211 |
+
```
|
| 212 |
+
|
| 213 |
+
</div>
|
| 214 |
+
|
| 215 |
+
**Note**: you can also call this same script with the `typer` command, but you don't need to.
|
| 216 |
+
|
| 217 |
+
## Example upgrade
|
| 218 |
+
|
| 219 |
+
This was the simplest example possible.
|
| 220 |
+
|
| 221 |
+
Now let's see one a bit more complex.
|
| 222 |
+
|
| 223 |
+
### An example with two subcommands
|
| 224 |
+
|
| 225 |
+
Modify the file `main.py`.
|
| 226 |
+
|
| 227 |
+
Create a `typer.Typer()` app, and create two subcommands with their parameters.
|
| 228 |
+
|
| 229 |
+
```Python hl_lines="3 6 11 20"
|
| 230 |
+
import typer
|
| 231 |
+
|
| 232 |
+
app = typer.Typer()
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@app.command()
|
| 236 |
+
def hello(name: str):
|
| 237 |
+
print(f"Hello {name}")
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@app.command()
|
| 241 |
+
def goodbye(name: str, formal: bool = False):
|
| 242 |
+
if formal:
|
| 243 |
+
print(f"Goodbye Ms. {name}. Have a good day.")
|
| 244 |
+
else:
|
| 245 |
+
print(f"Bye {name}!")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if __name__ == "__main__":
|
| 249 |
+
app()
|
| 250 |
+
```
|
| 251 |
+
|
| 252 |
+
And that will:
|
| 253 |
+
|
| 254 |
+
* Explicitly create a `typer.Typer` app.
|
| 255 |
+
* The previous `typer.run` actually creates one implicitly for you.
|
| 256 |
+
* Add two subcommands with `@app.command()`.
|
| 257 |
+
* Execute the `app()` itself, as if it was a function (instead of `typer.run`).
|
| 258 |
+
|
| 259 |
+
### Run the upgraded example
|
| 260 |
+
|
| 261 |
+
Check the new help:
|
| 262 |
+
|
| 263 |
+
<div class="termy">
|
| 264 |
+
|
| 265 |
+
```console
|
| 266 |
+
$ python main.py --help
|
| 267 |
+
|
| 268 |
+
Usage: main.py [OPTIONS] COMMAND [ARGS]...
|
| 269 |
+
|
| 270 |
+
╭─ Options ───────────────────────────────��─────────╮
|
| 271 |
+
│ --install-completion Install completion │
|
| 272 |
+
│ for the current │
|
| 273 |
+
│ shell. │
|
| 274 |
+
│ --show-completion Show completion for │
|
| 275 |
+
│ the current shell, │
|
| 276 |
+
│ to copy it or │
|
| 277 |
+
│ customize the │
|
| 278 |
+
│ installation. │
|
| 279 |
+
│ --help Show this message │
|
| 280 |
+
│ and exit. │
|
| 281 |
+
╰───────────────────────────────────────────────────╯
|
| 282 |
+
╭─ Commands ────────────────────────────────────────╮
|
| 283 |
+
│ goodbye │
|
| 284 |
+
│ hello │
|
| 285 |
+
╰───────────────────────────────────────────────────╯
|
| 286 |
+
|
| 287 |
+
// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion
|
| 288 |
+
|
| 289 |
+
// You have 2 subcommands (the 2 functions): goodbye and hello
|
| 290 |
+
```
|
| 291 |
+
|
| 292 |
+
</div>
|
| 293 |
+
|
| 294 |
+
Now check the help for the `hello` command:
|
| 295 |
+
|
| 296 |
+
<div class="termy">
|
| 297 |
+
|
| 298 |
+
```console
|
| 299 |
+
$ python main.py hello --help
|
| 300 |
+
|
| 301 |
+
Usage: main.py hello [OPTIONS] NAME
|
| 302 |
+
|
| 303 |
+
╭─ Arguments ───────────────────────────────────────╮
|
| 304 |
+
│ * name TEXT [default: None] [required] │
|
| 305 |
+
╰───────────────────────────────────────────────────╯
|
| 306 |
+
╭─ Options ─────────────────────────────────────────╮
|
| 307 |
+
│ --help Show this message and exit. │
|
| 308 |
+
╰───────────────────────────────────────────────────╯
|
| 309 |
+
```
|
| 310 |
+
|
| 311 |
+
</div>
|
| 312 |
+
|
| 313 |
+
And now check the help for the `goodbye` command:
|
| 314 |
+
|
| 315 |
+
<div class="termy">
|
| 316 |
+
|
| 317 |
+
```console
|
| 318 |
+
$ python main.py goodbye --help
|
| 319 |
+
|
| 320 |
+
Usage: main.py goodbye [OPTIONS] NAME
|
| 321 |
+
|
| 322 |
+
╭─ Arguments ───────────────────────────────────────╮
|
| 323 |
+
│ * name TEXT [default: None] [required] │
|
| 324 |
+
╰───────────────────────────────────────────────────╯
|
| 325 |
+
╭─ Options ─────────────────────────────────────────╮
|
| 326 |
+
│ --formal --no-formal [default: no-formal] │
|
| 327 |
+
│ --help Show this message │
|
| 328 |
+
│ and exit. │
|
| 329 |
+
╰───────────────────────────────────────────────────╯
|
| 330 |
+
|
| 331 |
+
// Automatic --formal and --no-formal for the bool option 🎉
|
| 332 |
+
```
|
| 333 |
+
|
| 334 |
+
</div>
|
| 335 |
+
|
| 336 |
+
Now you can try out the new command line application:
|
| 337 |
+
|
| 338 |
+
<div class="termy">
|
| 339 |
+
|
| 340 |
+
```console
|
| 341 |
+
// Use it with the hello command
|
| 342 |
+
|
| 343 |
+
$ python main.py hello Camila
|
| 344 |
+
|
| 345 |
+
Hello Camila
|
| 346 |
+
|
| 347 |
+
// And with the goodbye command
|
| 348 |
+
|
| 349 |
+
$ python main.py goodbye Camila
|
| 350 |
+
|
| 351 |
+
Bye Camila!
|
| 352 |
+
|
| 353 |
+
// And with --formal
|
| 354 |
+
|
| 355 |
+
$ python main.py goodbye --formal Camila
|
| 356 |
+
|
| 357 |
+
Goodbye Ms. Camila. Have a good day.
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
</div>
|
| 361 |
+
|
| 362 |
+
**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.
|
| 363 |
+
|
| 364 |
+
### Recap
|
| 365 |
+
|
| 366 |
+
In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.
|
| 367 |
+
|
| 368 |
+
You do that with standard modern Python types.
|
| 369 |
+
|
| 370 |
+
You don't have to learn a new syntax, the methods or classes of a specific library, etc.
|
| 371 |
+
|
| 372 |
+
Just standard **Python**.
|
| 373 |
+
|
| 374 |
+
For example, for an `int`:
|
| 375 |
+
|
| 376 |
+
```Python
|
| 377 |
+
total: int
|
| 378 |
+
```
|
| 379 |
+
|
| 380 |
+
or for a `bool` flag:
|
| 381 |
+
|
| 382 |
+
```Python
|
| 383 |
+
force: bool
|
| 384 |
+
```
|
| 385 |
+
|
| 386 |
+
And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.
|
| 387 |
+
|
| 388 |
+
**You get**: great editor support, including **completion** and **type checks** everywhere.
|
| 389 |
+
|
| 390 |
+
**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.
|
| 391 |
+
|
| 392 |
+
For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.
|
| 393 |
+
|
| 394 |
+
## Dependencies
|
| 395 |
+
|
| 396 |
+
**Typer** stands on the shoulders of giants. It has three required dependencies:
|
| 397 |
+
|
| 398 |
+
* <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.
|
| 399 |
+
* <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.
|
| 400 |
+
* <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.
|
| 401 |
+
|
| 402 |
+
### `typer-slim`
|
| 403 |
+
|
| 404 |
+
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.
|
| 405 |
+
|
| 406 |
+
However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.
|
| 407 |
+
|
| 408 |
+
If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.
|
| 409 |
+
|
| 410 |
+
## License
|
| 411 |
+
|
| 412 |
+
This project is licensed under the terms of the MIT license.
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
typer-0.24.1.dist-info/METADATA,sha256=V4OWoWjBhPNcoIaOxhr1cszo69nePKOHMRXERkMscKs,16057
|
| 2 |
+
typer-0.24.1.dist-info/WHEEL,sha256=Wb0ASbVj8JvWHpOiIpPi7ucfIgJeCi__PzivviEAQFc,90
|
| 3 |
+
typer-0.24.1.dist-info/entry_points.txt,sha256=YO13ByiqWeuas9V0JADLUARZFUe_cwU_7wmTNvxBYQ8,57
|
| 4 |
+
typer-0.24.1.dist-info/licenses/LICENSE,sha256=WJks68-N-25AxOIRLtEhJsJDZm3KORKj14t-ysSFnUk,1086
|
| 5 |
+
typer/__init__.py,sha256=WOelHJu4PW0hk9nfjEX0Qxssb58NCh1km_Xq5LY_33s,1596
|
| 6 |
+
typer/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
| 7 |
+
typer/_completion_classes.py,sha256=R9v4D8pJ_-n8fLOuyxrRSu7sP5lpXIy5fsLUW8zwsDU,7039
|
| 8 |
+
typer/_completion_shared.py,sha256=-uhCUIMc2S1ywdB-fBSSccH70mIBEsVTxHomcmy-klE,9129
|
| 9 |
+
typer/_types.py,sha256=0lcBDLcsxqr1sxTsqObj_u0Dfa37lWJYUY4PNkX4QlA,974
|
| 10 |
+
typer/_typing.py,sha256=QOw5o-B2L--C3ly2DQH6aUwag6x5brV5FhVaBZ5gzMg,1727
|
| 11 |
+
typer/cli.py,sha256=icRbazvdRdbYeaidPZOmJDOzrP3RAa7vj2INVV9Zb8Q,10183
|
| 12 |
+
typer/colors.py,sha256=e42j8uB520hLpX5C_0fiR3OOoIFMbhO3ADZvv6hlAV8,430
|
| 13 |
+
typer/completion.py,sha256=FRTR9hP_IPdJp-4GXPOq0btXo5SvgAtLVfS3ZkAMpgQ,4793
|
| 14 |
+
typer/core.py,sha256=O5NywSwHPyYbLhZkPYSfwIj7Za2hPnoPP4xPXRa97a0,27947
|
| 15 |
+
typer/main.py,sha256=xyNex-QfGUi-enu9j9rl-_wofApxs5VwdpCthAUAAkk,69005
|
| 16 |
+
typer/models.py,sha256=OwPG3MAXiUD5ih3p8eNVciXUsL07UIJfNWy3JiNpDfg,19843
|
| 17 |
+
typer/params.py,sha256=AovViRtl-VvUIXnmKKpnxoWK9_gHUbyQgXxxv3h_7lI,59713
|
| 18 |
+
typer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 19 |
+
typer/rich_utils.py,sha256=RTyeoxwz16ZZXYbwoEixB_LSEnqpoStG_TGCRTz6zFQ,25424
|
| 20 |
+
typer/testing.py,sha256=-ovLNjUNNEFCJoau-41iTJIobsjPbqyTrRq7-8ac4z4,871
|
| 21 |
+
typer/utils.py,sha256=wnJ1DWXBFMnxLHaMN_HDYntxLRby0K-rux63aokHInI,7599
|
| 22 |
+
typer-0.24.1.dist-info/RECORD,,
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: pdm-backend (2.4.7)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
typer = typer.cli:main
|
| 3 |
+
|
| 4 |
+
[gui_scripts]
|
| 5 |
+
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer-0.24.1.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
The MIT License (MIT)
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019 Sebastián Ramírez
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in
|
| 13 |
+
all copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 21 |
+
THE SOFTWARE.
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Typer, build great CLIs. Easy to code. Based on Python type hints."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.24.1"
|
| 4 |
+
|
| 5 |
+
from shutil import get_terminal_size as get_terminal_size
|
| 6 |
+
|
| 7 |
+
from click.exceptions import Abort as Abort
|
| 8 |
+
from click.exceptions import BadParameter as BadParameter
|
| 9 |
+
from click.exceptions import Exit as Exit
|
| 10 |
+
from click.termui import clear as clear
|
| 11 |
+
from click.termui import confirm as confirm
|
| 12 |
+
from click.termui import echo_via_pager as echo_via_pager
|
| 13 |
+
from click.termui import edit as edit
|
| 14 |
+
from click.termui import getchar as getchar
|
| 15 |
+
from click.termui import pause as pause
|
| 16 |
+
from click.termui import progressbar as progressbar
|
| 17 |
+
from click.termui import prompt as prompt
|
| 18 |
+
from click.termui import secho as secho
|
| 19 |
+
from click.termui import style as style
|
| 20 |
+
from click.termui import unstyle as unstyle
|
| 21 |
+
from click.utils import echo as echo
|
| 22 |
+
from click.utils import format_filename as format_filename
|
| 23 |
+
from click.utils import get_app_dir as get_app_dir
|
| 24 |
+
from click.utils import get_binary_stream as get_binary_stream
|
| 25 |
+
from click.utils import get_text_stream as get_text_stream
|
| 26 |
+
from click.utils import open_file as open_file
|
| 27 |
+
|
| 28 |
+
from . import colors as colors
|
| 29 |
+
from .main import Typer as Typer
|
| 30 |
+
from .main import launch as launch
|
| 31 |
+
from .main import run as run
|
| 32 |
+
from .models import CallbackParam as CallbackParam
|
| 33 |
+
from .models import Context as Context
|
| 34 |
+
from .models import FileBinaryRead as FileBinaryRead
|
| 35 |
+
from .models import FileBinaryWrite as FileBinaryWrite
|
| 36 |
+
from .models import FileText as FileText
|
| 37 |
+
from .models import FileTextWrite as FileTextWrite
|
| 38 |
+
from .params import Argument as Argument
|
| 39 |
+
from .params import Option as Option
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/__main__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .cli import main
|
| 2 |
+
|
| 3 |
+
main()
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_completion_classes.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import sys
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import click
|
| 8 |
+
import click.parser
|
| 9 |
+
import click.shell_completion
|
| 10 |
+
from click.shell_completion import split_arg_string as click_split_arg_string
|
| 11 |
+
|
| 12 |
+
from ._completion_shared import (
|
| 13 |
+
COMPLETION_SCRIPT_BASH,
|
| 14 |
+
COMPLETION_SCRIPT_FISH,
|
| 15 |
+
COMPLETION_SCRIPT_POWER_SHELL,
|
| 16 |
+
COMPLETION_SCRIPT_ZSH,
|
| 17 |
+
Shells,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _sanitize_help_text(text: str) -> str:
|
| 22 |
+
"""Sanitizes the help text by removing rich tags"""
|
| 23 |
+
if not importlib.util.find_spec("rich"):
|
| 24 |
+
return text
|
| 25 |
+
from . import rich_utils
|
| 26 |
+
|
| 27 |
+
return rich_utils.rich_render_text(text)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class BashComplete(click.shell_completion.BashComplete):
|
| 31 |
+
name = Shells.bash.value
|
| 32 |
+
source_template = COMPLETION_SCRIPT_BASH
|
| 33 |
+
|
| 34 |
+
def source_vars(self) -> dict[str, Any]:
|
| 35 |
+
return {
|
| 36 |
+
"complete_func": self.func_name,
|
| 37 |
+
"autocomplete_var": self.complete_var,
|
| 38 |
+
"prog_name": self.prog_name,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 42 |
+
cwords = click_split_arg_string(os.environ["COMP_WORDS"])
|
| 43 |
+
cword = int(os.environ["COMP_CWORD"])
|
| 44 |
+
args = cwords[1:cword]
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
incomplete = cwords[cword]
|
| 48 |
+
except IndexError:
|
| 49 |
+
incomplete = ""
|
| 50 |
+
|
| 51 |
+
return args, incomplete
|
| 52 |
+
|
| 53 |
+
def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
|
| 54 |
+
# TODO: Explore replicating the new behavior from Click, with item types and
|
| 55 |
+
# triggering completion for files and directories
|
| 56 |
+
# return f"{item.type},{item.value}"
|
| 57 |
+
return f"{item.value}"
|
| 58 |
+
|
| 59 |
+
def complete(self) -> str:
|
| 60 |
+
args, incomplete = self.get_completion_args()
|
| 61 |
+
completions = self.get_completions(args, incomplete)
|
| 62 |
+
out = [self.format_completion(item) for item in completions]
|
| 63 |
+
return "\n".join(out)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class ZshComplete(click.shell_completion.ZshComplete):
|
| 67 |
+
name = Shells.zsh.value
|
| 68 |
+
source_template = COMPLETION_SCRIPT_ZSH
|
| 69 |
+
|
| 70 |
+
def source_vars(self) -> dict[str, Any]:
|
| 71 |
+
return {
|
| 72 |
+
"complete_func": self.func_name,
|
| 73 |
+
"autocomplete_var": self.complete_var,
|
| 74 |
+
"prog_name": self.prog_name,
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 78 |
+
completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
|
| 79 |
+
cwords = click_split_arg_string(completion_args)
|
| 80 |
+
args = cwords[1:]
|
| 81 |
+
if args and not completion_args.endswith(" "):
|
| 82 |
+
incomplete = args[-1]
|
| 83 |
+
args = args[:-1]
|
| 84 |
+
else:
|
| 85 |
+
incomplete = ""
|
| 86 |
+
return args, incomplete
|
| 87 |
+
|
| 88 |
+
def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
|
| 89 |
+
def escape(s: str) -> str:
|
| 90 |
+
return (
|
| 91 |
+
s.replace('"', '""')
|
| 92 |
+
.replace("'", "''")
|
| 93 |
+
.replace("$", "\\$")
|
| 94 |
+
.replace("`", "\\`")
|
| 95 |
+
.replace(":", r"\\:")
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
# TODO: Explore replicating the new behavior from Click, pay attention to
|
| 99 |
+
# the difference with and without escape
|
| 100 |
+
# return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"
|
| 101 |
+
if item.help:
|
| 102 |
+
return f'"{escape(item.value)}":"{_sanitize_help_text(escape(item.help))}"'
|
| 103 |
+
else:
|
| 104 |
+
return f'"{escape(item.value)}"'
|
| 105 |
+
|
| 106 |
+
def complete(self) -> str:
|
| 107 |
+
args, incomplete = self.get_completion_args()
|
| 108 |
+
completions = self.get_completions(args, incomplete)
|
| 109 |
+
res = [self.format_completion(item) for item in completions]
|
| 110 |
+
if res:
|
| 111 |
+
args_str = "\n".join(res)
|
| 112 |
+
return f"_arguments '*: :(({args_str}))'"
|
| 113 |
+
else:
|
| 114 |
+
return "_files"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class FishComplete(click.shell_completion.FishComplete):
|
| 118 |
+
name = Shells.fish.value
|
| 119 |
+
source_template = COMPLETION_SCRIPT_FISH
|
| 120 |
+
|
| 121 |
+
def source_vars(self) -> dict[str, Any]:
|
| 122 |
+
return {
|
| 123 |
+
"complete_func": self.func_name,
|
| 124 |
+
"autocomplete_var": self.complete_var,
|
| 125 |
+
"prog_name": self.prog_name,
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 129 |
+
completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
|
| 130 |
+
cwords = click_split_arg_string(completion_args)
|
| 131 |
+
args = cwords[1:]
|
| 132 |
+
if args and not completion_args.endswith(" "):
|
| 133 |
+
incomplete = args[-1]
|
| 134 |
+
args = args[:-1]
|
| 135 |
+
else:
|
| 136 |
+
incomplete = ""
|
| 137 |
+
return args, incomplete
|
| 138 |
+
|
| 139 |
+
def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
|
| 140 |
+
# TODO: Explore replicating the new behavior from Click, pay attention to
|
| 141 |
+
# the difference with and without formatted help
|
| 142 |
+
# if item.help:
|
| 143 |
+
# return f"{item.type},{item.value}\t{item.help}"
|
| 144 |
+
|
| 145 |
+
# return f"{item.type},{item.value}
|
| 146 |
+
if item.help:
|
| 147 |
+
formatted_help = re.sub(r"\s", " ", item.help)
|
| 148 |
+
return f"{item.value}\t{_sanitize_help_text(formatted_help)}"
|
| 149 |
+
else:
|
| 150 |
+
return f"{item.value}"
|
| 151 |
+
|
| 152 |
+
def complete(self) -> str:
|
| 153 |
+
complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")
|
| 154 |
+
args, incomplete = self.get_completion_args()
|
| 155 |
+
completions = self.get_completions(args, incomplete)
|
| 156 |
+
show_args = [self.format_completion(item) for item in completions]
|
| 157 |
+
if complete_action == "get-args":
|
| 158 |
+
if show_args:
|
| 159 |
+
return "\n".join(show_args)
|
| 160 |
+
elif complete_action == "is-args":
|
| 161 |
+
if show_args:
|
| 162 |
+
# Activate complete args (no files)
|
| 163 |
+
sys.exit(0)
|
| 164 |
+
else:
|
| 165 |
+
# Deactivate complete args (allow files)
|
| 166 |
+
sys.exit(1)
|
| 167 |
+
return "" # pragma: no cover
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class PowerShellComplete(click.shell_completion.ShellComplete):
|
| 171 |
+
name = Shells.powershell.value
|
| 172 |
+
source_template = COMPLETION_SCRIPT_POWER_SHELL
|
| 173 |
+
|
| 174 |
+
def source_vars(self) -> dict[str, Any]:
|
| 175 |
+
return {
|
| 176 |
+
"complete_func": self.func_name,
|
| 177 |
+
"autocomplete_var": self.complete_var,
|
| 178 |
+
"prog_name": self.prog_name,
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 182 |
+
completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
|
| 183 |
+
incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")
|
| 184 |
+
cwords = click_split_arg_string(completion_args)
|
| 185 |
+
args = cwords[1:-1] if incomplete else cwords[1:]
|
| 186 |
+
return args, incomplete
|
| 187 |
+
|
| 188 |
+
def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
|
| 189 |
+
return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}"
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def completion_init() -> None:
|
| 193 |
+
click.shell_completion.add_completion_class(BashComplete, Shells.bash.value)
|
| 194 |
+
click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value)
|
| 195 |
+
click.shell_completion.add_completion_class(FishComplete, Shells.fish.value)
|
| 196 |
+
click.shell_completion.add_completion_class(
|
| 197 |
+
PowerSh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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import subprocess
|
| 4 |
+
from enum import Enum
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import click
|
| 8 |
+
import shellingham
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Shells(str, Enum):
|
| 12 |
+
bash = "bash"
|
| 13 |
+
zsh = "zsh"
|
| 14 |
+
fish = "fish"
|
| 15 |
+
powershell = "powershell"
|
| 16 |
+
pwsh = "pwsh"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
COMPLETION_SCRIPT_BASH = """
|
| 20 |
+
%(complete_func)s() {
|
| 21 |
+
local IFS=$'\n'
|
| 22 |
+
COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\
|
| 23 |
+
COMP_CWORD=$COMP_CWORD \\
|
| 24 |
+
%(autocomplete_var)s=complete_bash $1 ) )
|
| 25 |
+
return 0
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
complete -o default -F %(complete_func)s %(prog_name)s
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
COMPLETION_SCRIPT_ZSH = """
|
| 32 |
+
#compdef %(prog_name)s
|
| 33 |
+
|
| 34 |
+
%(complete_func)s() {
|
| 35 |
+
eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s)
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
compdef %(complete_func)s %(prog_name)s
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
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"'
|
| 42 |
+
|
| 43 |
+
COMPLETION_SCRIPT_POWER_SHELL = """
|
| 44 |
+
Import-Module PSReadLine
|
| 45 |
+
Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete
|
| 46 |
+
$scriptblock = {
|
| 47 |
+
param($wordToComplete, $commandAst, $cursorPosition)
|
| 48 |
+
$Env:%(autocomplete_var)s = "complete_powershell"
|
| 49 |
+
$Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString()
|
| 50 |
+
$Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete
|
| 51 |
+
%(prog_name)s | ForEach-Object {
|
| 52 |
+
$commandArray = $_ -Split ":::"
|
| 53 |
+
$command = $commandArray[0]
|
| 54 |
+
$helpString = $commandArray[1]
|
| 55 |
+
[System.Management.Automation.CompletionResult]::new(
|
| 56 |
+
$command, $command, 'ParameterValue', $helpString)
|
| 57 |
+
}
|
| 58 |
+
$Env:%(autocomplete_var)s = ""
|
| 59 |
+
$Env:_TYPER_COMPLETE_ARGS = ""
|
| 60 |
+
$Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = ""
|
| 61 |
+
}
|
| 62 |
+
Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
_completion_scripts = {
|
| 66 |
+
"bash": COMPLETION_SCRIPT_BASH,
|
| 67 |
+
"zsh": COMPLETION_SCRIPT_ZSH,
|
| 68 |
+
"fish": COMPLETION_SCRIPT_FISH,
|
| 69 |
+
"powershell": COMPLETION_SCRIPT_POWER_SHELL,
|
| 70 |
+
"pwsh": COMPLETION_SCRIPT_POWER_SHELL,
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
# TODO: Probably refactor this, copied from Click 7.x
|
| 74 |
+
_invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str:
|
| 78 |
+
cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))
|
| 79 |
+
script = _completion_scripts.get(shell)
|
| 80 |
+
if script is None:
|
| 81 |
+
click.echo(f"Shell {shell} not supported.", err=True)
|
| 82 |
+
raise click.exceptions.Exit(1)
|
| 83 |
+
return (
|
| 84 |
+
script
|
| 85 |
+
% {
|
| 86 |
+
"complete_func": f"_{cf_name}_completion",
|
| 87 |
+
"prog_name": prog_name,
|
| 88 |
+
"autocomplete_var": complete_var,
|
| 89 |
+
}
|
| 90 |
+
).strip()
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path:
|
| 94 |
+
# Ref: https://github.com/scop/bash-completion#faq
|
| 95 |
+
# It seems bash-completion is the official completion system for bash:
|
| 96 |
+
# Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html
|
| 97 |
+
# But installing in the locations from the docs doesn't seem to have effect
|
| 98 |
+
completion_path = Path.home() / ".bash_completions" / f"{prog_name}.sh"
|
| 99 |
+
rc_path = Path.home() / ".bashrc"
|
| 100 |
+
rc_path.parent.mkdir(parents=True, exist_ok=True)
|
| 101 |
+
rc_content = ""
|
| 102 |
+
if rc_path.is_file():
|
| 103 |
+
rc_content = rc_path.read_text()
|
| 104 |
+
completion_init_lines = [f"source '{completion_path}'"]
|
| 105 |
+
for line in completion_init_lines:
|
| 106 |
+
if line not in rc_content: # pragma: no cover
|
| 107 |
+
rc_content += f"\n{line}"
|
| 108 |
+
rc_content += "\n"
|
| 109 |
+
rc_path.write_text(rc_content)
|
| 110 |
+
# Install completion
|
| 111 |
+
completion_path.parent.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
script_content = get_completion_script(
|
| 113 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 114 |
+
)
|
| 115 |
+
completion_path.write_text(script_content)
|
| 116 |
+
return completion_path
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path:
|
| 120 |
+
# Setup Zsh and load ~/.zfunc
|
| 121 |
+
zshrc_path = Path.home() / ".zshrc"
|
| 122 |
+
zshrc_path.parent.mkdir(parents=True, exist_ok=True)
|
| 123 |
+
zshrc_content = ""
|
| 124 |
+
if zshrc_path.is_file():
|
| 125 |
+
zshrc_content = zshrc_path.read_text()
|
| 126 |
+
completion_line = "fpath+=~/.zfunc; autoload -Uz compinit; compinit"
|
| 127 |
+
if completion_line not in zshrc_content:
|
| 128 |
+
zshrc_content += f"\n{completion_line}\n"
|
| 129 |
+
style_line = "zstyle ':completion:*' menu select"
|
| 130 |
+
# TODO: consider setting the style only for the current program
|
| 131 |
+
# style_line = f"zstyle ':completion:*:*:{prog_name}:*' menu select"
|
| 132 |
+
# Install zstyle completion config only if the user doesn't have a customization
|
| 133 |
+
if "zstyle" not in zshrc_content:
|
| 134 |
+
zshrc_content += f"\n{style_line}\n"
|
| 135 |
+
zshrc_content = f"{zshrc_content.strip()}\n"
|
| 136 |
+
zshrc_path.write_text(zshrc_content)
|
| 137 |
+
# Install completion under ~/.zfunc/
|
| 138 |
+
path_obj = Path.home() / f".zfunc/_{prog_name}"
|
| 139 |
+
path_obj.parent.mkdir(parents=True, exist_ok=True)
|
| 140 |
+
script_content = get_completion_script(
|
| 141 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 142 |
+
)
|
| 143 |
+
path_obj.write_text(script_content)
|
| 144 |
+
return path_obj
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path:
|
| 148 |
+
path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"
|
| 149 |
+
parent_dir: Path = path_obj.parent
|
| 150 |
+
parent_dir.mkdir(parents=True, exist_ok=True)
|
| 151 |
+
script_content = get_completion_script(
|
| 152 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 153 |
+
)
|
| 154 |
+
path_obj.write_text(f"{script_content}\n")
|
| 155 |
+
return path_obj
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path:
|
| 159 |
+
subprocess.run(
|
| 160 |
+
[
|
| 161 |
+
shell,
|
| 162 |
+
"-Command",
|
| 163 |
+
"Set-ExecutionPolicy",
|
| 164 |
+
"Unrestricted",
|
| 165 |
+
"-Scope",
|
| 166 |
+
"CurrentUser",
|
| 167 |
+
]
|
| 168 |
+
)
|
| 169 |
+
result = subprocess.run(
|
| 170 |
+
[shell, "-NoProfile", "-Command", "echo", "$profile"],
|
| 171 |
+
check=True,
|
| 172 |
+
stdout=subprocess.PIPE,
|
| 173 |
+
)
|
| 174 |
+
if result.returncode != 0: # pragma: no cover
|
| 175 |
+
click.echo("Couldn't get PowerShell user profile", err=True)
|
| 176 |
+
raise click.exceptions.Exit(result.returncode)
|
| 177 |
+
path_str = ""
|
| 178 |
+
if isinstance(result.stdout, str): # pragma: no cover
|
| 179 |
+
path_str = result.stdout
|
| 180 |
+
if isinstance(result.stdout, bytes):
|
| 181 |
+
for encoding in ["windows-1252", "utf8", "cp850"]:
|
| 182 |
+
try:
|
| 183 |
+
path_str = result.stdout.decode(encoding)
|
| 184 |
+
break
|
| 185 |
+
except UnicodeDecodeError: # pragma: no cover
|
| 186 |
+
pass
|
| 187 |
+
if not path_str: # pragma: no cover
|
| 188 |
+
click.echo("Couldn't decode the path automatically", err=True)
|
| 189 |
+
raise click.exceptions.Exit(1)
|
| 190 |
+
path_obj = Path(path_str.strip())
|
| 191 |
+
parent_dir: Path = path_obj.parent
|
| 192 |
+
parent_dir.mkdir(parents=True, exist_ok=True)
|
| 193 |
+
script_content = get_completion_script(
|
| 194 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 195 |
+
)
|
| 196 |
+
with path_obj.open(mode="a") as f:
|
| 197 |
+
f.write(f"{script_content}\n")
|
| 198 |
+
return path_obj
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def install(
|
| 202 |
+
shell: str | None = None,
|
| 203 |
+
prog_name: str | None = None,
|
| 204 |
+
complete_var: str | None = None,
|
| 205 |
+
) -> tuple[str, Path]:
|
| 206 |
+
prog_name = prog_name or click.get_current_context().find_root().info_name
|
| 207 |
+
assert prog_name
|
| 208 |
+
if complete_var is None:
|
| 209 |
+
complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
|
| 210 |
+
test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
|
| 211 |
+
if shell is None and not test_disable_detection:
|
| 212 |
+
shell = _get_shell_name()
|
| 213 |
+
if shell == "bash":
|
| 214 |
+
installed_path = install_bash(
|
| 215 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 216 |
+
)
|
| 217 |
+
return shell, installed_path
|
| 218 |
+
elif shell == "zsh":
|
| 219 |
+
installed_path = install_zsh(
|
| 220 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 221 |
+
)
|
| 222 |
+
return shell, installed_path
|
| 223 |
+
elif shell == "fish":
|
| 224 |
+
installed_path = install_fish(
|
| 225 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 226 |
+
)
|
| 227 |
+
return shell, installed_path
|
| 228 |
+
elif shell in {"powershell", "pwsh"}:
|
| 229 |
+
installed_path = install_powershell(
|
| 230 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 231 |
+
)
|
| 232 |
+
return shell, installed_path
|
| 233 |
+
else:
|
| 234 |
+
click.echo(f"Shell {shell} is not supported.")
|
| 235 |
+
raise click.exceptions.Exit(1)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _get_shell_name() -> str | None:
|
| 239 |
+
"""Get the current shell name, if available.
|
| 240 |
+
|
| 241 |
+
The name will always be lowercase. If the shell cannot be detected, None is
|
| 242 |
+
returned.
|
| 243 |
+
"""
|
| 244 |
+
name: str | None # N.B. shellingham is untyped
|
| 245 |
+
try:
|
| 246 |
+
# N.B. detect_shell returns a tuple of (shell name, shell command).
|
| 247 |
+
# We only need the name.
|
| 248 |
+
name, _cmd = shellingham.detect_shell() # noqa: TID251
|
| 249 |
+
except shellingham.ShellDetectionFailure: # pragma: no cover
|
| 250 |
+
name = None
|
| 251 |
+
|
| 252 |
+
return name
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_types.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from enum import Enum
|
| 2 |
+
from typing import TypeVar
|
| 3 |
+
|
| 4 |
+
import click
|
| 5 |
+
|
| 6 |
+
ParamTypeValue = TypeVar("ParamTypeValue")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class TyperChoice(click.Choice[ParamTypeValue]):
|
| 10 |
+
def normalize_choice(
|
| 11 |
+
self, choice: ParamTypeValue, ctx: click.Context | None
|
| 12 |
+
) -> str:
|
| 13 |
+
# Click 8.2.0 added a new method `normalize_choice` to the `Choice` class
|
| 14 |
+
# to support enums, but it uses the enum names, while Typer has always used the
|
| 15 |
+
# enum values.
|
| 16 |
+
# This class overrides that method to maintain the previous behavior.
|
| 17 |
+
# In Click:
|
| 18 |
+
# normed_value = choice.name if isinstance(choice, Enum) else str(choice)
|
| 19 |
+
normed_value = str(choice.value) if isinstance(choice, Enum) else str(choice)
|
| 20 |
+
|
| 21 |
+
if ctx is not None and ctx.token_normalize_func is not None:
|
| 22 |
+
normed_value = ctx.token_normalize_func(normed_value)
|
| 23 |
+
|
| 24 |
+
if not self.case_sensitive:
|
| 25 |
+
normed_value = normed_value.casefold()
|
| 26 |
+
|
| 27 |
+
return normed_value
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/_typing.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copied from pydantic 1.9.2 (the latest version to support python 3.6.)
|
| 2 |
+
# https://github.com/pydantic/pydantic/blob/v1.9.2/pydantic/typing.py
|
| 3 |
+
# Reduced drastically to only include Typer-specific 3.9+ functionality
|
| 4 |
+
# mypy: ignore-errors
|
| 5 |
+
|
| 6 |
+
import types
|
| 7 |
+
from collections.abc import Callable
|
| 8 |
+
from typing import (
|
| 9 |
+
Annotated,
|
| 10 |
+
Any,
|
| 11 |
+
Literal,
|
| 12 |
+
Union,
|
| 13 |
+
get_args,
|
| 14 |
+
get_origin,
|
| 15 |
+
get_type_hints,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def is_union(tp: type[Any] | None) -> bool:
|
| 20 |
+
return tp is Union or tp is types.UnionType # noqa: E721
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = (
|
| 24 |
+
"NoneType",
|
| 25 |
+
"is_none_type",
|
| 26 |
+
"is_callable_type",
|
| 27 |
+
"is_literal_type",
|
| 28 |
+
"all_literal_values",
|
| 29 |
+
"is_union",
|
| 30 |
+
"Annotated",
|
| 31 |
+
"Literal",
|
| 32 |
+
"get_args",
|
| 33 |
+
"get_origin",
|
| 34 |
+
"get_type_hints",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
NoneType = None.__class__
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
NONE_TYPES: tuple[Any, Any, Any] = (None, NoneType, Literal[None])
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def is_none_type(type_: Any) -> bool:
|
| 45 |
+
for none_type in NONE_TYPES:
|
| 46 |
+
if type_ is none_type:
|
| 47 |
+
return True
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def is_callable_type(type_: type[Any]) -> bool:
|
| 52 |
+
return type_ is Callable or get_origin(type_) is Callable
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def is_literal_type(type_: type[Any]) -> bool:
|
| 56 |
+
return get_origin(type_) is Literal
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def literal_values(type_: type[Any]) -> tuple[Any, ...]:
|
| 60 |
+
return get_args(type_)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def all_literal_values(type_: type[Any]) -> tuple[Any, ...]:
|
| 64 |
+
"""
|
| 65 |
+
This method is used to retrieve all Literal values as
|
| 66 |
+
Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586)
|
| 67 |
+
e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]`
|
| 68 |
+
"""
|
| 69 |
+
if not is_literal_type(type_):
|
| 70 |
+
return (type_,)
|
| 71 |
+
|
| 72 |
+
values = literal_values(type_)
|
| 73 |
+
return tuple(x for value in values for x in all_literal_values(value))
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/cli.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import click
|
| 8 |
+
import typer
|
| 9 |
+
import typer.core
|
| 10 |
+
from click import Command, Group, Option
|
| 11 |
+
|
| 12 |
+
from . import __version__
|
| 13 |
+
from .core import HAS_RICH, MARKUP_MODE_KEY
|
| 14 |
+
|
| 15 |
+
default_app_names = ("app", "cli", "main")
|
| 16 |
+
default_func_names = ("main", "cli", "app")
|
| 17 |
+
|
| 18 |
+
app = typer.Typer()
|
| 19 |
+
utils_app = typer.Typer(help="Extra utility commands for Typer apps.")
|
| 20 |
+
app.add_typer(utils_app, name="utils")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class State:
|
| 24 |
+
def __init__(self) -> None:
|
| 25 |
+
self.app: str | None = None
|
| 26 |
+
self.func: str | None = None
|
| 27 |
+
self.file: Path | None = None
|
| 28 |
+
self.module: str | None = None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
state = State()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def maybe_update_state(ctx: click.Context) -> None:
|
| 35 |
+
path_or_module = ctx.params.get("path_or_module")
|
| 36 |
+
if path_or_module:
|
| 37 |
+
file_path = Path(path_or_module)
|
| 38 |
+
if file_path.exists() and file_path.is_file():
|
| 39 |
+
state.file = file_path
|
| 40 |
+
else:
|
| 41 |
+
if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module):
|
| 42 |
+
typer.echo(
|
| 43 |
+
f"Not a valid file or Python module: {path_or_module}", err=True
|
| 44 |
+
)
|
| 45 |
+
sys.exit(1)
|
| 46 |
+
state.module = path_or_module
|
| 47 |
+
app_name = ctx.params.get("app")
|
| 48 |
+
if app_name:
|
| 49 |
+
state.app = app_name
|
| 50 |
+
func_name = ctx.params.get("func")
|
| 51 |
+
if func_name:
|
| 52 |
+
state.func = func_name
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class TyperCLIGroup(typer.core.TyperGroup):
|
| 56 |
+
def list_commands(self, ctx: click.Context) -> list[str]:
|
| 57 |
+
self.maybe_add_run(ctx)
|
| 58 |
+
return super().list_commands(ctx)
|
| 59 |
+
|
| 60 |
+
def get_command(self, ctx: click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override]
|
| 61 |
+
self.maybe_add_run(ctx)
|
| 62 |
+
return super().get_command(ctx, name)
|
| 63 |
+
|
| 64 |
+
def invoke(self, ctx: click.Context) -> Any:
|
| 65 |
+
self.maybe_add_run(ctx)
|
| 66 |
+
return super().invoke(ctx)
|
| 67 |
+
|
| 68 |
+
def maybe_add_run(self, ctx: click.Context) -> None:
|
| 69 |
+
maybe_update_state(ctx)
|
| 70 |
+
maybe_add_run_to_cli(self)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def get_typer_from_module(module: Any) -> typer.Typer | None:
|
| 74 |
+
# Try to get defined app
|
| 75 |
+
if state.app:
|
| 76 |
+
obj = getattr(module, state.app, None)
|
| 77 |
+
if not isinstance(obj, typer.Typer):
|
| 78 |
+
typer.echo(f"Not a Typer object: --app {state.app}", err=True)
|
| 79 |
+
sys.exit(1)
|
| 80 |
+
return obj
|
| 81 |
+
# Try to get defined function
|
| 82 |
+
if state.func:
|
| 83 |
+
func_obj = getattr(module, state.func, None)
|
| 84 |
+
if not callable(func_obj):
|
| 85 |
+
typer.echo(f"Not a function: --func {state.func}", err=True)
|
| 86 |
+
raise typer.Exit(1)
|
| 87 |
+
sub_app = typer.Typer()
|
| 88 |
+
sub_app.command()(func_obj)
|
| 89 |
+
return sub_app
|
| 90 |
+
# Iterate and get a default object to use as CLI
|
| 91 |
+
local_names = dir(module)
|
| 92 |
+
local_names_set = set(local_names)
|
| 93 |
+
# Try to get a default Typer app
|
| 94 |
+
for name in default_app_names:
|
| 95 |
+
if name in local_names_set:
|
| 96 |
+
obj = getattr(module, name, None)
|
| 97 |
+
if isinstance(obj, typer.Typer):
|
| 98 |
+
return obj
|
| 99 |
+
# Try to get any Typer app
|
| 100 |
+
for name in local_names_set - set(default_app_names):
|
| 101 |
+
obj = getattr(module, name)
|
| 102 |
+
if isinstance(obj, typer.Typer):
|
| 103 |
+
return obj
|
| 104 |
+
# Try to get a default function
|
| 105 |
+
for func_name in default_func_names:
|
| 106 |
+
func_obj = getattr(module, func_name, None)
|
| 107 |
+
if callable(func_obj):
|
| 108 |
+
sub_app = typer.Typer()
|
| 109 |
+
sub_app.command()(func_obj)
|
| 110 |
+
return sub_app
|
| 111 |
+
# Try to get any func app
|
| 112 |
+
for func_name in local_names_set - set(default_func_names):
|
| 113 |
+
func_obj = getattr(module, func_name)
|
| 114 |
+
if callable(func_obj):
|
| 115 |
+
sub_app = typer.Typer()
|
| 116 |
+
sub_app.command()(func_obj)
|
| 117 |
+
return sub_app
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def get_typer_from_state() -> typer.Typer | None:
|
| 122 |
+
spec = None
|
| 123 |
+
if state.file:
|
| 124 |
+
module_name = state.file.name
|
| 125 |
+
spec = importlib.util.spec_from_file_location(module_name, str(state.file))
|
| 126 |
+
elif state.module:
|
| 127 |
+
spec = importlib.util.find_spec(state.module)
|
| 128 |
+
if spec is None:
|
| 129 |
+
if state.file:
|
| 130 |
+
typer.echo(f"Could not import as Python file: {state.file}", err=True)
|
| 131 |
+
else:
|
| 132 |
+
typer.echo(f"Could not import as Python module: {state.module}", err=True)
|
| 133 |
+
sys.exit(1)
|
| 134 |
+
module = importlib.util.module_from_spec(spec)
|
| 135 |
+
spec.loader.exec_module(module) # type: ignore
|
| 136 |
+
obj = get_typer_from_module(module)
|
| 137 |
+
return obj
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def maybe_add_run_to_cli(cli: click.Group) -> None:
|
| 141 |
+
if "run" not in cli.commands:
|
| 142 |
+
if state.file or state.module:
|
| 143 |
+
obj = get_typer_from_state()
|
| 144 |
+
if obj:
|
| 145 |
+
obj._add_completion = False
|
| 146 |
+
click_obj = typer.main.get_command(obj)
|
| 147 |
+
click_obj.name = "run"
|
| 148 |
+
if not click_obj.help:
|
| 149 |
+
click_obj.help = "Run the provided Typer app."
|
| 150 |
+
cli.add_command(click_obj)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def print_version(ctx: click.Context, param: Option, value: bool) -> None:
|
| 154 |
+
if not value or ctx.resilient_parsing:
|
| 155 |
+
return
|
| 156 |
+
typer.echo(f"Typer version: {__version__}")
|
| 157 |
+
raise typer.Exit()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@app.callback(cls=TyperCLIGroup, no_args_is_help=True)
|
| 161 |
+
def callback(
|
| 162 |
+
ctx: typer.Context,
|
| 163 |
+
*,
|
| 164 |
+
path_or_module: str = typer.Argument(None),
|
| 165 |
+
app: str = typer.Option(None, help="The typer app object/variable to use."),
|
| 166 |
+
func: str = typer.Option(None, help="The function to convert to Typer."),
|
| 167 |
+
version: bool = typer.Option(
|
| 168 |
+
False,
|
| 169 |
+
"--version",
|
| 170 |
+
help="Print version and exit.",
|
| 171 |
+
callback=print_version,
|
| 172 |
+
),
|
| 173 |
+
) -> None:
|
| 174 |
+
"""
|
| 175 |
+
Run Typer scripts with completion, without having to create a package.
|
| 176 |
+
|
| 177 |
+
You probably want to install completion for the typer command:
|
| 178 |
+
|
| 179 |
+
$ typer --install-completion
|
| 180 |
+
|
| 181 |
+
https://typer.tiangolo.com/
|
| 182 |
+
"""
|
| 183 |
+
maybe_update_state(ctx)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def get_docs_for_click(
|
| 187 |
+
*,
|
| 188 |
+
obj: Command,
|
| 189 |
+
ctx: typer.Context,
|
| 190 |
+
indent: int = 0,
|
| 191 |
+
name: str = "",
|
| 192 |
+
call_prefix: str = "",
|
| 193 |
+
title: str | None = None,
|
| 194 |
+
) -> str:
|
| 195 |
+
docs = "#" * (1 + indent)
|
| 196 |
+
command_name = name or obj.name
|
| 197 |
+
if call_prefix:
|
| 198 |
+
command_name = f"{call_prefix} {command_name}"
|
| 199 |
+
if not title:
|
| 200 |
+
title = f"`{command_name}`" if command_name else "CLI"
|
| 201 |
+
docs += f" {title}\n\n"
|
| 202 |
+
rich_markup_mode = None
|
| 203 |
+
if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
|
| 204 |
+
rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
|
| 205 |
+
to_parse: bool = bool(HAS_RICH and (rich_markup_mode == "rich"))
|
| 206 |
+
if obj.help:
|
| 207 |
+
docs += f"{_parse_html(to_parse, obj.help)}\n\n"
|
| 208 |
+
usage_pieces = obj.collect_usage_pieces(ctx)
|
| 209 |
+
if usage_pieces:
|
| 210 |
+
docs += "**Usage**:\n\n"
|
| 211 |
+
docs += "```console\n"
|
| 212 |
+
docs += "$ "
|
| 213 |
+
if command_name:
|
| 214 |
+
docs += f"{command_name} "
|
| 215 |
+
docs += f"{' '.join(usage_pieces)}\n"
|
| 216 |
+
docs += "```\n\n"
|
| 217 |
+
args = []
|
| 218 |
+
opts = []
|
| 219 |
+
for param in obj.get_params(ctx):
|
| 220 |
+
rv = param.get_help_record(ctx)
|
| 221 |
+
if rv is not None:
|
| 222 |
+
if param.param_type_name == "argument":
|
| 223 |
+
args.append(rv)
|
| 224 |
+
elif param.param_type_name == "option":
|
| 225 |
+
opts.append(rv)
|
| 226 |
+
if args:
|
| 227 |
+
docs += "**Arguments**:\n\n"
|
| 228 |
+
for arg_name, arg_help in args:
|
| 229 |
+
docs += f"* `{arg_name}`"
|
| 230 |
+
if arg_help:
|
| 231 |
+
docs += f": {_parse_html(to_parse, arg_help)}"
|
| 232 |
+
docs += "\n"
|
| 233 |
+
docs += "\n"
|
| 234 |
+
if opts:
|
| 235 |
+
docs += "**Options**:\n\n"
|
| 236 |
+
for opt_name, opt_help in opts:
|
| 237 |
+
docs += f"* `{opt_name}`"
|
| 238 |
+
if opt_help:
|
| 239 |
+
docs += f": {_parse_html(to_parse, opt_help)}"
|
| 240 |
+
docs += "\n"
|
| 241 |
+
docs += "\n"
|
| 242 |
+
if obj.epilog:
|
| 243 |
+
docs += f"{obj.epilog}\n\n"
|
| 244 |
+
if isinstance(obj, Group):
|
| 245 |
+
group = obj
|
| 246 |
+
commands = group.list_commands(ctx)
|
| 247 |
+
if commands:
|
| 248 |
+
docs += "**Commands**:\n\n"
|
| 249 |
+
for command in commands:
|
| 250 |
+
command_obj = group.get_command(ctx, command)
|
| 251 |
+
assert command_obj
|
| 252 |
+
docs += f"* `{command_obj.name}`"
|
| 253 |
+
command_help = command_obj.get_short_help_str()
|
| 254 |
+
if command_help:
|
| 255 |
+
docs += f": {_parse_html(to_parse, command_help)}"
|
| 256 |
+
docs += "\n"
|
| 257 |
+
docs += "\n"
|
| 258 |
+
for command in commands:
|
| 259 |
+
command_obj = group.get_command(ctx, command)
|
| 260 |
+
assert command_obj
|
| 261 |
+
use_prefix = ""
|
| 262 |
+
if command_name:
|
| 263 |
+
use_prefix += f"{command_name}"
|
| 264 |
+
docs += get_docs_for_click(
|
| 265 |
+
obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix
|
| 266 |
+
)
|
| 267 |
+
return docs
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _parse_html(to_parse: bool, input_text: str) -> str:
|
| 271 |
+
if not to_parse:
|
| 272 |
+
return input_text
|
| 273 |
+
from . import rich_utils
|
| 274 |
+
|
| 275 |
+
return rich_utils.rich_to_html(input_text)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@utils_app.command()
|
| 279 |
+
def docs(
|
| 280 |
+
ctx: typer.Context,
|
| 281 |
+
name: str = typer.Option("", help="The name of the CLI program to use in docs."),
|
| 282 |
+
output: Path | None = typer.Option(
|
| 283 |
+
None,
|
| 284 |
+
help="An output file to write docs to, like README.md.",
|
| 285 |
+
file_okay=True,
|
| 286 |
+
dir_okay=False,
|
| 287 |
+
),
|
| 288 |
+
title: str | None = typer.Option(
|
| 289 |
+
None,
|
| 290 |
+
help="The title for the documentation page. If not provided, the name of "
|
| 291 |
+
"the program is used.",
|
| 292 |
+
),
|
| 293 |
+
) -> None:
|
| 294 |
+
"""
|
| 295 |
+
Generate Markdown docs for a Typer app.
|
| 296 |
+
"""
|
| 297 |
+
typer_obj = get_typer_from_state()
|
| 298 |
+
if not typer_obj:
|
| 299 |
+
typer.echo("No Typer app found", err=True)
|
| 300 |
+
raise typer.Abort()
|
| 301 |
+
if hasattr(typer_obj, "rich_markup_mode"):
|
| 302 |
+
if not hasattr(ctx, "obj") or ctx.obj is None:
|
| 303 |
+
ctx.ensure_object(dict)
|
| 304 |
+
if isinstance(ctx.obj, dict):
|
| 305 |
+
ctx.obj[MARKUP_MODE_KEY] = typer_obj.rich_markup_mode
|
| 306 |
+
click_obj = typer.main.get_command(typer_obj)
|
| 307 |
+
docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title)
|
| 308 |
+
clean_docs = f"{docs.strip()}\n"
|
| 309 |
+
if output:
|
| 310 |
+
output.write_text(clean_docs)
|
| 311 |
+
typer.echo(f"Docs saved to: {output}")
|
| 312 |
+
else:
|
| 313 |
+
typer.echo(clean_docs)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def main() -> Any:
|
| 317 |
+
return app()
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/colors.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Variable names to colors, just for completion
|
| 2 |
+
BLACK = "black"
|
| 3 |
+
RED = "red"
|
| 4 |
+
GREEN = "green"
|
| 5 |
+
YELLOW = "yellow"
|
| 6 |
+
BLUE = "blue"
|
| 7 |
+
MAGENTA = "magenta"
|
| 8 |
+
CYAN = "cyan"
|
| 9 |
+
WHITE = "white"
|
| 10 |
+
|
| 11 |
+
RESET = "reset"
|
| 12 |
+
|
| 13 |
+
BRIGHT_BLACK = "bright_black"
|
| 14 |
+
BRIGHT_RED = "bright_red"
|
| 15 |
+
BRIGHT_GREEN = "bright_green"
|
| 16 |
+
BRIGHT_YELLOW = "bright_yellow"
|
| 17 |
+
BRIGHT_BLUE = "bright_blue"
|
| 18 |
+
BRIGHT_MAGENTA = "bright_magenta"
|
| 19 |
+
BRIGHT_CYAN = "bright_cyan"
|
| 20 |
+
BRIGHT_WHITE = "bright_white"
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/completion.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from collections.abc import MutableMapping
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import click
|
| 7 |
+
|
| 8 |
+
from ._completion_classes import completion_init
|
| 9 |
+
from ._completion_shared import Shells, _get_shell_name, get_completion_script, install
|
| 10 |
+
from .models import ParamMeta
|
| 11 |
+
from .params import Option
|
| 12 |
+
from .utils import get_params_from_function
|
| 13 |
+
|
| 14 |
+
_click_patched = False
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_completion_inspect_parameters() -> tuple[ParamMeta, ParamMeta]:
|
| 18 |
+
completion_init()
|
| 19 |
+
test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
|
| 20 |
+
if not test_disable_detection:
|
| 21 |
+
parameters = get_params_from_function(_install_completion_placeholder_function)
|
| 22 |
+
else:
|
| 23 |
+
parameters = get_params_from_function(
|
| 24 |
+
_install_completion_no_auto_placeholder_function
|
| 25 |
+
)
|
| 26 |
+
install_param, show_param = parameters.values()
|
| 27 |
+
return install_param, show_param
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
|
| 31 |
+
if not value or ctx.resilient_parsing:
|
| 32 |
+
return value # pragma: no cover
|
| 33 |
+
if isinstance(value, str):
|
| 34 |
+
shell, path = install(shell=value)
|
| 35 |
+
else:
|
| 36 |
+
shell, path = install()
|
| 37 |
+
click.secho(f"{shell} completion installed in {path}", fg="green")
|
| 38 |
+
click.echo("Completion will take effect once you restart the terminal")
|
| 39 |
+
sys.exit(0)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
|
| 43 |
+
if not value or ctx.resilient_parsing:
|
| 44 |
+
return value # pragma: no cover
|
| 45 |
+
prog_name = ctx.find_root().info_name
|
| 46 |
+
assert prog_name
|
| 47 |
+
complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
|
| 48 |
+
shell = ""
|
| 49 |
+
test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
|
| 50 |
+
if isinstance(value, str):
|
| 51 |
+
shell = value
|
| 52 |
+
elif not test_disable_detection:
|
| 53 |
+
detected_shell = _get_shell_name()
|
| 54 |
+
if detected_shell is not None:
|
| 55 |
+
shell = detected_shell
|
| 56 |
+
script_content = get_completion_script(
|
| 57 |
+
prog_name=prog_name, complete_var=complete_var, shell=shell
|
| 58 |
+
)
|
| 59 |
+
click.echo(script_content)
|
| 60 |
+
sys.exit(0)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Create a fake command function to extract the completion parameters
|
| 64 |
+
def _install_completion_placeholder_function(
|
| 65 |
+
install_completion: bool = Option(
|
| 66 |
+
None,
|
| 67 |
+
"--install-completion",
|
| 68 |
+
callback=install_callback,
|
| 69 |
+
expose_value=False,
|
| 70 |
+
help="Install completion for the current shell.",
|
| 71 |
+
),
|
| 72 |
+
show_completion: bool = Option(
|
| 73 |
+
None,
|
| 74 |
+
"--show-completion",
|
| 75 |
+
callback=show_callback,
|
| 76 |
+
expose_value=False,
|
| 77 |
+
help="Show completion for the current shell, to copy it or customize the installation.",
|
| 78 |
+
),
|
| 79 |
+
) -> Any:
|
| 80 |
+
pass # pragma: no cover
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _install_completion_no_auto_placeholder_function(
|
| 84 |
+
install_completion: Shells = Option(
|
| 85 |
+
None,
|
| 86 |
+
callback=install_callback,
|
| 87 |
+
expose_value=False,
|
| 88 |
+
help="Install completion for the specified shell.",
|
| 89 |
+
),
|
| 90 |
+
show_completion: Shells = Option(
|
| 91 |
+
None,
|
| 92 |
+
callback=show_callback,
|
| 93 |
+
expose_value=False,
|
| 94 |
+
help="Show completion for the specified shell, to copy it or customize the installation.",
|
| 95 |
+
),
|
| 96 |
+
) -> Any:
|
| 97 |
+
pass # pragma: no cover
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# Re-implement Click's shell_complete to add error message with:
|
| 101 |
+
# Invalid completion instruction
|
| 102 |
+
# To use 7.x instruction style for compatibility
|
| 103 |
+
# And to add extra error messages, for compatibility with Typer in previous versions
|
| 104 |
+
# This is only called in new Command method, only used by Click 8.x+
|
| 105 |
+
def shell_complete(
|
| 106 |
+
cli: click.Command,
|
| 107 |
+
ctx_args: MutableMapping[str, Any],
|
| 108 |
+
prog_name: str,
|
| 109 |
+
complete_var: str,
|
| 110 |
+
instruction: str,
|
| 111 |
+
) -> int:
|
| 112 |
+
import click
|
| 113 |
+
import click.shell_completion
|
| 114 |
+
|
| 115 |
+
if "_" not in instruction:
|
| 116 |
+
click.echo("Invalid completion instruction.", err=True)
|
| 117 |
+
return 1
|
| 118 |
+
|
| 119 |
+
# Click 8 changed the order/style of shell instructions from e.g.
|
| 120 |
+
# source_bash to bash_source
|
| 121 |
+
# Typer override to preserve the old style for compatibility
|
| 122 |
+
# Original in Click 8.x commented:
|
| 123 |
+
# shell, _, instruction = instruction.partition("_")
|
| 124 |
+
instruction, _, shell = instruction.partition("_")
|
| 125 |
+
# Typer override end
|
| 126 |
+
|
| 127 |
+
comp_cls = click.shell_completion.get_completion_class(shell)
|
| 128 |
+
|
| 129 |
+
if comp_cls is None:
|
| 130 |
+
click.echo(f"Shell {shell} not supported.", err=True)
|
| 131 |
+
return 1
|
| 132 |
+
|
| 133 |
+
comp = comp_cls(cli, ctx_args, prog_name, complete_var)
|
| 134 |
+
|
| 135 |
+
if instruction == "source":
|
| 136 |
+
click.echo(comp.source())
|
| 137 |
+
return 0
|
| 138 |
+
|
| 139 |
+
# Typer override to print the completion help msg with Rich
|
| 140 |
+
if instruction == "complete":
|
| 141 |
+
click.echo(comp.complete())
|
| 142 |
+
return 0
|
| 143 |
+
# Typer override end
|
| 144 |
+
|
| 145 |
+
click.echo(f'Completion instruction "{instruction}" not supported.', err=True)
|
| 146 |
+
return 1
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/core.py
ADDED
|
@@ -0,0 +1,821 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import errno
|
| 2 |
+
import inspect
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
from collections.abc import Callable, MutableMapping, Sequence
|
| 6 |
+
from difflib import get_close_matches
|
| 7 |
+
from enum import Enum
|
| 8 |
+
from gettext import gettext as _
|
| 9 |
+
from typing import (
|
| 10 |
+
Any,
|
| 11 |
+
TextIO,
|
| 12 |
+
Union,
|
| 13 |
+
cast,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
import click
|
| 17 |
+
import click.core
|
| 18 |
+
import click.formatting
|
| 19 |
+
import click.shell_completion
|
| 20 |
+
import click.types
|
| 21 |
+
import click.utils
|
| 22 |
+
|
| 23 |
+
from ._typing import Literal
|
| 24 |
+
from .utils import parse_boolean_env_var
|
| 25 |
+
|
| 26 |
+
MarkupMode = Literal["markdown", "rich", None]
|
| 27 |
+
MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"
|
| 28 |
+
|
| 29 |
+
HAS_RICH = parse_boolean_env_var(os.getenv("TYPER_USE_RICH"), default=True)
|
| 30 |
+
|
| 31 |
+
if HAS_RICH:
|
| 32 |
+
DEFAULT_MARKUP_MODE: MarkupMode = "rich"
|
| 33 |
+
else:
|
| 34 |
+
DEFAULT_MARKUP_MODE = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Copy from click.parser._split_opt
|
| 38 |
+
def _split_opt(opt: str) -> tuple[str, str]:
|
| 39 |
+
first = opt[:1]
|
| 40 |
+
if first.isalnum():
|
| 41 |
+
return "", opt
|
| 42 |
+
if opt[1:2] == first:
|
| 43 |
+
return opt[:2], opt[2:]
|
| 44 |
+
return first, opt[1:]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _typer_param_setup_autocompletion_compat(
|
| 48 |
+
self: click.Parameter,
|
| 49 |
+
*,
|
| 50 |
+
autocompletion: Callable[
|
| 51 |
+
[click.Context, list[str], str], list[tuple[str, str] | str]
|
| 52 |
+
]
|
| 53 |
+
| None = None,
|
| 54 |
+
) -> None:
|
| 55 |
+
if self._custom_shell_complete is not None:
|
| 56 |
+
import warnings
|
| 57 |
+
|
| 58 |
+
warnings.warn(
|
| 59 |
+
"In Typer, only the parameter 'autocompletion' is supported. "
|
| 60 |
+
"The support for 'shell_complete' is deprecated and will be removed in upcoming versions. ",
|
| 61 |
+
DeprecationWarning,
|
| 62 |
+
stacklevel=2,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
if autocompletion is not None:
|
| 66 |
+
|
| 67 |
+
def compat_autocompletion(
|
| 68 |
+
ctx: click.Context, param: click.core.Parameter, incomplete: str
|
| 69 |
+
) -> list["click.shell_completion.CompletionItem"]:
|
| 70 |
+
from click.shell_completion import CompletionItem
|
| 71 |
+
|
| 72 |
+
out = []
|
| 73 |
+
|
| 74 |
+
for c in autocompletion(ctx, [], incomplete):
|
| 75 |
+
if isinstance(c, tuple):
|
| 76 |
+
use_completion = CompletionItem(c[0], help=c[1])
|
| 77 |
+
else:
|
| 78 |
+
assert isinstance(c, str)
|
| 79 |
+
use_completion = CompletionItem(c)
|
| 80 |
+
|
| 81 |
+
if use_completion.value.startswith(incomplete):
|
| 82 |
+
out.append(use_completion)
|
| 83 |
+
|
| 84 |
+
return out
|
| 85 |
+
|
| 86 |
+
self._custom_shell_complete = compat_autocompletion
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _get_default_string(
|
| 90 |
+
obj: Union["TyperArgument", "TyperOption"],
|
| 91 |
+
*,
|
| 92 |
+
ctx: click.Context,
|
| 93 |
+
show_default_is_str: bool,
|
| 94 |
+
default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
|
| 95 |
+
) -> str:
|
| 96 |
+
# Extracted from click.core.Option.get_help_record() to be reused by
|
| 97 |
+
# rich_utils avoiding RegEx hacks
|
| 98 |
+
if show_default_is_str:
|
| 99 |
+
default_string = f"({obj.show_default})"
|
| 100 |
+
elif isinstance(default_value, (list, tuple)):
|
| 101 |
+
default_string = ", ".join(
|
| 102 |
+
_get_default_string(
|
| 103 |
+
obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d
|
| 104 |
+
)
|
| 105 |
+
for d in default_value
|
| 106 |
+
)
|
| 107 |
+
elif isinstance(default_value, Enum):
|
| 108 |
+
default_string = str(default_value.value)
|
| 109 |
+
elif inspect.isfunction(default_value):
|
| 110 |
+
default_string = _("(dynamic)")
|
| 111 |
+
elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts:
|
| 112 |
+
# For boolean flags that have distinct True/False opts,
|
| 113 |
+
# use the opt without prefix instead of the value.
|
| 114 |
+
# Typer override, original commented
|
| 115 |
+
# default_string = click.parser.split_opt(
|
| 116 |
+
# (self.opts if self.default else self.secondary_opts)[0]
|
| 117 |
+
# )[1]
|
| 118 |
+
if obj.default:
|
| 119 |
+
if obj.opts:
|
| 120 |
+
default_string = _split_opt(obj.opts[0])[1]
|
| 121 |
+
else:
|
| 122 |
+
default_string = str(default_value)
|
| 123 |
+
else:
|
| 124 |
+
default_string = _split_opt(obj.secondary_opts[0])[1]
|
| 125 |
+
# Typer override end
|
| 126 |
+
elif (
|
| 127 |
+
isinstance(obj, TyperOption)
|
| 128 |
+
and obj.is_bool_flag
|
| 129 |
+
and not obj.secondary_opts
|
| 130 |
+
and not default_value
|
| 131 |
+
):
|
| 132 |
+
default_string = ""
|
| 133 |
+
else:
|
| 134 |
+
default_string = str(default_value)
|
| 135 |
+
return default_string
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _extract_default_help_str(
|
| 139 |
+
obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context
|
| 140 |
+
) -> Any | Callable[[], Any] | None:
|
| 141 |
+
# Extracted from click.core.Option.get_help_record() to be reused by
|
| 142 |
+
# rich_utils avoiding RegEx hacks
|
| 143 |
+
# Temporarily enable resilient parsing to avoid type casting
|
| 144 |
+
# failing for the default. Might be possible to extend this to
|
| 145 |
+
# help formatting in general.
|
| 146 |
+
resilient = ctx.resilient_parsing
|
| 147 |
+
ctx.resilient_parsing = True
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
default_value = obj.get_default(ctx, call=False)
|
| 151 |
+
finally:
|
| 152 |
+
ctx.resilient_parsing = resilient
|
| 153 |
+
return default_value
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _main(
|
| 157 |
+
self: click.Command,
|
| 158 |
+
*,
|
| 159 |
+
args: Sequence[str] | None = None,
|
| 160 |
+
prog_name: str | None = None,
|
| 161 |
+
complete_var: str | None = None,
|
| 162 |
+
standalone_mode: bool = True,
|
| 163 |
+
windows_expand_args: bool = True,
|
| 164 |
+
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
|
| 165 |
+
**extra: Any,
|
| 166 |
+
) -> Any:
|
| 167 |
+
# Typer override, duplicated from click.main() to handle custom rich exceptions
|
| 168 |
+
# Verify that the environment is configured correctly, or reject
|
| 169 |
+
# further execution to avoid a broken script.
|
| 170 |
+
if args is None:
|
| 171 |
+
args = sys.argv[1:]
|
| 172 |
+
|
| 173 |
+
# Covered in Click tests
|
| 174 |
+
if os.name == "nt" and windows_expand_args: # pragma: no cover
|
| 175 |
+
args = click.utils._expand_args(args)
|
| 176 |
+
else:
|
| 177 |
+
args = list(args)
|
| 178 |
+
|
| 179 |
+
if prog_name is None:
|
| 180 |
+
prog_name = click.utils._detect_program_name()
|
| 181 |
+
|
| 182 |
+
# Process shell completion requests and exit early.
|
| 183 |
+
self._main_shell_completion(extra, prog_name, complete_var)
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
try:
|
| 187 |
+
with self.make_context(prog_name, args, **extra) as ctx:
|
| 188 |
+
rv = self.invoke(ctx)
|
| 189 |
+
if not standalone_mode:
|
| 190 |
+
return rv
|
| 191 |
+
# it's not safe to `ctx.exit(rv)` here!
|
| 192 |
+
# note that `rv` may actually contain data like "1" which
|
| 193 |
+
# has obvious effects
|
| 194 |
+
# more subtle case: `rv=[None, None]` can come out of
|
| 195 |
+
# chained commands which all returned `None` -- so it's not
|
| 196 |
+
# even always obvious that `rv` indicates success/failure
|
| 197 |
+
# by its truthiness/falsiness
|
| 198 |
+
ctx.exit()
|
| 199 |
+
except EOFError as e:
|
| 200 |
+
click.echo(file=sys.stderr)
|
| 201 |
+
raise click.Abort() from e
|
| 202 |
+
except KeyboardInterrupt as e:
|
| 203 |
+
raise click.exceptions.Exit(130) from e
|
| 204 |
+
except click.ClickException as e:
|
| 205 |
+
if not standalone_mode:
|
| 206 |
+
raise
|
| 207 |
+
# Typer override
|
| 208 |
+
if HAS_RICH and rich_markup_mode is not None:
|
| 209 |
+
from . import rich_utils
|
| 210 |
+
|
| 211 |
+
rich_utils.rich_format_error(e)
|
| 212 |
+
else:
|
| 213 |
+
e.show()
|
| 214 |
+
# Typer override end
|
| 215 |
+
sys.exit(e.exit_code)
|
| 216 |
+
except OSError as e:
|
| 217 |
+
if e.errno == errno.EPIPE:
|
| 218 |
+
sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout))
|
| 219 |
+
sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr))
|
| 220 |
+
sys.exit(1)
|
| 221 |
+
else:
|
| 222 |
+
raise
|
| 223 |
+
except click.exceptions.Exit as e:
|
| 224 |
+
if standalone_mode:
|
| 225 |
+
sys.exit(e.exit_code)
|
| 226 |
+
else:
|
| 227 |
+
# in non-standalone mode, return the exit code
|
| 228 |
+
# note that this is only reached if `self.invoke` above raises
|
| 229 |
+
# an Exit explicitly -- thus bypassing the check there which
|
| 230 |
+
# would return its result
|
| 231 |
+
# the results of non-standalone execution may therefore be
|
| 232 |
+
# somewhat ambiguous: if there are codepaths which lead to
|
| 233 |
+
# `ctx.exit(1)` and to `return 1`, the caller won't be able to
|
| 234 |
+
# tell the difference between the two
|
| 235 |
+
return e.exit_code
|
| 236 |
+
except click.Abort:
|
| 237 |
+
if not standalone_mode:
|
| 238 |
+
raise
|
| 239 |
+
# Typer override
|
| 240 |
+
if HAS_RICH and rich_markup_mode is not None:
|
| 241 |
+
from . import rich_utils
|
| 242 |
+
|
| 243 |
+
rich_utils.rich_abort_error()
|
| 244 |
+
else:
|
| 245 |
+
click.echo(_("Aborted!"), file=sys.stderr)
|
| 246 |
+
# Typer override end
|
| 247 |
+
sys.exit(1)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class TyperArgument(click.core.Argument):
|
| 251 |
+
def __init__(
|
| 252 |
+
self,
|
| 253 |
+
*,
|
| 254 |
+
# Parameter
|
| 255 |
+
param_decls: list[str],
|
| 256 |
+
type: Any | None = None,
|
| 257 |
+
required: bool | None = None,
|
| 258 |
+
default: Any | None = None,
|
| 259 |
+
callback: Callable[..., Any] | None = None,
|
| 260 |
+
nargs: int | None = None,
|
| 261 |
+
metavar: str | None = None,
|
| 262 |
+
expose_value: bool = True,
|
| 263 |
+
is_eager: bool = False,
|
| 264 |
+
envvar: str | list[str] | None = None,
|
| 265 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 266 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 267 |
+
shell_complete: Callable[
|
| 268 |
+
[click.Context, click.Parameter, str],
|
| 269 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 270 |
+
]
|
| 271 |
+
| None = None,
|
| 272 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 273 |
+
# TyperArgument
|
| 274 |
+
show_default: bool | str = True,
|
| 275 |
+
show_choices: bool = True,
|
| 276 |
+
show_envvar: bool = True,
|
| 277 |
+
help: str | None = None,
|
| 278 |
+
hidden: bool = False,
|
| 279 |
+
# Rich settings
|
| 280 |
+
rich_help_panel: str | None = None,
|
| 281 |
+
):
|
| 282 |
+
self.help = help
|
| 283 |
+
self.show_default = show_default
|
| 284 |
+
self.show_choices = show_choices
|
| 285 |
+
self.show_envvar = show_envvar
|
| 286 |
+
self.hidden = hidden
|
| 287 |
+
self.rich_help_panel = rich_help_panel
|
| 288 |
+
|
| 289 |
+
super().__init__(
|
| 290 |
+
param_decls=param_decls,
|
| 291 |
+
type=type,
|
| 292 |
+
required=required,
|
| 293 |
+
default=default,
|
| 294 |
+
callback=callback,
|
| 295 |
+
nargs=nargs,
|
| 296 |
+
metavar=metavar,
|
| 297 |
+
expose_value=expose_value,
|
| 298 |
+
is_eager=is_eager,
|
| 299 |
+
envvar=envvar,
|
| 300 |
+
shell_complete=shell_complete,
|
| 301 |
+
)
|
| 302 |
+
_typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
|
| 303 |
+
|
| 304 |
+
def _get_default_string(
|
| 305 |
+
self,
|
| 306 |
+
*,
|
| 307 |
+
ctx: click.Context,
|
| 308 |
+
show_default_is_str: bool,
|
| 309 |
+
default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
|
| 310 |
+
) -> str:
|
| 311 |
+
return _get_default_string(
|
| 312 |
+
self,
|
| 313 |
+
ctx=ctx,
|
| 314 |
+
show_default_is_str=show_default_is_str,
|
| 315 |
+
default_value=default_value,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
def _extract_default_help_str(
|
| 319 |
+
self, *, ctx: click.Context
|
| 320 |
+
) -> Any | Callable[[], Any] | None:
|
| 321 |
+
return _extract_default_help_str(self, ctx=ctx)
|
| 322 |
+
|
| 323 |
+
def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
|
| 324 |
+
# Modified version of click.core.Option.get_help_record()
|
| 325 |
+
# to support Arguments
|
| 326 |
+
if self.hidden:
|
| 327 |
+
return None
|
| 328 |
+
name = self.make_metavar(ctx=ctx)
|
| 329 |
+
help = self.help or ""
|
| 330 |
+
extra = []
|
| 331 |
+
if self.show_envvar:
|
| 332 |
+
envvar = self.envvar
|
| 333 |
+
# allow_from_autoenv is currently not supported in Typer for CLI Arguments
|
| 334 |
+
if envvar is not None:
|
| 335 |
+
var_str = (
|
| 336 |
+
", ".join(str(d) for d in envvar)
|
| 337 |
+
if isinstance(envvar, (list, tuple))
|
| 338 |
+
else envvar
|
| 339 |
+
)
|
| 340 |
+
extra.append(f"env var: {var_str}")
|
| 341 |
+
|
| 342 |
+
# Typer override:
|
| 343 |
+
# Extracted to _extract_default_help_str() to allow re-using it in rich_utils
|
| 344 |
+
default_value = self._extract_default_help_str(ctx=ctx)
|
| 345 |
+
# Typer override end
|
| 346 |
+
|
| 347 |
+
show_default_is_str = isinstance(self.show_default, str)
|
| 348 |
+
|
| 349 |
+
if show_default_is_str or (
|
| 350 |
+
default_value is not None and (self.show_default or ctx.show_default)
|
| 351 |
+
):
|
| 352 |
+
# Typer override:
|
| 353 |
+
# Extracted to _get_default_string() to allow re-using it in rich_utils
|
| 354 |
+
default_string = self._get_default_string(
|
| 355 |
+
ctx=ctx,
|
| 356 |
+
show_default_is_str=show_default_is_str,
|
| 357 |
+
default_value=default_value,
|
| 358 |
+
)
|
| 359 |
+
# Typer override end
|
| 360 |
+
if default_string:
|
| 361 |
+
extra.append(_("default: {default}").format(default=default_string))
|
| 362 |
+
if self.required:
|
| 363 |
+
extra.append(_("required"))
|
| 364 |
+
if extra:
|
| 365 |
+
extra_str = "; ".join(extra)
|
| 366 |
+
extra_str = f"[{extra_str}]"
|
| 367 |
+
rich_markup_mode = None
|
| 368 |
+
if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
|
| 369 |
+
rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
|
| 370 |
+
if HAS_RICH and rich_markup_mode == "rich":
|
| 371 |
+
# This is needed for when we want to export to HTML
|
| 372 |
+
from . import rich_utils
|
| 373 |
+
|
| 374 |
+
extra_str = rich_utils.escape_before_html_export(extra_str)
|
| 375 |
+
|
| 376 |
+
help = f"{help} {extra_str}" if help else f"{extra_str}"
|
| 377 |
+
return name, help
|
| 378 |
+
|
| 379 |
+
def make_metavar(self, ctx: click.Context | None = None) -> str:
|
| 380 |
+
# Modified version of click.core.Argument.make_metavar()
|
| 381 |
+
# to include Argument name
|
| 382 |
+
if self.metavar is not None:
|
| 383 |
+
var = self.metavar
|
| 384 |
+
if not self.required and not var.startswith("["):
|
| 385 |
+
var = f"[{var}]"
|
| 386 |
+
return var
|
| 387 |
+
var = (self.name or "").upper()
|
| 388 |
+
if not self.required:
|
| 389 |
+
var = f"[{var}]"
|
| 390 |
+
type_var = self.type.get_metavar(self, ctx=ctx) # type: ignore[arg-type]
|
| 391 |
+
# type_var = self.type.get_metavar(self, ctx=ctx)
|
| 392 |
+
if type_var:
|
| 393 |
+
var += f":{type_var}"
|
| 394 |
+
if self.nargs != 1:
|
| 395 |
+
var += "..."
|
| 396 |
+
return var
|
| 397 |
+
|
| 398 |
+
def value_is_missing(self, value: Any) -> bool:
|
| 399 |
+
return _value_is_missing(self, value)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class TyperOption(click.core.Option):
|
| 403 |
+
def __init__(
|
| 404 |
+
self,
|
| 405 |
+
*,
|
| 406 |
+
# Parameter
|
| 407 |
+
param_decls: list[str],
|
| 408 |
+
type: click.types.ParamType | Any | None = None,
|
| 409 |
+
required: bool | None = None,
|
| 410 |
+
default: Any | None = None,
|
| 411 |
+
callback: Callable[..., Any] | None = None,
|
| 412 |
+
nargs: int | None = None,
|
| 413 |
+
metavar: str | None = None,
|
| 414 |
+
expose_value: bool = True,
|
| 415 |
+
is_eager: bool = False,
|
| 416 |
+
envvar: str | list[str] | None = None,
|
| 417 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 418 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 419 |
+
shell_complete: Callable[
|
| 420 |
+
[click.Context, click.Parameter, str],
|
| 421 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 422 |
+
]
|
| 423 |
+
| None = None,
|
| 424 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 425 |
+
# Option
|
| 426 |
+
show_default: bool | str = False,
|
| 427 |
+
prompt: bool | str = False,
|
| 428 |
+
confirmation_prompt: bool | str = False,
|
| 429 |
+
prompt_required: bool = True,
|
| 430 |
+
hide_input: bool = False,
|
| 431 |
+
is_flag: bool | None = None,
|
| 432 |
+
multiple: bool = False,
|
| 433 |
+
count: bool = False,
|
| 434 |
+
allow_from_autoenv: bool = True,
|
| 435 |
+
help: str | None = None,
|
| 436 |
+
hidden: bool = False,
|
| 437 |
+
show_choices: bool = True,
|
| 438 |
+
show_envvar: bool = False,
|
| 439 |
+
# Rich settings
|
| 440 |
+
rich_help_panel: str | None = None,
|
| 441 |
+
):
|
| 442 |
+
super().__init__(
|
| 443 |
+
param_decls=param_decls,
|
| 444 |
+
type=type,
|
| 445 |
+
required=required,
|
| 446 |
+
default=default,
|
| 447 |
+
callback=callback,
|
| 448 |
+
nargs=nargs,
|
| 449 |
+
metavar=metavar,
|
| 450 |
+
expose_value=expose_value,
|
| 451 |
+
is_eager=is_eager,
|
| 452 |
+
envvar=envvar,
|
| 453 |
+
show_default=show_default,
|
| 454 |
+
prompt=prompt,
|
| 455 |
+
confirmation_prompt=confirmation_prompt,
|
| 456 |
+
hide_input=hide_input,
|
| 457 |
+
is_flag=is_flag,
|
| 458 |
+
multiple=multiple,
|
| 459 |
+
count=count,
|
| 460 |
+
allow_from_autoenv=allow_from_autoenv,
|
| 461 |
+
help=help,
|
| 462 |
+
hidden=hidden,
|
| 463 |
+
show_choices=show_choices,
|
| 464 |
+
show_envvar=show_envvar,
|
| 465 |
+
prompt_required=prompt_required,
|
| 466 |
+
shell_complete=shell_complete,
|
| 467 |
+
)
|
| 468 |
+
_typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
|
| 469 |
+
self.rich_help_panel = rich_help_panel
|
| 470 |
+
|
| 471 |
+
def _get_default_string(
|
| 472 |
+
self,
|
| 473 |
+
*,
|
| 474 |
+
ctx: click.Context,
|
| 475 |
+
show_default_is_str: bool,
|
| 476 |
+
default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
|
| 477 |
+
) -> str:
|
| 478 |
+
return _get_default_string(
|
| 479 |
+
self,
|
| 480 |
+
ctx=ctx,
|
| 481 |
+
show_default_is_str=show_default_is_str,
|
| 482 |
+
default_value=default_value,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
def _extract_default_help_str(
|
| 486 |
+
self, *, ctx: click.Context
|
| 487 |
+
) -> Any | Callable[[], Any] | None:
|
| 488 |
+
return _extract_default_help_str(self, ctx=ctx)
|
| 489 |
+
|
| 490 |
+
def make_metavar(self, ctx: click.Context | None = None) -> str:
|
| 491 |
+
return super().make_metavar(ctx=ctx) # type: ignore[arg-type]
|
| 492 |
+
|
| 493 |
+
def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
|
| 494 |
+
# Duplicate all of Click's logic only to modify a single line, to allow boolean
|
| 495 |
+
# flags with only names for False values as it's currently supported by Typer
|
| 496 |
+
# Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false
|
| 497 |
+
if self.hidden:
|
| 498 |
+
return None
|
| 499 |
+
|
| 500 |
+
any_prefix_is_slash = False
|
| 501 |
+
|
| 502 |
+
def _write_opts(opts: Sequence[str]) -> str:
|
| 503 |
+
nonlocal any_prefix_is_slash
|
| 504 |
+
|
| 505 |
+
rv, any_slashes = click.formatting.join_options(opts)
|
| 506 |
+
|
| 507 |
+
if any_slashes:
|
| 508 |
+
any_prefix_is_slash = True
|
| 509 |
+
|
| 510 |
+
if not self.is_flag and not self.count:
|
| 511 |
+
rv += f" {self.make_metavar(ctx=ctx)}"
|
| 512 |
+
|
| 513 |
+
return rv
|
| 514 |
+
|
| 515 |
+
rv = [_write_opts(self.opts)]
|
| 516 |
+
|
| 517 |
+
if self.secondary_opts:
|
| 518 |
+
rv.append(_write_opts(self.secondary_opts))
|
| 519 |
+
|
| 520 |
+
help = self.help or ""
|
| 521 |
+
extra = []
|
| 522 |
+
|
| 523 |
+
if self.show_envvar:
|
| 524 |
+
envvar = self.envvar
|
| 525 |
+
|
| 526 |
+
if envvar is None:
|
| 527 |
+
if (
|
| 528 |
+
self.allow_from_autoenv
|
| 529 |
+
and ctx.auto_envvar_prefix is not None
|
| 530 |
+
and self.name is not None
|
| 531 |
+
):
|
| 532 |
+
envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
|
| 533 |
+
|
| 534 |
+
if envvar is not None:
|
| 535 |
+
var_str = (
|
| 536 |
+
envvar
|
| 537 |
+
if isinstance(envvar, str)
|
| 538 |
+
else ", ".join(str(d) for d in envvar)
|
| 539 |
+
)
|
| 540 |
+
extra.append(_("env var: {var}").format(var=var_str))
|
| 541 |
+
|
| 542 |
+
# Typer override:
|
| 543 |
+
# Extracted to _extract_default() to allow re-using it in rich_utils
|
| 544 |
+
default_value = self._extract_default_help_str(ctx=ctx)
|
| 545 |
+
# Typer override end
|
| 546 |
+
|
| 547 |
+
show_default_is_str = isinstance(self.show_default, str)
|
| 548 |
+
|
| 549 |
+
if show_default_is_str or (
|
| 550 |
+
default_value is not None and (self.show_default or ctx.show_default)
|
| 551 |
+
):
|
| 552 |
+
# Typer override:
|
| 553 |
+
# Extracted to _get_default_string() to allow re-using it in rich_utils
|
| 554 |
+
default_string = self._get_default_string(
|
| 555 |
+
ctx=ctx,
|
| 556 |
+
show_default_is_str=show_default_is_str,
|
| 557 |
+
default_value=default_value,
|
| 558 |
+
)
|
| 559 |
+
# Typer override end
|
| 560 |
+
if default_string:
|
| 561 |
+
extra.append(_("default: {default}").format(default=default_string))
|
| 562 |
+
|
| 563 |
+
if isinstance(self.type, click.types._NumberRangeBase):
|
| 564 |
+
range_str = self.type._describe_range()
|
| 565 |
+
|
| 566 |
+
if range_str:
|
| 567 |
+
extra.append(range_str)
|
| 568 |
+
|
| 569 |
+
if self.required:
|
| 570 |
+
extra.append(_("required"))
|
| 571 |
+
|
| 572 |
+
if extra:
|
| 573 |
+
extra_str = "; ".join(extra)
|
| 574 |
+
extra_str = f"[{extra_str}]"
|
| 575 |
+
rich_markup_mode = None
|
| 576 |
+
if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
|
| 577 |
+
rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
|
| 578 |
+
if HAS_RICH and rich_markup_mode == "rich":
|
| 579 |
+
# This is needed for when we want to export to HTML
|
| 580 |
+
from . import rich_utils
|
| 581 |
+
|
| 582 |
+
extra_str = rich_utils.escape_before_html_export(extra_str)
|
| 583 |
+
|
| 584 |
+
help = f"{help} {extra_str}" if help else f"{extra_str}"
|
| 585 |
+
|
| 586 |
+
return ("; " if any_prefix_is_slash else " / ").join(rv), help
|
| 587 |
+
|
| 588 |
+
def value_is_missing(self, value: Any) -> bool:
|
| 589 |
+
return _value_is_missing(self, value)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def _value_is_missing(param: click.Parameter, value: Any) -> bool:
|
| 593 |
+
if value is None:
|
| 594 |
+
return True
|
| 595 |
+
|
| 596 |
+
# Click 8.3 and beyond
|
| 597 |
+
# if value is UNSET:
|
| 598 |
+
# return True
|
| 599 |
+
|
| 600 |
+
if (param.nargs != 1 or param.multiple) and value == ():
|
| 601 |
+
return True # pragma: no cover
|
| 602 |
+
|
| 603 |
+
return False
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _typer_format_options(
|
| 607 |
+
self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter
|
| 608 |
+
) -> None:
|
| 609 |
+
args = []
|
| 610 |
+
opts = []
|
| 611 |
+
for param in self.get_params(ctx):
|
| 612 |
+
rv = param.get_help_record(ctx)
|
| 613 |
+
if rv is not None:
|
| 614 |
+
if param.param_type_name == "argument":
|
| 615 |
+
args.append(rv)
|
| 616 |
+
elif param.param_type_name == "option":
|
| 617 |
+
opts.append(rv)
|
| 618 |
+
|
| 619 |
+
if args:
|
| 620 |
+
with formatter.section(_("Arguments")):
|
| 621 |
+
formatter.write_dl(args)
|
| 622 |
+
if opts:
|
| 623 |
+
with formatter.section(_("Options")):
|
| 624 |
+
formatter.write_dl(opts)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def _typer_main_shell_completion(
|
| 628 |
+
self: click.core.Command,
|
| 629 |
+
*,
|
| 630 |
+
ctx_args: MutableMapping[str, Any],
|
| 631 |
+
prog_name: str,
|
| 632 |
+
complete_var: str | None = None,
|
| 633 |
+
) -> None:
|
| 634 |
+
if complete_var is None:
|
| 635 |
+
complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()
|
| 636 |
+
|
| 637 |
+
instruction = os.environ.get(complete_var)
|
| 638 |
+
|
| 639 |
+
if not instruction:
|
| 640 |
+
return
|
| 641 |
+
|
| 642 |
+
from .completion import shell_complete
|
| 643 |
+
|
| 644 |
+
rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
|
| 645 |
+
sys.exit(rv)
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
class TyperCommand(click.core.Command):
|
| 649 |
+
def __init__(
|
| 650 |
+
self,
|
| 651 |
+
name: str | None,
|
| 652 |
+
*,
|
| 653 |
+
context_settings: dict[str, Any] | None = None,
|
| 654 |
+
callback: Callable[..., Any] | None = None,
|
| 655 |
+
params: list[click.Parameter] | None = None,
|
| 656 |
+
help: str | None = None,
|
| 657 |
+
epilog: str | None = None,
|
| 658 |
+
short_help: str | None = None,
|
| 659 |
+
options_metavar: str | None = "[OPTIONS]",
|
| 660 |
+
add_help_option: bool = True,
|
| 661 |
+
no_args_is_help: bool = False,
|
| 662 |
+
hidden: bool = False,
|
| 663 |
+
deprecated: bool = False,
|
| 664 |
+
# Rich settings
|
| 665 |
+
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
|
| 666 |
+
rich_help_panel: str | None = None,
|
| 667 |
+
) -> None:
|
| 668 |
+
super().__init__(
|
| 669 |
+
name=name,
|
| 670 |
+
context_settings=context_settings,
|
| 671 |
+
callback=callback,
|
| 672 |
+
params=params,
|
| 673 |
+
help=help,
|
| 674 |
+
epilog=epilog,
|
| 675 |
+
short_help=short_help,
|
| 676 |
+
options_metavar=options_metavar,
|
| 677 |
+
add_help_option=add_help_option,
|
| 678 |
+
no_args_is_help=no_args_is_help,
|
| 679 |
+
hidden=hidden,
|
| 680 |
+
deprecated=deprecated,
|
| 681 |
+
)
|
| 682 |
+
self.rich_markup_mode: MarkupMode = rich_markup_mode
|
| 683 |
+
self.rich_help_panel = rich_help_panel
|
| 684 |
+
|
| 685 |
+
def format_options(
|
| 686 |
+
self, ctx: click.Context, formatter: click.HelpFormatter
|
| 687 |
+
) -> None:
|
| 688 |
+
_typer_format_options(self, ctx=ctx, formatter=formatter)
|
| 689 |
+
|
| 690 |
+
def _main_shell_completion(
|
| 691 |
+
self,
|
| 692 |
+
ctx_args: MutableMapping[str, Any],
|
| 693 |
+
prog_name: str,
|
| 694 |
+
complete_var: str | None = None,
|
| 695 |
+
) -> None:
|
| 696 |
+
_typer_main_shell_completion(
|
| 697 |
+
self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
|
| 698 |
+
)
|
| 699 |
+
|
| 700 |
+
def main(
|
| 701 |
+
self,
|
| 702 |
+
args: Sequence[str] | None = None,
|
| 703 |
+
prog_name: str | None = None,
|
| 704 |
+
complete_var: str | None = None,
|
| 705 |
+
standalone_mode: bool = True,
|
| 706 |
+
windows_expand_args: bool = True,
|
| 707 |
+
**extra: Any,
|
| 708 |
+
) -> Any:
|
| 709 |
+
return _main(
|
| 710 |
+
self,
|
| 711 |
+
args=args,
|
| 712 |
+
prog_name=prog_name,
|
| 713 |
+
complete_var=complete_var,
|
| 714 |
+
standalone_mode=standalone_mode,
|
| 715 |
+
windows_expand_args=windows_expand_args,
|
| 716 |
+
rich_markup_mode=self.rich_markup_mode,
|
| 717 |
+
**extra,
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 721 |
+
if not HAS_RICH or self.rich_markup_mode is None:
|
| 722 |
+
if not hasattr(ctx, "obj") or ctx.obj is None:
|
| 723 |
+
ctx.ensure_object(dict)
|
| 724 |
+
if isinstance(ctx.obj, dict):
|
| 725 |
+
ctx.obj[MARKUP_MODE_KEY] = self.rich_markup_mode
|
| 726 |
+
return super().format_help(ctx, formatter)
|
| 727 |
+
from . import rich_utils
|
| 728 |
+
|
| 729 |
+
return rich_utils.rich_format_help(
|
| 730 |
+
obj=self,
|
| 731 |
+
ctx=ctx,
|
| 732 |
+
markup_mode=self.rich_markup_mode,
|
| 733 |
+
)
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
class TyperGroup(click.core.Group):
|
| 737 |
+
def __init__(
|
| 738 |
+
self,
|
| 739 |
+
*,
|
| 740 |
+
name: str | None = None,
|
| 741 |
+
commands: dict[str, click.Command] | Sequence[click.Command] | None = None,
|
| 742 |
+
# Rich settings
|
| 743 |
+
rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
|
| 744 |
+
rich_help_panel: str | None = None,
|
| 745 |
+
suggest_commands: bool = True,
|
| 746 |
+
**attrs: Any,
|
| 747 |
+
) -> None:
|
| 748 |
+
super().__init__(name=name, commands=commands, **attrs)
|
| 749 |
+
self.rich_markup_mode: MarkupMode = rich_markup_mode
|
| 750 |
+
self.rich_help_panel = rich_help_panel
|
| 751 |
+
self.suggest_commands = suggest_commands
|
| 752 |
+
|
| 753 |
+
def format_options(
|
| 754 |
+
self, ctx: click.Context, formatter: click.HelpFormatter
|
| 755 |
+
) -> None:
|
| 756 |
+
_typer_format_options(self, ctx=ctx, formatter=formatter)
|
| 757 |
+
self.format_commands(ctx, formatter)
|
| 758 |
+
|
| 759 |
+
def _main_shell_completion(
|
| 760 |
+
self,
|
| 761 |
+
ctx_args: MutableMapping[str, Any],
|
| 762 |
+
prog_name: str,
|
| 763 |
+
complete_var: str | None = None,
|
| 764 |
+
) -> None:
|
| 765 |
+
_typer_main_shell_completion(
|
| 766 |
+
self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
def resolve_command(
|
| 770 |
+
self, ctx: click.Context, args: list[str]
|
| 771 |
+
) -> tuple[str | None, click.Command | None, list[str]]:
|
| 772 |
+
try:
|
| 773 |
+
return super().resolve_command(ctx, args)
|
| 774 |
+
except click.UsageError as e:
|
| 775 |
+
if self.suggest_commands:
|
| 776 |
+
available_commands = list(self.commands.keys())
|
| 777 |
+
if available_commands and args:
|
| 778 |
+
typo = args[0]
|
| 779 |
+
matches = get_close_matches(typo, available_commands)
|
| 780 |
+
if matches:
|
| 781 |
+
suggestions = ", ".join(f"{m!r}" for m in matches)
|
| 782 |
+
message = e.message.rstrip(".")
|
| 783 |
+
e.message = f"{message}. Did you mean {suggestions}?"
|
| 784 |
+
raise
|
| 785 |
+
|
| 786 |
+
def main(
|
| 787 |
+
self,
|
| 788 |
+
args: Sequence[str] | None = None,
|
| 789 |
+
prog_name: str | None = None,
|
| 790 |
+
complete_var: str | None = None,
|
| 791 |
+
standalone_mode: bool = True,
|
| 792 |
+
windows_expand_args: bool = True,
|
| 793 |
+
**extra: Any,
|
| 794 |
+
) -> Any:
|
| 795 |
+
return _main(
|
| 796 |
+
self,
|
| 797 |
+
args=args,
|
| 798 |
+
prog_name=prog_name,
|
| 799 |
+
complete_var=complete_var,
|
| 800 |
+
standalone_mode=standalone_mode,
|
| 801 |
+
windows_expand_args=windows_expand_args,
|
| 802 |
+
rich_markup_mode=self.rich_markup_mode,
|
| 803 |
+
**extra,
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 807 |
+
if not HAS_RICH or self.rich_markup_mode is None:
|
| 808 |
+
return super().format_help(ctx, formatter)
|
| 809 |
+
from . import rich_utils
|
| 810 |
+
|
| 811 |
+
return rich_utils.rich_format_help(
|
| 812 |
+
obj=self,
|
| 813 |
+
ctx=ctx,
|
| 814 |
+
markup_mode=self.rich_markup_mode,
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
def list_commands(self, ctx: click.Context) -> list[str]:
|
| 818 |
+
"""Returns a list of subcommand names.
|
| 819 |
+
Note that in Click's Group class, these are sorted.
|
| 820 |
+
In Typer, we wish to maintain the original order of creation (cf Issue #933)"""
|
| 821 |
+
return [n for n, c in self.commands.items()]
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/main.py
ADDED
|
@@ -0,0 +1,2013 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import os
|
| 3 |
+
import platform
|
| 4 |
+
import shutil
|
| 5 |
+
import subprocess
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
from collections.abc import Callable, Sequence
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from enum import Enum
|
| 11 |
+
from functools import update_wrapper
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from traceback import FrameSummary, StackSummary
|
| 14 |
+
from types import TracebackType
|
| 15 |
+
from typing import Annotated, Any
|
| 16 |
+
from uuid import UUID
|
| 17 |
+
|
| 18 |
+
import click
|
| 19 |
+
from annotated_doc import Doc
|
| 20 |
+
from typer._types import TyperChoice
|
| 21 |
+
|
| 22 |
+
from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values
|
| 23 |
+
from .completion import get_completion_inspect_parameters
|
| 24 |
+
from .core import (
|
| 25 |
+
DEFAULT_MARKUP_MODE,
|
| 26 |
+
HAS_RICH,
|
| 27 |
+
MarkupMode,
|
| 28 |
+
TyperArgument,
|
| 29 |
+
TyperCommand,
|
| 30 |
+
TyperGroup,
|
| 31 |
+
TyperOption,
|
| 32 |
+
)
|
| 33 |
+
from .models import (
|
| 34 |
+
AnyType,
|
| 35 |
+
ArgumentInfo,
|
| 36 |
+
CommandFunctionType,
|
| 37 |
+
CommandInfo,
|
| 38 |
+
Default,
|
| 39 |
+
DefaultPlaceholder,
|
| 40 |
+
DeveloperExceptionConfig,
|
| 41 |
+
FileBinaryRead,
|
| 42 |
+
FileBinaryWrite,
|
| 43 |
+
FileText,
|
| 44 |
+
FileTextWrite,
|
| 45 |
+
NoneType,
|
| 46 |
+
OptionInfo,
|
| 47 |
+
ParameterInfo,
|
| 48 |
+
ParamMeta,
|
| 49 |
+
Required,
|
| 50 |
+
TyperInfo,
|
| 51 |
+
TyperPath,
|
| 52 |
+
)
|
| 53 |
+
from .utils import get_params_from_function
|
| 54 |
+
|
| 55 |
+
_original_except_hook = sys.excepthook
|
| 56 |
+
_typer_developer_exception_attr_name = "__typer_developer_exception__"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def except_hook(
|
| 60 |
+
exc_type: type[BaseException], exc_value: BaseException, tb: TracebackType | None
|
| 61 |
+
) -> None:
|
| 62 |
+
exception_config: DeveloperExceptionConfig | None = getattr(
|
| 63 |
+
exc_value, _typer_developer_exception_attr_name, None
|
| 64 |
+
)
|
| 65 |
+
standard_traceback = os.getenv(
|
| 66 |
+
"TYPER_STANDARD_TRACEBACK", os.getenv("_TYPER_STANDARD_TRACEBACK")
|
| 67 |
+
)
|
| 68 |
+
if (
|
| 69 |
+
standard_traceback
|
| 70 |
+
or not exception_config
|
| 71 |
+
or not exception_config.pretty_exceptions_enable
|
| 72 |
+
):
|
| 73 |
+
_original_except_hook(exc_type, exc_value, tb)
|
| 74 |
+
return
|
| 75 |
+
typer_path = os.path.dirname(__file__)
|
| 76 |
+
click_path = os.path.dirname(click.__file__)
|
| 77 |
+
internal_dir_names = [typer_path, click_path]
|
| 78 |
+
exc = exc_value
|
| 79 |
+
if HAS_RICH:
|
| 80 |
+
from . import rich_utils
|
| 81 |
+
|
| 82 |
+
rich_tb = rich_utils.get_traceback(exc, exception_config, internal_dir_names)
|
| 83 |
+
console_stderr = rich_utils._get_rich_console(stderr=True)
|
| 84 |
+
console_stderr.print(rich_tb)
|
| 85 |
+
return
|
| 86 |
+
tb_exc = traceback.TracebackException.from_exception(exc)
|
| 87 |
+
stack: list[FrameSummary] = []
|
| 88 |
+
for frame in tb_exc.stack:
|
| 89 |
+
if any(frame.filename.startswith(path) for path in internal_dir_names):
|
| 90 |
+
if not exception_config.pretty_exceptions_short:
|
| 91 |
+
# Hide the line for internal libraries, Typer and Click
|
| 92 |
+
stack.append(
|
| 93 |
+
traceback.FrameSummary(
|
| 94 |
+
filename=frame.filename,
|
| 95 |
+
lineno=frame.lineno,
|
| 96 |
+
name=frame.name,
|
| 97 |
+
line="",
|
| 98 |
+
)
|
| 99 |
+
)
|
| 100 |
+
else:
|
| 101 |
+
stack.append(frame)
|
| 102 |
+
# Type ignore ref: https://github.com/python/typeshed/pull/8244
|
| 103 |
+
final_stack_summary = StackSummary.from_list(stack)
|
| 104 |
+
tb_exc.stack = final_stack_summary
|
| 105 |
+
for line in tb_exc.format():
|
| 106 |
+
print(line, file=sys.stderr)
|
| 107 |
+
return
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_install_completion_arguments() -> tuple[click.Parameter, click.Parameter]:
|
| 111 |
+
install_param, show_param = get_completion_inspect_parameters()
|
| 112 |
+
click_install_param, _ = get_click_param(install_param)
|
| 113 |
+
click_show_param, _ = get_click_param(show_param)
|
| 114 |
+
return click_install_param, click_show_param
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Typer:
|
| 118 |
+
"""
|
| 119 |
+
`Typer` main class, the main entrypoint to use Typer.
|
| 120 |
+
|
| 121 |
+
Read more in the
|
| 122 |
+
[Typer docs for First Steps](https://typer.tiangolo.com/tutorial/typer-app/).
|
| 123 |
+
|
| 124 |
+
## Example
|
| 125 |
+
|
| 126 |
+
```python
|
| 127 |
+
import typer
|
| 128 |
+
|
| 129 |
+
app = typer.Typer()
|
| 130 |
+
```
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
def __init__(
|
| 134 |
+
self,
|
| 135 |
+
*,
|
| 136 |
+
name: Annotated[
|
| 137 |
+
str | None,
|
| 138 |
+
Doc(
|
| 139 |
+
"""
|
| 140 |
+
The name of this application.
|
| 141 |
+
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=...)`.
|
| 142 |
+
|
| 143 |
+
**Example**
|
| 144 |
+
|
| 145 |
+
```python
|
| 146 |
+
import typer
|
| 147 |
+
|
| 148 |
+
app = typer.Typer(name="users")
|
| 149 |
+
```
|
| 150 |
+
"""
|
| 151 |
+
),
|
| 152 |
+
] = Default(None),
|
| 153 |
+
cls: Annotated[
|
| 154 |
+
type[TyperGroup] | None,
|
| 155 |
+
Doc(
|
| 156 |
+
"""
|
| 157 |
+
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`.
|
| 158 |
+
Otherwise, should be a subtype of `TyperGroup`.
|
| 159 |
+
|
| 160 |
+
**Example**
|
| 161 |
+
|
| 162 |
+
```python
|
| 163 |
+
import typer
|
| 164 |
+
|
| 165 |
+
app = typer.Typer(cls=TyperGroup)
|
| 166 |
+
```
|
| 167 |
+
"""
|
| 168 |
+
),
|
| 169 |
+
] = Default(None),
|
| 170 |
+
invoke_without_command: Annotated[
|
| 171 |
+
bool,
|
| 172 |
+
Doc(
|
| 173 |
+
"""
|
| 174 |
+
By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
|
| 175 |
+
|
| 176 |
+
**Example**
|
| 177 |
+
|
| 178 |
+
```python
|
| 179 |
+
import typer
|
| 180 |
+
|
| 181 |
+
app = typer.Typer(invoke_without_command=True)
|
| 182 |
+
```
|
| 183 |
+
"""
|
| 184 |
+
),
|
| 185 |
+
] = Default(False),
|
| 186 |
+
no_args_is_help: Annotated[
|
| 187 |
+
bool,
|
| 188 |
+
Doc(
|
| 189 |
+
"""
|
| 190 |
+
If this is set to `True`, running a command without any arguments will automatically show the help page.
|
| 191 |
+
|
| 192 |
+
**Example**
|
| 193 |
+
|
| 194 |
+
```python
|
| 195 |
+
import typer
|
| 196 |
+
|
| 197 |
+
app = typer.Typer(no_args_is_help=True)
|
| 198 |
+
```
|
| 199 |
+
"""
|
| 200 |
+
),
|
| 201 |
+
] = Default(False),
|
| 202 |
+
subcommand_metavar: Annotated[
|
| 203 |
+
str | None,
|
| 204 |
+
Doc(
|
| 205 |
+
"""
|
| 206 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 207 |
+
from Click and supported for compatibility.
|
| 208 |
+
|
| 209 |
+
---
|
| 210 |
+
|
| 211 |
+
How to represent the subcommand argument in help.
|
| 212 |
+
"""
|
| 213 |
+
),
|
| 214 |
+
] = Default(None),
|
| 215 |
+
chain: Annotated[
|
| 216 |
+
bool,
|
| 217 |
+
Doc(
|
| 218 |
+
"""
|
| 219 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 220 |
+
from Click and supported for compatibility.
|
| 221 |
+
|
| 222 |
+
---
|
| 223 |
+
|
| 224 |
+
Allow passing more than one subcommand argument.
|
| 225 |
+
"""
|
| 226 |
+
),
|
| 227 |
+
] = Default(False),
|
| 228 |
+
result_callback: Annotated[
|
| 229 |
+
Callable[..., Any] | None,
|
| 230 |
+
Doc(
|
| 231 |
+
"""
|
| 232 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 233 |
+
from Click and supported for compatibility.
|
| 234 |
+
|
| 235 |
+
---
|
| 236 |
+
|
| 237 |
+
A function to call after the group's and subcommand's callbacks.
|
| 238 |
+
"""
|
| 239 |
+
),
|
| 240 |
+
] = Default(None),
|
| 241 |
+
# Command
|
| 242 |
+
context_settings: Annotated[
|
| 243 |
+
dict[Any, Any] | None,
|
| 244 |
+
Doc(
|
| 245 |
+
"""
|
| 246 |
+
Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
|
| 247 |
+
Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
|
| 248 |
+
|
| 249 |
+
**Example**
|
| 250 |
+
|
| 251 |
+
```python
|
| 252 |
+
import typer
|
| 253 |
+
|
| 254 |
+
app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})
|
| 255 |
+
```
|
| 256 |
+
"""
|
| 257 |
+
),
|
| 258 |
+
] = Default(None),
|
| 259 |
+
callback: Annotated[
|
| 260 |
+
Callable[..., Any] | None,
|
| 261 |
+
Doc(
|
| 262 |
+
"""
|
| 263 |
+
Add a callback to the main Typer app. Can be overridden with `@app.callback()`.
|
| 264 |
+
See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.
|
| 265 |
+
|
| 266 |
+
**Example**
|
| 267 |
+
|
| 268 |
+
```python
|
| 269 |
+
import typer
|
| 270 |
+
|
| 271 |
+
def callback():
|
| 272 |
+
print("Running a command")
|
| 273 |
+
|
| 274 |
+
app = typer.Typer(callback=callback)
|
| 275 |
+
```
|
| 276 |
+
"""
|
| 277 |
+
),
|
| 278 |
+
] = Default(None),
|
| 279 |
+
help: Annotated[
|
| 280 |
+
str | None,
|
| 281 |
+
Doc(
|
| 282 |
+
"""
|
| 283 |
+
Help text for the main Typer app.
|
| 284 |
+
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,
|
| 285 |
+
and which one takes priority.
|
| 286 |
+
|
| 287 |
+
**Example**
|
| 288 |
+
|
| 289 |
+
```python
|
| 290 |
+
import typer
|
| 291 |
+
|
| 292 |
+
app = typer.Typer(help="Some help.")
|
| 293 |
+
```
|
| 294 |
+
"""
|
| 295 |
+
),
|
| 296 |
+
] = Default(None),
|
| 297 |
+
epilog: Annotated[
|
| 298 |
+
str | None,
|
| 299 |
+
Doc(
|
| 300 |
+
"""
|
| 301 |
+
Text that will be printed right after the help text.
|
| 302 |
+
|
| 303 |
+
**Example**
|
| 304 |
+
|
| 305 |
+
```python
|
| 306 |
+
import typer
|
| 307 |
+
|
| 308 |
+
app = typer.Typer(epilog="May the force be with you")
|
| 309 |
+
```
|
| 310 |
+
"""
|
| 311 |
+
),
|
| 312 |
+
] = Default(None),
|
| 313 |
+
short_help: Annotated[
|
| 314 |
+
str | None,
|
| 315 |
+
Doc(
|
| 316 |
+
"""
|
| 317 |
+
A shortened version of the help text that can be used e.g. in the help table listing subcommands.
|
| 318 |
+
When not defined, the normal `help` text will be used instead.
|
| 319 |
+
|
| 320 |
+
**Example**
|
| 321 |
+
|
| 322 |
+
```python
|
| 323 |
+
import typer
|
| 324 |
+
|
| 325 |
+
app = typer.Typer(help="A lot of explanation about user management", short_help="user management")
|
| 326 |
+
```
|
| 327 |
+
"""
|
| 328 |
+
),
|
| 329 |
+
] = Default(None),
|
| 330 |
+
options_metavar: Annotated[
|
| 331 |
+
str,
|
| 332 |
+
Doc(
|
| 333 |
+
"""
|
| 334 |
+
In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
|
| 335 |
+
Set `options_metavar` to change this into a different string.
|
| 336 |
+
|
| 337 |
+
**Example**
|
| 338 |
+
|
| 339 |
+
```python
|
| 340 |
+
import typer
|
| 341 |
+
|
| 342 |
+
app = typer.Typer(options_metavar="[OPTS]")
|
| 343 |
+
```
|
| 344 |
+
"""
|
| 345 |
+
),
|
| 346 |
+
] = Default("[OPTIONS]"),
|
| 347 |
+
add_help_option: Annotated[
|
| 348 |
+
bool,
|
| 349 |
+
Doc(
|
| 350 |
+
"""
|
| 351 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 352 |
+
from Click and supported for compatibility.
|
| 353 |
+
|
| 354 |
+
---
|
| 355 |
+
|
| 356 |
+
By default each command registers a `--help` option. This can be disabled by this parameter.
|
| 357 |
+
"""
|
| 358 |
+
),
|
| 359 |
+
] = Default(True),
|
| 360 |
+
hidden: Annotated[
|
| 361 |
+
bool,
|
| 362 |
+
Doc(
|
| 363 |
+
"""
|
| 364 |
+
Hide this command from help outputs. `False` by default.
|
| 365 |
+
|
| 366 |
+
**Example**
|
| 367 |
+
|
| 368 |
+
```python
|
| 369 |
+
import typer
|
| 370 |
+
|
| 371 |
+
app = typer.Typer(hidden=True)
|
| 372 |
+
```
|
| 373 |
+
"""
|
| 374 |
+
),
|
| 375 |
+
] = Default(False),
|
| 376 |
+
deprecated: Annotated[
|
| 377 |
+
bool,
|
| 378 |
+
Doc(
|
| 379 |
+
"""
|
| 380 |
+
Mark this command as being deprecated in the help text. `False` by default.
|
| 381 |
+
|
| 382 |
+
**Example**
|
| 383 |
+
|
| 384 |
+
```python
|
| 385 |
+
import typer
|
| 386 |
+
|
| 387 |
+
app = typer.Typer(deprecated=True)
|
| 388 |
+
```
|
| 389 |
+
"""
|
| 390 |
+
),
|
| 391 |
+
] = Default(False),
|
| 392 |
+
add_completion: Annotated[
|
| 393 |
+
bool,
|
| 394 |
+
Doc(
|
| 395 |
+
"""
|
| 396 |
+
Toggle whether or not to add the `--install-completion` and `--show-completion` options to the app.
|
| 397 |
+
Set to `True` by default.
|
| 398 |
+
|
| 399 |
+
**Example**
|
| 400 |
+
|
| 401 |
+
```python
|
| 402 |
+
import typer
|
| 403 |
+
|
| 404 |
+
app = typer.Typer(add_completion=False)
|
| 405 |
+
```
|
| 406 |
+
"""
|
| 407 |
+
),
|
| 408 |
+
] = True,
|
| 409 |
+
# Rich settings
|
| 410 |
+
rich_markup_mode: Annotated[
|
| 411 |
+
MarkupMode,
|
| 412 |
+
Doc(
|
| 413 |
+
"""
|
| 414 |
+
Enable markup text if you have Rich installed. This can be set to `"markdown"`, `"rich"`, or `None`.
|
| 415 |
+
By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed.
|
| 416 |
+
See [the tutorial on help formatting](https://typer.tiangolo.com/tutorial/commands/help/#rich-markdown-and-markup) for more information.
|
| 417 |
+
|
| 418 |
+
**Example**
|
| 419 |
+
|
| 420 |
+
```python
|
| 421 |
+
import typer
|
| 422 |
+
|
| 423 |
+
app = typer.Typer(rich_markup_mode="rich")
|
| 424 |
+
```
|
| 425 |
+
"""
|
| 426 |
+
),
|
| 427 |
+
] = DEFAULT_MARKUP_MODE,
|
| 428 |
+
rich_help_panel: Annotated[
|
| 429 |
+
str | None,
|
| 430 |
+
Doc(
|
| 431 |
+
"""
|
| 432 |
+
Set the panel name of the command when the help is printed with Rich.
|
| 433 |
+
|
| 434 |
+
**Example**
|
| 435 |
+
|
| 436 |
+
```python
|
| 437 |
+
import typer
|
| 438 |
+
|
| 439 |
+
app = typer.Typer(rich_help_panel="Utils and Configs")
|
| 440 |
+
```
|
| 441 |
+
"""
|
| 442 |
+
),
|
| 443 |
+
] = Default(None),
|
| 444 |
+
suggest_commands: Annotated[
|
| 445 |
+
bool,
|
| 446 |
+
Doc(
|
| 447 |
+
"""
|
| 448 |
+
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.
|
| 449 |
+
You can turn this setting off with `suggest_commands`:
|
| 450 |
+
|
| 451 |
+
**Example**
|
| 452 |
+
|
| 453 |
+
```python
|
| 454 |
+
import typer
|
| 455 |
+
|
| 456 |
+
app = typer.Typer(suggest_commands=False)
|
| 457 |
+
```
|
| 458 |
+
"""
|
| 459 |
+
),
|
| 460 |
+
] = True,
|
| 461 |
+
pretty_exceptions_enable: Annotated[
|
| 462 |
+
bool,
|
| 463 |
+
Doc(
|
| 464 |
+
"""
|
| 465 |
+
If you want to disable [pretty exceptions with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich),
|
| 466 |
+
you can set `pretty_exceptions_enable` to `False`. When doing so, you will see the usual standard exception trace.
|
| 467 |
+
|
| 468 |
+
**Example**
|
| 469 |
+
|
| 470 |
+
```python
|
| 471 |
+
import typer
|
| 472 |
+
|
| 473 |
+
app = typer.Typer(pretty_exceptions_enable=False)
|
| 474 |
+
```
|
| 475 |
+
"""
|
| 476 |
+
),
|
| 477 |
+
] = True,
|
| 478 |
+
pretty_exceptions_show_locals: Annotated[
|
| 479 |
+
bool,
|
| 480 |
+
Doc(
|
| 481 |
+
"""
|
| 482 |
+
If Rich is installed, [error messages](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-and-errors)
|
| 483 |
+
will be nicely printed.
|
| 484 |
+
|
| 485 |
+
If you set `pretty_exceptions_show_locals=True` it will also include the values of local variables for easy debugging.
|
| 486 |
+
|
| 487 |
+
However, if such a variable contains delicate information, you should consider leaving `pretty_exceptions_show_locals=False`
|
| 488 |
+
(the default) to `False` to enhance security.
|
| 489 |
+
|
| 490 |
+
**Example**
|
| 491 |
+
|
| 492 |
+
```python
|
| 493 |
+
import typer
|
| 494 |
+
|
| 495 |
+
app = typer.Typer(pretty_exceptions_show_locals=True)
|
| 496 |
+
```
|
| 497 |
+
"""
|
| 498 |
+
),
|
| 499 |
+
] = False,
|
| 500 |
+
pretty_exceptions_short: Annotated[
|
| 501 |
+
bool,
|
| 502 |
+
Doc(
|
| 503 |
+
"""
|
| 504 |
+
By default, [pretty exceptions formatted with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich) hide the long stack trace.
|
| 505 |
+
If you want to show the full trace instead, you can set the parameter `pretty_exceptions_short` to `False`:
|
| 506 |
+
|
| 507 |
+
**Example**
|
| 508 |
+
|
| 509 |
+
```python
|
| 510 |
+
import typer
|
| 511 |
+
|
| 512 |
+
app = typer.Typer(pretty_exceptions_short=False)
|
| 513 |
+
```
|
| 514 |
+
"""
|
| 515 |
+
),
|
| 516 |
+
] = True,
|
| 517 |
+
):
|
| 518 |
+
self._add_completion = add_completion
|
| 519 |
+
self.rich_markup_mode: MarkupMode = rich_markup_mode
|
| 520 |
+
self.rich_help_panel = rich_help_panel
|
| 521 |
+
self.suggest_commands = suggest_commands
|
| 522 |
+
self.pretty_exceptions_enable = pretty_exceptions_enable
|
| 523 |
+
self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
|
| 524 |
+
self.pretty_exceptions_short = pretty_exceptions_short
|
| 525 |
+
self.info = TyperInfo(
|
| 526 |
+
name=name,
|
| 527 |
+
cls=cls,
|
| 528 |
+
invoke_without_command=invoke_without_command,
|
| 529 |
+
no_args_is_help=no_args_is_help,
|
| 530 |
+
subcommand_metavar=subcommand_metavar,
|
| 531 |
+
chain=chain,
|
| 532 |
+
result_callback=result_callback,
|
| 533 |
+
context_settings=context_settings,
|
| 534 |
+
callback=callback,
|
| 535 |
+
help=help,
|
| 536 |
+
epilog=epilog,
|
| 537 |
+
short_help=short_help,
|
| 538 |
+
options_metavar=options_metavar,
|
| 539 |
+
add_help_option=add_help_option,
|
| 540 |
+
hidden=hidden,
|
| 541 |
+
deprecated=deprecated,
|
| 542 |
+
)
|
| 543 |
+
self.registered_groups: list[TyperInfo] = []
|
| 544 |
+
self.registered_commands: list[CommandInfo] = []
|
| 545 |
+
self.registered_callback: TyperInfo | None = None
|
| 546 |
+
|
| 547 |
+
def callback(
|
| 548 |
+
self,
|
| 549 |
+
*,
|
| 550 |
+
cls: Annotated[
|
| 551 |
+
type[TyperGroup] | None,
|
| 552 |
+
Doc(
|
| 553 |
+
"""
|
| 554 |
+
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`.
|
| 555 |
+
Otherwise, should be a subtype of `TyperGroup`.
|
| 556 |
+
"""
|
| 557 |
+
),
|
| 558 |
+
] = Default(None),
|
| 559 |
+
invoke_without_command: Annotated[
|
| 560 |
+
bool,
|
| 561 |
+
Doc(
|
| 562 |
+
"""
|
| 563 |
+
By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
|
| 564 |
+
"""
|
| 565 |
+
),
|
| 566 |
+
] = Default(False),
|
| 567 |
+
no_args_is_help: Annotated[
|
| 568 |
+
bool,
|
| 569 |
+
Doc(
|
| 570 |
+
"""
|
| 571 |
+
If this is set to `True`, running a command without any arguments will automatically show the help page.
|
| 572 |
+
"""
|
| 573 |
+
),
|
| 574 |
+
] = Default(False),
|
| 575 |
+
subcommand_metavar: Annotated[
|
| 576 |
+
str | None,
|
| 577 |
+
Doc(
|
| 578 |
+
"""
|
| 579 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 580 |
+
from Click and supported for compatibility.
|
| 581 |
+
|
| 582 |
+
---
|
| 583 |
+
|
| 584 |
+
How to represent the subcommand argument in help.
|
| 585 |
+
"""
|
| 586 |
+
),
|
| 587 |
+
] = Default(None),
|
| 588 |
+
chain: Annotated[
|
| 589 |
+
bool,
|
| 590 |
+
Doc(
|
| 591 |
+
"""
|
| 592 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 593 |
+
from Click and supported for compatibility.
|
| 594 |
+
|
| 595 |
+
---
|
| 596 |
+
|
| 597 |
+
Allow passing more than one subcommand argument.
|
| 598 |
+
"""
|
| 599 |
+
),
|
| 600 |
+
] = Default(False),
|
| 601 |
+
result_callback: Annotated[
|
| 602 |
+
Callable[..., Any] | None,
|
| 603 |
+
Doc(
|
| 604 |
+
"""
|
| 605 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 606 |
+
from Click and supported for compatibility.
|
| 607 |
+
|
| 608 |
+
---
|
| 609 |
+
|
| 610 |
+
A function to call after the group's and subcommand's callbacks.
|
| 611 |
+
"""
|
| 612 |
+
),
|
| 613 |
+
] = Default(None),
|
| 614 |
+
# Command
|
| 615 |
+
context_settings: Annotated[
|
| 616 |
+
dict[Any, Any] | None,
|
| 617 |
+
Doc(
|
| 618 |
+
"""
|
| 619 |
+
Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
|
| 620 |
+
Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
|
| 621 |
+
"""
|
| 622 |
+
),
|
| 623 |
+
] = Default(None),
|
| 624 |
+
help: Annotated[
|
| 625 |
+
str | None,
|
| 626 |
+
Doc(
|
| 627 |
+
"""
|
| 628 |
+
Help text for the command.
|
| 629 |
+
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,
|
| 630 |
+
and which one takes priority.
|
| 631 |
+
"""
|
| 632 |
+
),
|
| 633 |
+
] = Default(None),
|
| 634 |
+
epilog: Annotated[
|
| 635 |
+
str | None,
|
| 636 |
+
Doc(
|
| 637 |
+
"""
|
| 638 |
+
Text that will be printed right after the help text.
|
| 639 |
+
"""
|
| 640 |
+
),
|
| 641 |
+
] = Default(None),
|
| 642 |
+
short_help: Annotated[
|
| 643 |
+
str | None,
|
| 644 |
+
Doc(
|
| 645 |
+
"""
|
| 646 |
+
A shortened version of the help text that can be used e.g. in the help table listing subcommands.
|
| 647 |
+
When not defined, the normal `help` text will be used instead.
|
| 648 |
+
"""
|
| 649 |
+
),
|
| 650 |
+
] = Default(None),
|
| 651 |
+
options_metavar: Annotated[
|
| 652 |
+
str | None,
|
| 653 |
+
Doc(
|
| 654 |
+
"""
|
| 655 |
+
In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
|
| 656 |
+
Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
|
| 657 |
+
"""
|
| 658 |
+
),
|
| 659 |
+
] = Default(None),
|
| 660 |
+
add_help_option: Annotated[
|
| 661 |
+
bool,
|
| 662 |
+
Doc(
|
| 663 |
+
"""
|
| 664 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 665 |
+
from Click and supported for compatibility.
|
| 666 |
+
|
| 667 |
+
---
|
| 668 |
+
|
| 669 |
+
By default each command registers a `--help` option. This can be disabled by this parameter.
|
| 670 |
+
"""
|
| 671 |
+
),
|
| 672 |
+
] = Default(True),
|
| 673 |
+
hidden: Annotated[
|
| 674 |
+
bool,
|
| 675 |
+
Doc(
|
| 676 |
+
"""
|
| 677 |
+
Hide this command from help outputs. `False` by default.
|
| 678 |
+
"""
|
| 679 |
+
),
|
| 680 |
+
] = Default(False),
|
| 681 |
+
deprecated: Annotated[
|
| 682 |
+
bool,
|
| 683 |
+
Doc(
|
| 684 |
+
"""
|
| 685 |
+
Mark this command as deprecated in the help text. `False` by default.
|
| 686 |
+
"""
|
| 687 |
+
),
|
| 688 |
+
] = Default(False),
|
| 689 |
+
# Rich settings
|
| 690 |
+
rich_help_panel: Annotated[
|
| 691 |
+
str | None,
|
| 692 |
+
Doc(
|
| 693 |
+
"""
|
| 694 |
+
Set the panel name of the command when the help is printed with Rich.
|
| 695 |
+
"""
|
| 696 |
+
),
|
| 697 |
+
] = Default(None),
|
| 698 |
+
) -> Callable[[CommandFunctionType], CommandFunctionType]:
|
| 699 |
+
"""
|
| 700 |
+
Using the decorator `@app.callback`, you can declare the CLI parameters for the main CLI application.
|
| 701 |
+
|
| 702 |
+
Read more in the
|
| 703 |
+
[Typer docs for Callbacks](https://typer.tiangolo.com/tutorial/commands/callback/).
|
| 704 |
+
|
| 705 |
+
## Example
|
| 706 |
+
|
| 707 |
+
```python
|
| 708 |
+
import typer
|
| 709 |
+
|
| 710 |
+
app = typer.Typer()
|
| 711 |
+
state = {"verbose": False}
|
| 712 |
+
|
| 713 |
+
@app.callback()
|
| 714 |
+
def main(verbose: bool = False):
|
| 715 |
+
if verbose:
|
| 716 |
+
print("Will write verbose output")
|
| 717 |
+
state["verbose"] = True
|
| 718 |
+
|
| 719 |
+
@app.command()
|
| 720 |
+
def delete(username: str):
|
| 721 |
+
# define subcommand
|
| 722 |
+
...
|
| 723 |
+
```
|
| 724 |
+
"""
|
| 725 |
+
|
| 726 |
+
def decorator(f: CommandFunctionType) -> CommandFunctionType:
|
| 727 |
+
self.registered_callback = TyperInfo(
|
| 728 |
+
cls=cls,
|
| 729 |
+
invoke_without_command=invoke_without_command,
|
| 730 |
+
no_args_is_help=no_args_is_help,
|
| 731 |
+
subcommand_metavar=subcommand_metavar,
|
| 732 |
+
chain=chain,
|
| 733 |
+
result_callback=result_callback,
|
| 734 |
+
context_settings=context_settings,
|
| 735 |
+
callback=f,
|
| 736 |
+
help=help,
|
| 737 |
+
epilog=epilog,
|
| 738 |
+
short_help=short_help,
|
| 739 |
+
options_metavar=(
|
| 740 |
+
options_metavar or self._info_val_str("options_metavar")
|
| 741 |
+
),
|
| 742 |
+
add_help_option=add_help_option,
|
| 743 |
+
hidden=hidden,
|
| 744 |
+
deprecated=deprecated,
|
| 745 |
+
rich_help_panel=rich_help_panel,
|
| 746 |
+
)
|
| 747 |
+
return f
|
| 748 |
+
|
| 749 |
+
return decorator
|
| 750 |
+
|
| 751 |
+
def command(
|
| 752 |
+
self,
|
| 753 |
+
name: Annotated[
|
| 754 |
+
str | None,
|
| 755 |
+
Doc(
|
| 756 |
+
"""
|
| 757 |
+
The name of this command.
|
| 758 |
+
"""
|
| 759 |
+
),
|
| 760 |
+
] = None,
|
| 761 |
+
*,
|
| 762 |
+
cls: Annotated[
|
| 763 |
+
type[TyperCommand] | None,
|
| 764 |
+
Doc(
|
| 765 |
+
"""
|
| 766 |
+
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`.
|
| 767 |
+
Otherwise, should be a subtype of `TyperCommand`.
|
| 768 |
+
"""
|
| 769 |
+
),
|
| 770 |
+
] = None,
|
| 771 |
+
context_settings: Annotated[
|
| 772 |
+
dict[Any, Any] | None,
|
| 773 |
+
Doc(
|
| 774 |
+
"""
|
| 775 |
+
Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
|
| 776 |
+
Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
|
| 777 |
+
"""
|
| 778 |
+
),
|
| 779 |
+
] = None,
|
| 780 |
+
help: Annotated[
|
| 781 |
+
str | None,
|
| 782 |
+
Doc(
|
| 783 |
+
"""
|
| 784 |
+
Help text for the command.
|
| 785 |
+
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,
|
| 786 |
+
and which one takes priority.
|
| 787 |
+
"""
|
| 788 |
+
),
|
| 789 |
+
] = None,
|
| 790 |
+
epilog: Annotated[
|
| 791 |
+
str | None,
|
| 792 |
+
Doc(
|
| 793 |
+
"""
|
| 794 |
+
Text that will be printed right after the help text.
|
| 795 |
+
"""
|
| 796 |
+
),
|
| 797 |
+
] = None,
|
| 798 |
+
short_help: Annotated[
|
| 799 |
+
str | None,
|
| 800 |
+
Doc(
|
| 801 |
+
"""
|
| 802 |
+
A shortened version of the help text that can be used e.g. in the help table listing subcommands.
|
| 803 |
+
When not defined, the normal `help` text will be used instead.
|
| 804 |
+
"""
|
| 805 |
+
),
|
| 806 |
+
] = None,
|
| 807 |
+
options_metavar: Annotated[
|
| 808 |
+
str | None,
|
| 809 |
+
Doc(
|
| 810 |
+
"""
|
| 811 |
+
In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
|
| 812 |
+
Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
|
| 813 |
+
"""
|
| 814 |
+
),
|
| 815 |
+
] = Default(None),
|
| 816 |
+
add_help_option: Annotated[
|
| 817 |
+
bool,
|
| 818 |
+
Doc(
|
| 819 |
+
"""
|
| 820 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 821 |
+
from Click and supported for compatibility.
|
| 822 |
+
|
| 823 |
+
---
|
| 824 |
+
|
| 825 |
+
By default each command registers a `--help` option. This can be disabled by this parameter.
|
| 826 |
+
"""
|
| 827 |
+
),
|
| 828 |
+
] = True,
|
| 829 |
+
no_args_is_help: Annotated[
|
| 830 |
+
bool,
|
| 831 |
+
Doc(
|
| 832 |
+
"""
|
| 833 |
+
If this is set to `True`, running a command without any arguments will automatically show the help page.
|
| 834 |
+
"""
|
| 835 |
+
),
|
| 836 |
+
] = False,
|
| 837 |
+
hidden: Annotated[
|
| 838 |
+
bool,
|
| 839 |
+
Doc(
|
| 840 |
+
"""
|
| 841 |
+
Hide this command from help outputs. `False` by default.
|
| 842 |
+
"""
|
| 843 |
+
),
|
| 844 |
+
] = False,
|
| 845 |
+
deprecated: Annotated[
|
| 846 |
+
bool,
|
| 847 |
+
Doc(
|
| 848 |
+
"""
|
| 849 |
+
Mark this command as deprecated in the help outputs. `False` by default.
|
| 850 |
+
"""
|
| 851 |
+
),
|
| 852 |
+
] = False,
|
| 853 |
+
# Rich settings
|
| 854 |
+
rich_help_panel: Annotated[
|
| 855 |
+
str | None,
|
| 856 |
+
Doc(
|
| 857 |
+
"""
|
| 858 |
+
Set the panel name of the command when the help is printed with Rich.
|
| 859 |
+
"""
|
| 860 |
+
),
|
| 861 |
+
] = Default(None),
|
| 862 |
+
) -> Callable[[CommandFunctionType], CommandFunctionType]:
|
| 863 |
+
"""
|
| 864 |
+
Using the decorator `@app.command`, you can define a subcommand of the previously defined Typer app.
|
| 865 |
+
|
| 866 |
+
Read more in the
|
| 867 |
+
[Typer docs for Commands](https://typer.tiangolo.com/tutorial/commands/).
|
| 868 |
+
|
| 869 |
+
## Example
|
| 870 |
+
|
| 871 |
+
```python
|
| 872 |
+
import typer
|
| 873 |
+
|
| 874 |
+
app = typer.Typer()
|
| 875 |
+
|
| 876 |
+
@app.command()
|
| 877 |
+
def create():
|
| 878 |
+
print("Creating user: Hiro Hamada")
|
| 879 |
+
|
| 880 |
+
@app.command()
|
| 881 |
+
def delete():
|
| 882 |
+
print("Deleting user: Hiro Hamada")
|
| 883 |
+
```
|
| 884 |
+
"""
|
| 885 |
+
if cls is None:
|
| 886 |
+
cls = TyperCommand
|
| 887 |
+
|
| 888 |
+
def decorator(f: CommandFunctionType) -> CommandFunctionType:
|
| 889 |
+
self.registered_commands.append(
|
| 890 |
+
CommandInfo(
|
| 891 |
+
name=name,
|
| 892 |
+
cls=cls,
|
| 893 |
+
context_settings=context_settings,
|
| 894 |
+
callback=f,
|
| 895 |
+
help=help,
|
| 896 |
+
epilog=epilog,
|
| 897 |
+
short_help=short_help,
|
| 898 |
+
options_metavar=(
|
| 899 |
+
options_metavar or self._info_val_str("options_metavar")
|
| 900 |
+
),
|
| 901 |
+
add_help_option=add_help_option,
|
| 902 |
+
no_args_is_help=no_args_is_help,
|
| 903 |
+
hidden=hidden,
|
| 904 |
+
deprecated=deprecated,
|
| 905 |
+
# Rich settings
|
| 906 |
+
rich_help_panel=rich_help_panel,
|
| 907 |
+
)
|
| 908 |
+
)
|
| 909 |
+
return f
|
| 910 |
+
|
| 911 |
+
return decorator
|
| 912 |
+
|
| 913 |
+
def add_typer(
|
| 914 |
+
self,
|
| 915 |
+
typer_instance: "Typer",
|
| 916 |
+
*,
|
| 917 |
+
name: Annotated[
|
| 918 |
+
str | None,
|
| 919 |
+
Doc(
|
| 920 |
+
"""
|
| 921 |
+
The name of this subcommand.
|
| 922 |
+
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,
|
| 923 |
+
and which one takes priority.
|
| 924 |
+
"""
|
| 925 |
+
),
|
| 926 |
+
] = Default(None),
|
| 927 |
+
cls: Annotated[
|
| 928 |
+
type[TyperGroup] | None,
|
| 929 |
+
Doc(
|
| 930 |
+
"""
|
| 931 |
+
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`.
|
| 932 |
+
Otherwise, should be a subtype of `TyperGroup`.
|
| 933 |
+
"""
|
| 934 |
+
),
|
| 935 |
+
] = Default(None),
|
| 936 |
+
invoke_without_command: Annotated[
|
| 937 |
+
bool,
|
| 938 |
+
Doc(
|
| 939 |
+
"""
|
| 940 |
+
By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
|
| 941 |
+
"""
|
| 942 |
+
),
|
| 943 |
+
] = Default(False),
|
| 944 |
+
no_args_is_help: Annotated[
|
| 945 |
+
bool,
|
| 946 |
+
Doc(
|
| 947 |
+
"""
|
| 948 |
+
If this is set to `True`, running a command without any arguments will automatically show the help page.
|
| 949 |
+
"""
|
| 950 |
+
),
|
| 951 |
+
] = Default(False),
|
| 952 |
+
subcommand_metavar: Annotated[
|
| 953 |
+
str | None,
|
| 954 |
+
Doc(
|
| 955 |
+
"""
|
| 956 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 957 |
+
from Click and supported for compatibility.
|
| 958 |
+
|
| 959 |
+
---
|
| 960 |
+
|
| 961 |
+
How to represent the subcommand argument in help.
|
| 962 |
+
"""
|
| 963 |
+
),
|
| 964 |
+
] = Default(None),
|
| 965 |
+
chain: Annotated[
|
| 966 |
+
bool,
|
| 967 |
+
Doc(
|
| 968 |
+
"""
|
| 969 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 970 |
+
from Click and supported for compatibility.
|
| 971 |
+
|
| 972 |
+
---
|
| 973 |
+
|
| 974 |
+
Allow passing more than one subcommand argument.
|
| 975 |
+
"""
|
| 976 |
+
),
|
| 977 |
+
] = Default(False),
|
| 978 |
+
result_callback: Annotated[
|
| 979 |
+
Callable[..., Any] | None,
|
| 980 |
+
Doc(
|
| 981 |
+
"""
|
| 982 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 983 |
+
from Click and supported for compatibility.
|
| 984 |
+
|
| 985 |
+
---
|
| 986 |
+
|
| 987 |
+
A function to call after the group's and subcommand's callbacks.
|
| 988 |
+
"""
|
| 989 |
+
),
|
| 990 |
+
] = Default(None),
|
| 991 |
+
# Command
|
| 992 |
+
context_settings: Annotated[
|
| 993 |
+
dict[Any, Any] | None,
|
| 994 |
+
Doc(
|
| 995 |
+
"""
|
| 996 |
+
Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
|
| 997 |
+
Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
|
| 998 |
+
"""
|
| 999 |
+
),
|
| 1000 |
+
] = Default(None),
|
| 1001 |
+
callback: Annotated[
|
| 1002 |
+
Callable[..., Any] | None,
|
| 1003 |
+
Doc(
|
| 1004 |
+
"""
|
| 1005 |
+
Add a callback to this app.
|
| 1006 |
+
See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.
|
| 1007 |
+
"""
|
| 1008 |
+
),
|
| 1009 |
+
] = Default(None),
|
| 1010 |
+
help: Annotated[
|
| 1011 |
+
str | None,
|
| 1012 |
+
Doc(
|
| 1013 |
+
"""
|
| 1014 |
+
Help text for the subcommand.
|
| 1015 |
+
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,
|
| 1016 |
+
and which one takes priority.
|
| 1017 |
+
"""
|
| 1018 |
+
),
|
| 1019 |
+
] = Default(None),
|
| 1020 |
+
epilog: Annotated[
|
| 1021 |
+
str | None,
|
| 1022 |
+
Doc(
|
| 1023 |
+
"""
|
| 1024 |
+
Text that will be printed right after the help text.
|
| 1025 |
+
"""
|
| 1026 |
+
),
|
| 1027 |
+
] = Default(None),
|
| 1028 |
+
short_help: Annotated[
|
| 1029 |
+
str | None,
|
| 1030 |
+
Doc(
|
| 1031 |
+
"""
|
| 1032 |
+
A shortened version of the help text that can be used e.g. in the help table listing subcommands.
|
| 1033 |
+
When not defined, the normal `help` text will be used instead.
|
| 1034 |
+
"""
|
| 1035 |
+
),
|
| 1036 |
+
] = Default(None),
|
| 1037 |
+
options_metavar: Annotated[
|
| 1038 |
+
str | None,
|
| 1039 |
+
Doc(
|
| 1040 |
+
"""
|
| 1041 |
+
In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
|
| 1042 |
+
Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
|
| 1043 |
+
"""
|
| 1044 |
+
),
|
| 1045 |
+
] = Default(None),
|
| 1046 |
+
add_help_option: Annotated[
|
| 1047 |
+
bool,
|
| 1048 |
+
Doc(
|
| 1049 |
+
"""
|
| 1050 |
+
**Note**: you probably shouldn't use this parameter, it is inherited
|
| 1051 |
+
from Click and supported for compatibility.
|
| 1052 |
+
|
| 1053 |
+
---
|
| 1054 |
+
|
| 1055 |
+
By default each command registers a `--help` option. This can be disabled by this parameter.
|
| 1056 |
+
"""
|
| 1057 |
+
),
|
| 1058 |
+
] = Default(True),
|
| 1059 |
+
hidden: Annotated[
|
| 1060 |
+
bool,
|
| 1061 |
+
Doc(
|
| 1062 |
+
"""
|
| 1063 |
+
Hide this command from help outputs. `False` by default.
|
| 1064 |
+
"""
|
| 1065 |
+
),
|
| 1066 |
+
] = Default(False),
|
| 1067 |
+
deprecated: Annotated[
|
| 1068 |
+
bool,
|
| 1069 |
+
Doc(
|
| 1070 |
+
"""
|
| 1071 |
+
Mark this command as deprecated in the help outputs. `False` by default.
|
| 1072 |
+
"""
|
| 1073 |
+
),
|
| 1074 |
+
] = False,
|
| 1075 |
+
# Rich settings
|
| 1076 |
+
rich_help_panel: Annotated[
|
| 1077 |
+
str | None,
|
| 1078 |
+
Doc(
|
| 1079 |
+
"""
|
| 1080 |
+
Set the panel name of the command when the help is printed with Rich.
|
| 1081 |
+
"""
|
| 1082 |
+
),
|
| 1083 |
+
] = Default(None),
|
| 1084 |
+
) -> None:
|
| 1085 |
+
"""
|
| 1086 |
+
Add subcommands to the main app using `app.add_typer()`.
|
| 1087 |
+
Subcommands may be defined in separate modules, ensuring clean separation of code by functionality.
|
| 1088 |
+
|
| 1089 |
+
Read more in the
|
| 1090 |
+
[Typer docs for SubCommands](https://typer.tiangolo.com/tutorial/subcommands/add-typer/).
|
| 1091 |
+
|
| 1092 |
+
## Example
|
| 1093 |
+
|
| 1094 |
+
```python
|
| 1095 |
+
import typer
|
| 1096 |
+
|
| 1097 |
+
from .add import app as add_app
|
| 1098 |
+
from .delete import app as delete_app
|
| 1099 |
+
|
| 1100 |
+
app = typer.Typer()
|
| 1101 |
+
|
| 1102 |
+
app.add_typer(add_app)
|
| 1103 |
+
app.add_typer(delete_app)
|
| 1104 |
+
```
|
| 1105 |
+
"""
|
| 1106 |
+
self.registered_groups.append(
|
| 1107 |
+
TyperInfo(
|
| 1108 |
+
typer_instance,
|
| 1109 |
+
name=name,
|
| 1110 |
+
cls=cls,
|
| 1111 |
+
invoke_without_command=invoke_without_command,
|
| 1112 |
+
no_args_is_help=no_args_is_help,
|
| 1113 |
+
subcommand_metavar=subcommand_metavar,
|
| 1114 |
+
chain=chain,
|
| 1115 |
+
result_callback=result_callback,
|
| 1116 |
+
context_settings=context_settings,
|
| 1117 |
+
callback=callback,
|
| 1118 |
+
help=help,
|
| 1119 |
+
epilog=epilog,
|
| 1120 |
+
short_help=short_help,
|
| 1121 |
+
options_metavar=(
|
| 1122 |
+
options_metavar or self._info_val_str("options_metavar")
|
| 1123 |
+
),
|
| 1124 |
+
add_help_option=add_help_option,
|
| 1125 |
+
hidden=hidden,
|
| 1126 |
+
deprecated=deprecated,
|
| 1127 |
+
rich_help_panel=rich_help_panel,
|
| 1128 |
+
)
|
| 1129 |
+
)
|
| 1130 |
+
|
| 1131 |
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
| 1132 |
+
if sys.excepthook != except_hook:
|
| 1133 |
+
sys.excepthook = except_hook
|
| 1134 |
+
try:
|
| 1135 |
+
return get_command(self)(*args, **kwargs)
|
| 1136 |
+
except Exception as e:
|
| 1137 |
+
# Set a custom attribute to tell the hook to show nice exceptions for user
|
| 1138 |
+
# code. An alternative/first implementation was a custom exception with
|
| 1139 |
+
# raise custom_exc from e
|
| 1140 |
+
# but that means the last error shown is the custom exception, not the
|
| 1141 |
+
# actual error. This trick improves developer experience by showing the
|
| 1142 |
+
# actual error last.
|
| 1143 |
+
setattr(
|
| 1144 |
+
e,
|
| 1145 |
+
_typer_developer_exception_attr_name,
|
| 1146 |
+
DeveloperExceptionConfig(
|
| 1147 |
+
pretty_exceptions_enable=self.pretty_exceptions_enable,
|
| 1148 |
+
pretty_exceptions_show_locals=self.pretty_exceptions_show_locals,
|
| 1149 |
+
pretty_exceptions_short=self.pretty_exceptions_short,
|
| 1150 |
+
),
|
| 1151 |
+
)
|
| 1152 |
+
raise e
|
| 1153 |
+
|
| 1154 |
+
def _info_val_str(self, name: str) -> str:
|
| 1155 |
+
val = getattr(self.info, name)
|
| 1156 |
+
val_str = val.value if isinstance(val, DefaultPlaceholder) else val
|
| 1157 |
+
assert isinstance(val_str, str)
|
| 1158 |
+
return val_str
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
def get_group(typer_instance: Typer) -> TyperGroup:
|
| 1162 |
+
group = get_group_from_info(
|
| 1163 |
+
TyperInfo(typer_instance),
|
| 1164 |
+
pretty_exceptions_short=typer_instance.pretty_exceptions_short,
|
| 1165 |
+
rich_markup_mode=typer_instance.rich_markup_mode,
|
| 1166 |
+
suggest_commands=typer_instance.suggest_commands,
|
| 1167 |
+
)
|
| 1168 |
+
return group
|
| 1169 |
+
|
| 1170 |
+
|
| 1171 |
+
def get_command(typer_instance: Typer) -> click.Command:
|
| 1172 |
+
if typer_instance._add_completion:
|
| 1173 |
+
click_install_param, click_show_param = get_install_completion_arguments()
|
| 1174 |
+
if (
|
| 1175 |
+
typer_instance.registered_callback
|
| 1176 |
+
or typer_instance.info.callback
|
| 1177 |
+
or typer_instance.registered_groups
|
| 1178 |
+
or len(typer_instance.registered_commands) > 1
|
| 1179 |
+
):
|
| 1180 |
+
# Create a Group
|
| 1181 |
+
click_command: click.Command = get_group(typer_instance)
|
| 1182 |
+
if typer_instance._add_completion:
|
| 1183 |
+
click_command.params.append(click_install_param)
|
| 1184 |
+
click_command.params.append(click_show_param)
|
| 1185 |
+
return click_command
|
| 1186 |
+
elif len(typer_instance.registered_commands) == 1:
|
| 1187 |
+
# Create a single Command
|
| 1188 |
+
single_command = typer_instance.registered_commands[0]
|
| 1189 |
+
|
| 1190 |
+
if not single_command.context_settings and not isinstance(
|
| 1191 |
+
typer_instance.info.context_settings, DefaultPlaceholder
|
| 1192 |
+
):
|
| 1193 |
+
single_command.context_settings = typer_instance.info.context_settings
|
| 1194 |
+
|
| 1195 |
+
click_command = get_command_from_info(
|
| 1196 |
+
single_command,
|
| 1197 |
+
pretty_exceptions_short=typer_instance.pretty_exceptions_short,
|
| 1198 |
+
rich_markup_mode=typer_instance.rich_markup_mode,
|
| 1199 |
+
)
|
| 1200 |
+
if typer_instance._add_completion:
|
| 1201 |
+
click_command.params.append(click_install_param)
|
| 1202 |
+
click_command.params.append(click_show_param)
|
| 1203 |
+
return click_command
|
| 1204 |
+
raise RuntimeError(
|
| 1205 |
+
"Could not get a command for this Typer instance"
|
| 1206 |
+
) # pragma: no cover
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
def solve_typer_info_help(typer_info: TyperInfo) -> str:
|
| 1210 |
+
# Priority 1: Explicit value was set in app.add_typer()
|
| 1211 |
+
if not isinstance(typer_info.help, DefaultPlaceholder):
|
| 1212 |
+
return inspect.cleandoc(typer_info.help or "")
|
| 1213 |
+
# Priority 2: Explicit value was set in sub_app.callback()
|
| 1214 |
+
if typer_info.typer_instance and typer_info.typer_instance.registered_callback:
|
| 1215 |
+
callback_help = typer_info.typer_instance.registered_callback.help
|
| 1216 |
+
if not isinstance(callback_help, DefaultPlaceholder):
|
| 1217 |
+
return inspect.cleandoc(callback_help or "")
|
| 1218 |
+
# Priority 3: Explicit value was set in sub_app = typer.Typer()
|
| 1219 |
+
if typer_info.typer_instance and typer_info.typer_instance.info:
|
| 1220 |
+
instance_help = typer_info.typer_instance.info.help
|
| 1221 |
+
if not isinstance(instance_help, DefaultPlaceholder):
|
| 1222 |
+
return inspect.cleandoc(instance_help or "")
|
| 1223 |
+
# Priority 4: Implicit inference from callback docstring in app.add_typer()
|
| 1224 |
+
if typer_info.callback:
|
| 1225 |
+
doc = inspect.getdoc(typer_info.callback)
|
| 1226 |
+
if doc:
|
| 1227 |
+
return doc
|
| 1228 |
+
# Priority 5: Implicit inference from callback docstring in @app.callback()
|
| 1229 |
+
if typer_info.typer_instance and typer_info.typer_instance.registered_callback:
|
| 1230 |
+
callback = typer_info.typer_instance.registered_callback.callback
|
| 1231 |
+
if not isinstance(callback, DefaultPlaceholder):
|
| 1232 |
+
doc = inspect.getdoc(callback or "")
|
| 1233 |
+
if doc:
|
| 1234 |
+
return doc
|
| 1235 |
+
# Priority 6: Implicit inference from callback docstring in typer.Typer()
|
| 1236 |
+
if typer_info.typer_instance and typer_info.typer_instance.info:
|
| 1237 |
+
instance_callback = typer_info.typer_instance.info.callback
|
| 1238 |
+
if not isinstance(instance_callback, DefaultPlaceholder):
|
| 1239 |
+
doc = inspect.getdoc(instance_callback)
|
| 1240 |
+
if doc:
|
| 1241 |
+
return doc
|
| 1242 |
+
# Value not set, use the default
|
| 1243 |
+
return typer_info.help.value
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo:
|
| 1247 |
+
values: dict[str, Any] = {}
|
| 1248 |
+
for name, value in typer_info.__dict__.items():
|
| 1249 |
+
# Priority 1: Value was set in app.add_typer()
|
| 1250 |
+
if not isinstance(value, DefaultPlaceholder):
|
| 1251 |
+
values[name] = value
|
| 1252 |
+
continue
|
| 1253 |
+
# Priority 2: Value was set in @subapp.callback()
|
| 1254 |
+
try:
|
| 1255 |
+
callback_value = getattr(
|
| 1256 |
+
typer_info.typer_instance.registered_callback, # type: ignore
|
| 1257 |
+
name,
|
| 1258 |
+
)
|
| 1259 |
+
if not isinstance(callback_value, DefaultPlaceholder):
|
| 1260 |
+
values[name] = callback_value
|
| 1261 |
+
continue
|
| 1262 |
+
except AttributeError:
|
| 1263 |
+
pass
|
| 1264 |
+
# Priority 3: Value set in subapp = typer.Typer()
|
| 1265 |
+
try:
|
| 1266 |
+
instance_value = getattr(
|
| 1267 |
+
typer_info.typer_instance.info, # type: ignore
|
| 1268 |
+
name,
|
| 1269 |
+
)
|
| 1270 |
+
if not isinstance(instance_value, DefaultPlaceholder):
|
| 1271 |
+
values[name] = instance_value
|
| 1272 |
+
continue
|
| 1273 |
+
except AttributeError:
|
| 1274 |
+
pass
|
| 1275 |
+
# Value not set, use the default
|
| 1276 |
+
values[name] = value.value
|
| 1277 |
+
values["help"] = solve_typer_info_help(typer_info)
|
| 1278 |
+
return TyperInfo(**values)
|
| 1279 |
+
|
| 1280 |
+
|
| 1281 |
+
def get_group_from_info(
|
| 1282 |
+
group_info: TyperInfo,
|
| 1283 |
+
*,
|
| 1284 |
+
pretty_exceptions_short: bool,
|
| 1285 |
+
suggest_commands: bool,
|
| 1286 |
+
rich_markup_mode: MarkupMode,
|
| 1287 |
+
) -> TyperGroup:
|
| 1288 |
+
assert group_info.typer_instance, (
|
| 1289 |
+
"A Typer instance is needed to generate a Click Group"
|
| 1290 |
+
)
|
| 1291 |
+
commands: dict[str, click.Command] = {}
|
| 1292 |
+
for command_info in group_info.typer_instance.registered_commands:
|
| 1293 |
+
command = get_command_from_info(
|
| 1294 |
+
command_info=command_info,
|
| 1295 |
+
pretty_exceptions_short=pretty_exceptions_short,
|
| 1296 |
+
rich_markup_mode=rich_markup_mode,
|
| 1297 |
+
)
|
| 1298 |
+
if command.name:
|
| 1299 |
+
commands[command.name] = command
|
| 1300 |
+
for sub_group_info in group_info.typer_instance.registered_groups:
|
| 1301 |
+
sub_group = get_group_from_info(
|
| 1302 |
+
sub_group_info,
|
| 1303 |
+
pretty_exceptions_short=pretty_exceptions_short,
|
| 1304 |
+
rich_markup_mode=rich_markup_mode,
|
| 1305 |
+
suggest_commands=suggest_commands,
|
| 1306 |
+
)
|
| 1307 |
+
if sub_group.name:
|
| 1308 |
+
commands[sub_group.name] = sub_group
|
| 1309 |
+
else:
|
| 1310 |
+
if sub_group.callback:
|
| 1311 |
+
import warnings
|
| 1312 |
+
|
| 1313 |
+
warnings.warn(
|
| 1314 |
+
"The 'callback' parameter is not supported by Typer when using `add_typer` without a name",
|
| 1315 |
+
stacklevel=5,
|
| 1316 |
+
)
|
| 1317 |
+
for sub_command_name, sub_command in sub_group.commands.items():
|
| 1318 |
+
commands[sub_command_name] = sub_command
|
| 1319 |
+
solved_info = solve_typer_info_defaults(group_info)
|
| 1320 |
+
(
|
| 1321 |
+
params,
|
| 1322 |
+
convertors,
|
| 1323 |
+
context_param_name,
|
| 1324 |
+
) = get_params_convertors_ctx_param_name_from_function(solved_info.callback)
|
| 1325 |
+
cls = solved_info.cls or TyperGroup
|
| 1326 |
+
assert issubclass(cls, TyperGroup), f"{cls} should be a subclass of {TyperGroup}"
|
| 1327 |
+
group = cls(
|
| 1328 |
+
name=solved_info.name or "",
|
| 1329 |
+
commands=commands,
|
| 1330 |
+
invoke_without_command=solved_info.invoke_without_command,
|
| 1331 |
+
no_args_is_help=solved_info.no_args_is_help,
|
| 1332 |
+
subcommand_metavar=solved_info.subcommand_metavar,
|
| 1333 |
+
chain=solved_info.chain,
|
| 1334 |
+
result_callback=solved_info.result_callback,
|
| 1335 |
+
context_settings=solved_info.context_settings,
|
| 1336 |
+
callback=get_callback(
|
| 1337 |
+
callback=solved_info.callback,
|
| 1338 |
+
params=params,
|
| 1339 |
+
convertors=convertors,
|
| 1340 |
+
context_param_name=context_param_name,
|
| 1341 |
+
pretty_exceptions_short=pretty_exceptions_short,
|
| 1342 |
+
),
|
| 1343 |
+
params=params,
|
| 1344 |
+
help=solved_info.help,
|
| 1345 |
+
epilog=solved_info.epilog,
|
| 1346 |
+
short_help=solved_info.short_help,
|
| 1347 |
+
options_metavar=solved_info.options_metavar,
|
| 1348 |
+
add_help_option=solved_info.add_help_option,
|
| 1349 |
+
hidden=solved_info.hidden,
|
| 1350 |
+
deprecated=solved_info.deprecated,
|
| 1351 |
+
rich_markup_mode=rich_markup_mode,
|
| 1352 |
+
# Rich settings
|
| 1353 |
+
rich_help_panel=solved_info.rich_help_panel,
|
| 1354 |
+
suggest_commands=suggest_commands,
|
| 1355 |
+
)
|
| 1356 |
+
return group
|
| 1357 |
+
|
| 1358 |
+
|
| 1359 |
+
def get_command_name(name: str) -> str:
|
| 1360 |
+
return name.lower().replace("_", "-")
|
| 1361 |
+
|
| 1362 |
+
|
| 1363 |
+
def get_params_convertors_ctx_param_name_from_function(
|
| 1364 |
+
callback: Callable[..., Any] | None,
|
| 1365 |
+
) -> tuple[list[click.Argument | click.Option], dict[str, Any], str | None]:
|
| 1366 |
+
params = []
|
| 1367 |
+
convertors = {}
|
| 1368 |
+
context_param_name = None
|
| 1369 |
+
if callback:
|
| 1370 |
+
parameters = get_params_from_function(callback)
|
| 1371 |
+
for param_name, param in parameters.items():
|
| 1372 |
+
if lenient_issubclass(param.annotation, click.Context):
|
| 1373 |
+
context_param_name = param_name
|
| 1374 |
+
continue
|
| 1375 |
+
click_param, convertor = get_click_param(param)
|
| 1376 |
+
if convertor:
|
| 1377 |
+
convertors[param_name] = convertor
|
| 1378 |
+
params.append(click_param)
|
| 1379 |
+
return params, convertors, context_param_name
|
| 1380 |
+
|
| 1381 |
+
|
| 1382 |
+
def get_command_from_info(
|
| 1383 |
+
command_info: CommandInfo,
|
| 1384 |
+
*,
|
| 1385 |
+
pretty_exceptions_short: bool,
|
| 1386 |
+
rich_markup_mode: MarkupMode,
|
| 1387 |
+
) -> click.Command:
|
| 1388 |
+
assert command_info.callback, "A command must have a callback function"
|
| 1389 |
+
name = command_info.name or get_command_name(command_info.callback.__name__) # ty:ignore[unresolved-attribute]
|
| 1390 |
+
use_help = command_info.help
|
| 1391 |
+
if use_help is None:
|
| 1392 |
+
use_help = inspect.getdoc(command_info.callback)
|
| 1393 |
+
else:
|
| 1394 |
+
use_help = inspect.cleandoc(use_help)
|
| 1395 |
+
(
|
| 1396 |
+
params,
|
| 1397 |
+
convertors,
|
| 1398 |
+
context_param_name,
|
| 1399 |
+
) = get_params_convertors_ctx_param_name_from_function(command_info.callback)
|
| 1400 |
+
cls = command_info.cls or TyperCommand
|
| 1401 |
+
command = cls(
|
| 1402 |
+
name=name,
|
| 1403 |
+
context_settings=command_info.context_settings,
|
| 1404 |
+
callback=get_callback(
|
| 1405 |
+
callback=command_info.callback,
|
| 1406 |
+
params=params,
|
| 1407 |
+
convertors=convertors,
|
| 1408 |
+
context_param_name=context_param_name,
|
| 1409 |
+
pretty_exceptions_short=pretty_exceptions_short,
|
| 1410 |
+
),
|
| 1411 |
+
params=params, # type: ignore
|
| 1412 |
+
help=use_help,
|
| 1413 |
+
epilog=command_info.epilog,
|
| 1414 |
+
short_help=command_info.short_help,
|
| 1415 |
+
options_metavar=command_info.options_metavar,
|
| 1416 |
+
add_help_option=command_info.add_help_option,
|
| 1417 |
+
no_args_is_help=command_info.no_args_is_help,
|
| 1418 |
+
hidden=command_info.hidden,
|
| 1419 |
+
deprecated=command_info.deprecated,
|
| 1420 |
+
rich_markup_mode=rich_markup_mode,
|
| 1421 |
+
# Rich settings
|
| 1422 |
+
rich_help_panel=command_info.rich_help_panel,
|
| 1423 |
+
)
|
| 1424 |
+
return command
|
| 1425 |
+
|
| 1426 |
+
|
| 1427 |
+
def determine_type_convertor(type_: Any) -> Callable[[Any], Any] | None:
|
| 1428 |
+
convertor: Callable[[Any], Any] | None = None
|
| 1429 |
+
if lenient_issubclass(type_, Path):
|
| 1430 |
+
convertor = param_path_convertor
|
| 1431 |
+
if lenient_issubclass(type_, Enum):
|
| 1432 |
+
convertor = generate_enum_convertor(type_)
|
| 1433 |
+
return convertor
|
| 1434 |
+
|
| 1435 |
+
|
| 1436 |
+
def param_path_convertor(value: str | None = None) -> Path | None:
|
| 1437 |
+
if value is not None:
|
| 1438 |
+
# allow returning any subclass of Path created by an annotated parser without converting
|
| 1439 |
+
# it back to a Path
|
| 1440 |
+
return value if isinstance(value, Path) else Path(value)
|
| 1441 |
+
return None
|
| 1442 |
+
|
| 1443 |
+
|
| 1444 |
+
def generate_enum_convertor(enum: type[Enum]) -> Callable[[Any], Any]:
|
| 1445 |
+
val_map = {str(val.value): val for val in enum}
|
| 1446 |
+
|
| 1447 |
+
def convertor(value: Any) -> Any:
|
| 1448 |
+
if value is not None:
|
| 1449 |
+
val = str(value)
|
| 1450 |
+
if val in val_map:
|
| 1451 |
+
key = val_map[val]
|
| 1452 |
+
return enum(key)
|
| 1453 |
+
|
| 1454 |
+
return convertor
|
| 1455 |
+
|
| 1456 |
+
|
| 1457 |
+
def generate_list_convertor(
|
| 1458 |
+
convertor: Callable[[Any], Any] | None, default_value: Any | None
|
| 1459 |
+
) -> Callable[[Sequence[Any] | None], list[Any] | None]:
|
| 1460 |
+
def internal_convertor(value: Sequence[Any] | None) -> list[Any] | None:
|
| 1461 |
+
if (value is None) or (default_value is None and len(value) == 0):
|
| 1462 |
+
return None
|
| 1463 |
+
return [convertor(v) if convertor else v for v in value]
|
| 1464 |
+
|
| 1465 |
+
return internal_convertor
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
def generate_tuple_convertor(
|
| 1469 |
+
types: Sequence[Any],
|
| 1470 |
+
) -> Callable[[tuple[Any, ...] | None], tuple[Any, ...] | None]:
|
| 1471 |
+
convertors = [determine_type_convertor(type_) for type_ in types]
|
| 1472 |
+
|
| 1473 |
+
def internal_convertor(
|
| 1474 |
+
param_args: tuple[Any, ...] | None,
|
| 1475 |
+
) -> tuple[Any, ...] | None:
|
| 1476 |
+
if param_args is None:
|
| 1477 |
+
return None
|
| 1478 |
+
return tuple(
|
| 1479 |
+
convertor(arg) if convertor else arg
|
| 1480 |
+
for (convertor, arg) in zip(convertors, param_args, strict=False)
|
| 1481 |
+
)
|
| 1482 |
+
|
| 1483 |
+
return internal_convertor
|
| 1484 |
+
|
| 1485 |
+
|
| 1486 |
+
def get_callback(
|
| 1487 |
+
*,
|
| 1488 |
+
callback: Callable[..., Any] | None = None,
|
| 1489 |
+
params: Sequence[click.Parameter] = [],
|
| 1490 |
+
convertors: dict[str, Callable[[str], Any]] | None = None,
|
| 1491 |
+
context_param_name: str | None = None,
|
| 1492 |
+
pretty_exceptions_short: bool,
|
| 1493 |
+
) -> Callable[..., Any] | None:
|
| 1494 |
+
use_convertors = convertors or {}
|
| 1495 |
+
if not callback:
|
| 1496 |
+
return None
|
| 1497 |
+
parameters = get_params_from_function(callback)
|
| 1498 |
+
use_params: dict[str, Any] = {}
|
| 1499 |
+
for param_name in parameters:
|
| 1500 |
+
use_params[param_name] = None
|
| 1501 |
+
for param in params:
|
| 1502 |
+
if param.name:
|
| 1503 |
+
use_params[param.name] = param.default
|
| 1504 |
+
|
| 1505 |
+
def wrapper(**kwargs: Any) -> Any:
|
| 1506 |
+
_rich_traceback_guard = pretty_exceptions_short # noqa: F841
|
| 1507 |
+
for k, v in kwargs.items():
|
| 1508 |
+
if k in use_convertors:
|
| 1509 |
+
use_params[k] = use_convertors[k](v)
|
| 1510 |
+
else:
|
| 1511 |
+
use_params[k] = v
|
| 1512 |
+
if context_param_name:
|
| 1513 |
+
use_params[context_param_name] = click.get_current_context()
|
| 1514 |
+
return callback(**use_params)
|
| 1515 |
+
|
| 1516 |
+
update_wrapper(wrapper, callback)
|
| 1517 |
+
return wrapper
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
def get_click_type(
|
| 1521 |
+
*, annotation: Any, parameter_info: ParameterInfo
|
| 1522 |
+
) -> click.ParamType:
|
| 1523 |
+
if parameter_info.click_type is not None:
|
| 1524 |
+
return parameter_info.click_type
|
| 1525 |
+
|
| 1526 |
+
elif parameter_info.parser is not None:
|
| 1527 |
+
return click.types.FuncParamType(parameter_info.parser)
|
| 1528 |
+
|
| 1529 |
+
elif annotation is str:
|
| 1530 |
+
return click.STRING
|
| 1531 |
+
elif annotation is int:
|
| 1532 |
+
if parameter_info.min is not None or parameter_info.max is not None:
|
| 1533 |
+
min_ = None
|
| 1534 |
+
max_ = None
|
| 1535 |
+
if parameter_info.min is not None:
|
| 1536 |
+
min_ = int(parameter_info.min)
|
| 1537 |
+
if parameter_info.max is not None:
|
| 1538 |
+
max_ = int(parameter_info.max)
|
| 1539 |
+
return click.IntRange(min=min_, max=max_, clamp=parameter_info.clamp)
|
| 1540 |
+
else:
|
| 1541 |
+
return click.INT
|
| 1542 |
+
elif annotation is float:
|
| 1543 |
+
if parameter_info.min is not None or parameter_info.max is not None:
|
| 1544 |
+
return click.FloatRange(
|
| 1545 |
+
min=parameter_info.min,
|
| 1546 |
+
max=parameter_info.max,
|
| 1547 |
+
clamp=parameter_info.clamp,
|
| 1548 |
+
)
|
| 1549 |
+
else:
|
| 1550 |
+
return click.FLOAT
|
| 1551 |
+
elif annotation is bool:
|
| 1552 |
+
return click.BOOL
|
| 1553 |
+
elif annotation == UUID:
|
| 1554 |
+
return click.UUID
|
| 1555 |
+
elif annotation == datetime:
|
| 1556 |
+
return click.DateTime(formats=parameter_info.formats)
|
| 1557 |
+
elif (
|
| 1558 |
+
annotation == Path
|
| 1559 |
+
or parameter_info.allow_dash
|
| 1560 |
+
or parameter_info.path_type
|
| 1561 |
+
or parameter_info.resolve_path
|
| 1562 |
+
):
|
| 1563 |
+
return TyperPath(
|
| 1564 |
+
exists=parameter_info.exists,
|
| 1565 |
+
file_okay=parameter_info.file_okay,
|
| 1566 |
+
dir_okay=parameter_info.dir_okay,
|
| 1567 |
+
writable=parameter_info.writable,
|
| 1568 |
+
readable=parameter_info.readable,
|
| 1569 |
+
resolve_path=parameter_info.resolve_path,
|
| 1570 |
+
allow_dash=parameter_info.allow_dash,
|
| 1571 |
+
path_type=parameter_info.path_type,
|
| 1572 |
+
)
|
| 1573 |
+
elif lenient_issubclass(annotation, FileTextWrite):
|
| 1574 |
+
return click.File(
|
| 1575 |
+
mode=parameter_info.mode or "w",
|
| 1576 |
+
encoding=parameter_info.encoding,
|
| 1577 |
+
errors=parameter_info.errors,
|
| 1578 |
+
lazy=parameter_info.lazy,
|
| 1579 |
+
atomic=parameter_info.atomic,
|
| 1580 |
+
)
|
| 1581 |
+
elif lenient_issubclass(annotation, FileText):
|
| 1582 |
+
return click.File(
|
| 1583 |
+
mode=parameter_info.mode or "r",
|
| 1584 |
+
encoding=parameter_info.encoding,
|
| 1585 |
+
errors=parameter_info.errors,
|
| 1586 |
+
lazy=parameter_info.lazy,
|
| 1587 |
+
atomic=parameter_info.atomic,
|
| 1588 |
+
)
|
| 1589 |
+
elif lenient_issubclass(annotation, FileBinaryRead):
|
| 1590 |
+
return click.File(
|
| 1591 |
+
mode=parameter_info.mode or "rb",
|
| 1592 |
+
encoding=parameter_info.encoding,
|
| 1593 |
+
errors=parameter_info.errors,
|
| 1594 |
+
lazy=parameter_info.lazy,
|
| 1595 |
+
atomic=parameter_info.atomic,
|
| 1596 |
+
)
|
| 1597 |
+
elif lenient_issubclass(annotation, FileBinaryWrite):
|
| 1598 |
+
return click.File(
|
| 1599 |
+
mode=parameter_info.mode or "wb",
|
| 1600 |
+
encoding=parameter_info.encoding,
|
| 1601 |
+
errors=parameter_info.errors,
|
| 1602 |
+
lazy=parameter_info.lazy,
|
| 1603 |
+
atomic=parameter_info.atomic,
|
| 1604 |
+
)
|
| 1605 |
+
elif lenient_issubclass(annotation, Enum):
|
| 1606 |
+
# The custom TyperChoice is only needed for Click < 8.2.0, to parse the
|
| 1607 |
+
# command line values matching them to the enum values. Click 8.2.0 added
|
| 1608 |
+
# support for enum values but reading enum names.
|
| 1609 |
+
# Passing here the list of enum values (instead of just the enum) accounts for
|
| 1610 |
+
# Click < 8.2.0.
|
| 1611 |
+
return TyperChoice(
|
| 1612 |
+
[item.value for item in annotation],
|
| 1613 |
+
case_sensitive=parameter_info.case_sensitive,
|
| 1614 |
+
)
|
| 1615 |
+
elif is_literal_type(annotation):
|
| 1616 |
+
return click.Choice(
|
| 1617 |
+
literal_values(annotation),
|
| 1618 |
+
case_sensitive=parameter_info.case_sensitive,
|
| 1619 |
+
)
|
| 1620 |
+
raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover
|
| 1621 |
+
|
| 1622 |
+
|
| 1623 |
+
def lenient_issubclass(cls: Any, class_or_tuple: AnyType | tuple[AnyType, ...]) -> bool:
|
| 1624 |
+
return isinstance(cls, type) and issubclass(cls, class_or_tuple)
|
| 1625 |
+
|
| 1626 |
+
|
| 1627 |
+
def get_click_param(
|
| 1628 |
+
param: ParamMeta,
|
| 1629 |
+
) -> tuple[click.Argument | click.Option, Any]:
|
| 1630 |
+
# First, find out what will be:
|
| 1631 |
+
# * ParamInfo (ArgumentInfo or OptionInfo)
|
| 1632 |
+
# * default_value
|
| 1633 |
+
# * required
|
| 1634 |
+
default_value = None
|
| 1635 |
+
required = False
|
| 1636 |
+
if isinstance(param.default, ParameterInfo):
|
| 1637 |
+
parameter_info = param.default
|
| 1638 |
+
if parameter_info.default == Required:
|
| 1639 |
+
required = True
|
| 1640 |
+
else:
|
| 1641 |
+
default_value = parameter_info.default
|
| 1642 |
+
elif param.default == Required or param.default is param.empty:
|
| 1643 |
+
required = True
|
| 1644 |
+
parameter_info = ArgumentInfo()
|
| 1645 |
+
else:
|
| 1646 |
+
default_value = param.default
|
| 1647 |
+
parameter_info = OptionInfo()
|
| 1648 |
+
annotation: Any
|
| 1649 |
+
if param.annotation is not param.empty:
|
| 1650 |
+
annotation = param.annotation
|
| 1651 |
+
else:
|
| 1652 |
+
annotation = str
|
| 1653 |
+
main_type = annotation
|
| 1654 |
+
is_list = False
|
| 1655 |
+
is_tuple = False
|
| 1656 |
+
parameter_type: Any = None
|
| 1657 |
+
is_flag = None
|
| 1658 |
+
origin = get_origin(main_type)
|
| 1659 |
+
|
| 1660 |
+
if origin is not None:
|
| 1661 |
+
# Handle SomeType | None and Optional[SomeType]
|
| 1662 |
+
if is_union(origin):
|
| 1663 |
+
types = []
|
| 1664 |
+
for type_ in get_args(main_type):
|
| 1665 |
+
if type_ is NoneType:
|
| 1666 |
+
continue
|
| 1667 |
+
types.append(type_)
|
| 1668 |
+
assert len(types) == 1, "Typer Currently doesn't support Union types"
|
| 1669 |
+
main_type = types[0]
|
| 1670 |
+
origin = get_origin(main_type)
|
| 1671 |
+
# Handle Tuples and Lists
|
| 1672 |
+
if lenient_issubclass(origin, list):
|
| 1673 |
+
main_type = get_args(main_type)[0]
|
| 1674 |
+
assert not get_origin(main_type), (
|
| 1675 |
+
"List types with complex sub-types are not currently supported"
|
| 1676 |
+
)
|
| 1677 |
+
is_list = True
|
| 1678 |
+
elif lenient_issubclass(origin, tuple):
|
| 1679 |
+
types = []
|
| 1680 |
+
for type_ in get_args(main_type):
|
| 1681 |
+
assert not get_origin(type_), (
|
| 1682 |
+
"Tuple types with complex sub-types are not currently supported"
|
| 1683 |
+
)
|
| 1684 |
+
types.append(
|
| 1685 |
+
get_click_type(annotation=type_, parameter_info=parameter_info)
|
| 1686 |
+
)
|
| 1687 |
+
parameter_type = tuple(types)
|
| 1688 |
+
is_tuple = True
|
| 1689 |
+
if parameter_type is None:
|
| 1690 |
+
parameter_type = get_click_type(
|
| 1691 |
+
annotation=main_type, parameter_info=parameter_info
|
| 1692 |
+
)
|
| 1693 |
+
convertor = determine_type_convertor(main_type)
|
| 1694 |
+
if is_list:
|
| 1695 |
+
convertor = generate_list_convertor(
|
| 1696 |
+
convertor=convertor, default_value=default_value
|
| 1697 |
+
)
|
| 1698 |
+
if is_tuple:
|
| 1699 |
+
convertor = generate_tuple_convertor(get_args(main_type))
|
| 1700 |
+
if isinstance(parameter_info, OptionInfo):
|
| 1701 |
+
if main_type is bool:
|
| 1702 |
+
is_flag = True
|
| 1703 |
+
# Click doesn't accept a flag of type bool, only None, and then it sets it
|
| 1704 |
+
# to bool internally
|
| 1705 |
+
parameter_type = None
|
| 1706 |
+
default_option_name = get_command_name(param.name)
|
| 1707 |
+
if is_flag:
|
| 1708 |
+
default_option_declaration = (
|
| 1709 |
+
f"--{default_option_name}/--no-{default_option_name}"
|
| 1710 |
+
)
|
| 1711 |
+
else:
|
| 1712 |
+
default_option_declaration = f"--{default_option_name}"
|
| 1713 |
+
param_decls = [param.name]
|
| 1714 |
+
if parameter_info.param_decls:
|
| 1715 |
+
param_decls.extend(parameter_info.param_decls)
|
| 1716 |
+
else:
|
| 1717 |
+
param_decls.append(default_option_declaration)
|
| 1718 |
+
return (
|
| 1719 |
+
TyperOption(
|
| 1720 |
+
# Option
|
| 1721 |
+
param_decls=param_decls,
|
| 1722 |
+
show_default=parameter_info.show_default,
|
| 1723 |
+
prompt=parameter_info.prompt,
|
| 1724 |
+
confirmation_prompt=parameter_info.confirmation_prompt,
|
| 1725 |
+
prompt_required=parameter_info.prompt_required,
|
| 1726 |
+
hide_input=parameter_info.hide_input,
|
| 1727 |
+
is_flag=is_flag,
|
| 1728 |
+
multiple=is_list,
|
| 1729 |
+
count=parameter_info.count,
|
| 1730 |
+
allow_from_autoenv=parameter_info.allow_from_autoenv,
|
| 1731 |
+
type=parameter_type,
|
| 1732 |
+
help=parameter_info.help,
|
| 1733 |
+
hidden=parameter_info.hidden,
|
| 1734 |
+
show_choices=parameter_info.show_choices,
|
| 1735 |
+
show_envvar=parameter_info.show_envvar,
|
| 1736 |
+
# Parameter
|
| 1737 |
+
required=required,
|
| 1738 |
+
default=default_value,
|
| 1739 |
+
callback=get_param_callback(
|
| 1740 |
+
callback=parameter_info.callback, convertor=convertor
|
| 1741 |
+
),
|
| 1742 |
+
metavar=parameter_info.metavar,
|
| 1743 |
+
expose_value=parameter_info.expose_value,
|
| 1744 |
+
is_eager=parameter_info.is_eager,
|
| 1745 |
+
envvar=parameter_info.envvar,
|
| 1746 |
+
shell_complete=parameter_info.shell_complete,
|
| 1747 |
+
autocompletion=get_param_completion(parameter_info.autocompletion),
|
| 1748 |
+
# Rich settings
|
| 1749 |
+
rich_help_panel=parameter_info.rich_help_panel,
|
| 1750 |
+
),
|
| 1751 |
+
convertor,
|
| 1752 |
+
)
|
| 1753 |
+
elif isinstance(parameter_info, ArgumentInfo):
|
| 1754 |
+
param_decls = [param.name]
|
| 1755 |
+
nargs = None
|
| 1756 |
+
if is_list:
|
| 1757 |
+
nargs = -1
|
| 1758 |
+
return (
|
| 1759 |
+
TyperArgument(
|
| 1760 |
+
# Argument
|
| 1761 |
+
param_decls=param_decls,
|
| 1762 |
+
type=parameter_type,
|
| 1763 |
+
required=required,
|
| 1764 |
+
nargs=nargs,
|
| 1765 |
+
# TyperArgument
|
| 1766 |
+
show_default=parameter_info.show_default,
|
| 1767 |
+
show_choices=parameter_info.show_choices,
|
| 1768 |
+
show_envvar=parameter_info.show_envvar,
|
| 1769 |
+
help=parameter_info.help,
|
| 1770 |
+
hidden=parameter_info.hidden,
|
| 1771 |
+
# Parameter
|
| 1772 |
+
default=default_value,
|
| 1773 |
+
callback=get_param_callback(
|
| 1774 |
+
callback=parameter_info.callback, convertor=convertor
|
| 1775 |
+
),
|
| 1776 |
+
metavar=parameter_info.metavar,
|
| 1777 |
+
expose_value=parameter_info.expose_value,
|
| 1778 |
+
is_eager=parameter_info.is_eager,
|
| 1779 |
+
envvar=parameter_info.envvar,
|
| 1780 |
+
shell_complete=parameter_info.shell_complete,
|
| 1781 |
+
autocompletion=get_param_completion(parameter_info.autocompletion),
|
| 1782 |
+
# Rich settings
|
| 1783 |
+
rich_help_panel=parameter_info.rich_help_panel,
|
| 1784 |
+
),
|
| 1785 |
+
convertor,
|
| 1786 |
+
)
|
| 1787 |
+
raise AssertionError("A click.Parameter should be returned") # pragma: no cover
|
| 1788 |
+
|
| 1789 |
+
|
| 1790 |
+
def get_param_callback(
|
| 1791 |
+
*,
|
| 1792 |
+
callback: Callable[..., Any] | None = None,
|
| 1793 |
+
convertor: Callable[..., Any] | None = None,
|
| 1794 |
+
) -> Callable[..., Any] | None:
|
| 1795 |
+
if not callback:
|
| 1796 |
+
return None
|
| 1797 |
+
parameters = get_params_from_function(callback)
|
| 1798 |
+
ctx_name = None
|
| 1799 |
+
click_param_name = None
|
| 1800 |
+
value_name = None
|
| 1801 |
+
untyped_names: list[str] = []
|
| 1802 |
+
for param_name, param_sig in parameters.items():
|
| 1803 |
+
if lenient_issubclass(param_sig.annotation, click.Context):
|
| 1804 |
+
ctx_name = param_name
|
| 1805 |
+
elif lenient_issubclass(param_sig.annotation, click.Parameter):
|
| 1806 |
+
click_param_name = param_name
|
| 1807 |
+
else:
|
| 1808 |
+
untyped_names.append(param_name)
|
| 1809 |
+
# Extract value param name first
|
| 1810 |
+
if untyped_names:
|
| 1811 |
+
value_name = untyped_names.pop()
|
| 1812 |
+
# If context and Click param were not typed (old/Click callback style) extract them
|
| 1813 |
+
if untyped_names:
|
| 1814 |
+
if ctx_name is None:
|
| 1815 |
+
ctx_name = untyped_names.pop(0)
|
| 1816 |
+
if click_param_name is None:
|
| 1817 |
+
if untyped_names:
|
| 1818 |
+
click_param_name = untyped_names.pop(0)
|
| 1819 |
+
if untyped_names:
|
| 1820 |
+
raise click.ClickException(
|
| 1821 |
+
"Too many CLI parameter callback function parameters"
|
| 1822 |
+
)
|
| 1823 |
+
|
| 1824 |
+
def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
|
| 1825 |
+
use_params: dict[str, Any] = {}
|
| 1826 |
+
if ctx_name:
|
| 1827 |
+
use_params[ctx_name] = ctx
|
| 1828 |
+
if click_param_name:
|
| 1829 |
+
use_params[click_param_name] = param
|
| 1830 |
+
if value_name:
|
| 1831 |
+
if convertor:
|
| 1832 |
+
use_value = convertor(value)
|
| 1833 |
+
else:
|
| 1834 |
+
use_value = value
|
| 1835 |
+
use_params[value_name] = use_value
|
| 1836 |
+
return callback(**use_params)
|
| 1837 |
+
|
| 1838 |
+
update_wrapper(wrapper, callback)
|
| 1839 |
+
return wrapper
|
| 1840 |
+
|
| 1841 |
+
|
| 1842 |
+
def get_param_completion(
|
| 1843 |
+
callback: Callable[..., Any] | None = None,
|
| 1844 |
+
) -> Callable[..., Any] | None:
|
| 1845 |
+
if not callback:
|
| 1846 |
+
return None
|
| 1847 |
+
parameters = get_params_from_function(callback)
|
| 1848 |
+
ctx_name = None
|
| 1849 |
+
args_name = None
|
| 1850 |
+
incomplete_name = None
|
| 1851 |
+
unassigned_params = list(parameters.values())
|
| 1852 |
+
for param_sig in unassigned_params[:]:
|
| 1853 |
+
origin = get_origin(param_sig.annotation)
|
| 1854 |
+
if lenient_issubclass(param_sig.annotation, click.Context):
|
| 1855 |
+
ctx_name = param_sig.name
|
| 1856 |
+
unassigned_params.remove(param_sig)
|
| 1857 |
+
elif lenient_issubclass(origin, list):
|
| 1858 |
+
args_name = param_sig.name
|
| 1859 |
+
unassigned_params.remove(param_sig)
|
| 1860 |
+
elif lenient_issubclass(param_sig.annotation, str):
|
| 1861 |
+
incomplete_name = param_sig.name
|
| 1862 |
+
unassigned_params.remove(param_sig)
|
| 1863 |
+
# If there are still unassigned parameters (not typed), extract by name
|
| 1864 |
+
for param_sig in unassigned_params[:]:
|
| 1865 |
+
if ctx_name is None and param_sig.name == "ctx":
|
| 1866 |
+
ctx_name = param_sig.name
|
| 1867 |
+
unassigned_params.remove(param_sig)
|
| 1868 |
+
elif args_name is None and param_sig.name == "args":
|
| 1869 |
+
args_name = param_sig.name
|
| 1870 |
+
unassigned_params.remove(param_sig)
|
| 1871 |
+
elif incomplete_name is None and param_sig.name == "incomplete":
|
| 1872 |
+
incomplete_name = param_sig.name
|
| 1873 |
+
unassigned_params.remove(param_sig)
|
| 1874 |
+
# Extract value param name first
|
| 1875 |
+
if unassigned_params:
|
| 1876 |
+
show_params = " ".join([param.name for param in unassigned_params])
|
| 1877 |
+
raise click.ClickException(
|
| 1878 |
+
f"Invalid autocompletion callback parameters: {show_params}"
|
| 1879 |
+
)
|
| 1880 |
+
|
| 1881 |
+
def wrapper(ctx: click.Context, args: list[str], incomplete: str | None) -> Any:
|
| 1882 |
+
use_params: dict[str, Any] = {}
|
| 1883 |
+
if ctx_name:
|
| 1884 |
+
use_params[ctx_name] = ctx
|
| 1885 |
+
if args_name:
|
| 1886 |
+
use_params[args_name] = args
|
| 1887 |
+
if incomplete_name:
|
| 1888 |
+
use_params[incomplete_name] = incomplete
|
| 1889 |
+
return callback(**use_params)
|
| 1890 |
+
|
| 1891 |
+
update_wrapper(wrapper, callback)
|
| 1892 |
+
return wrapper
|
| 1893 |
+
|
| 1894 |
+
|
| 1895 |
+
def run(
|
| 1896 |
+
function: Annotated[
|
| 1897 |
+
Callable[..., Any],
|
| 1898 |
+
Doc(
|
| 1899 |
+
"""
|
| 1900 |
+
The function that should power this CLI application.
|
| 1901 |
+
"""
|
| 1902 |
+
),
|
| 1903 |
+
],
|
| 1904 |
+
) -> None:
|
| 1905 |
+
"""
|
| 1906 |
+
This function converts a given function to a CLI application with `Typer()` and executes it.
|
| 1907 |
+
|
| 1908 |
+
## Example
|
| 1909 |
+
|
| 1910 |
+
```python
|
| 1911 |
+
import typer
|
| 1912 |
+
|
| 1913 |
+
def main(name: str):
|
| 1914 |
+
print(f"Hello {name}")
|
| 1915 |
+
|
| 1916 |
+
if __name__ == "__main__":
|
| 1917 |
+
typer.run(main)
|
| 1918 |
+
```
|
| 1919 |
+
"""
|
| 1920 |
+
app = Typer(add_completion=False)
|
| 1921 |
+
app.command()(function)
|
| 1922 |
+
app()
|
| 1923 |
+
|
| 1924 |
+
|
| 1925 |
+
def _is_macos() -> bool:
|
| 1926 |
+
return platform.system() == "Darwin"
|
| 1927 |
+
|
| 1928 |
+
|
| 1929 |
+
def _is_linux_or_bsd() -> bool:
|
| 1930 |
+
if platform.system() == "Linux":
|
| 1931 |
+
return True
|
| 1932 |
+
|
| 1933 |
+
return "BSD" in platform.system()
|
| 1934 |
+
|
| 1935 |
+
|
| 1936 |
+
def launch(
|
| 1937 |
+
url: Annotated[
|
| 1938 |
+
str,
|
| 1939 |
+
Doc(
|
| 1940 |
+
"""
|
| 1941 |
+
URL or filename of the thing to launch.
|
| 1942 |
+
"""
|
| 1943 |
+
),
|
| 1944 |
+
],
|
| 1945 |
+
wait: Annotated[
|
| 1946 |
+
bool,
|
| 1947 |
+
Doc(
|
| 1948 |
+
"""
|
| 1949 |
+
Wait for the program to exit before returning. This only works if the launched program blocks.
|
| 1950 |
+
In particular, `xdg-open` on Linux does not block.
|
| 1951 |
+
"""
|
| 1952 |
+
),
|
| 1953 |
+
] = False,
|
| 1954 |
+
locate: Annotated[
|
| 1955 |
+
bool,
|
| 1956 |
+
Doc(
|
| 1957 |
+
"""
|
| 1958 |
+
If this is set to `True`, then instead of launching the application associated with the URL, it will attempt to
|
| 1959 |
+
launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.
|
| 1960 |
+
"""
|
| 1961 |
+
),
|
| 1962 |
+
] = False,
|
| 1963 |
+
) -> int:
|
| 1964 |
+
"""
|
| 1965 |
+
This function launches the given URL (or filename) in the default
|
| 1966 |
+
viewer application for this file type. If this is an executable, it
|
| 1967 |
+
might launch the executable in a new session. The return value is
|
| 1968 |
+
the exit code of the launched application. Usually, `0` indicates
|
| 1969 |
+
success.
|
| 1970 |
+
|
| 1971 |
+
This function handles url in different operating systems separately:
|
| 1972 |
+
- On macOS (Darwin), it uses the `open` command.
|
| 1973 |
+
- On Linux and BSD, it uses `xdg-open` if available.
|
| 1974 |
+
- On Windows (and other OSes), it uses the standard webbrowser module.
|
| 1975 |
+
|
| 1976 |
+
The function avoids, when possible, using the webbrowser module on Linux and macOS
|
| 1977 |
+
to prevent spammy terminal messages from some browsers (e.g., Chrome).
|
| 1978 |
+
|
| 1979 |
+
## Examples
|
| 1980 |
+
```python
|
| 1981 |
+
import typer
|
| 1982 |
+
|
| 1983 |
+
typer.launch("https://typer.tiangolo.com/")
|
| 1984 |
+
```
|
| 1985 |
+
|
| 1986 |
+
```python
|
| 1987 |
+
import typer
|
| 1988 |
+
|
| 1989 |
+
typer.launch("/my/downloaded/file", locate=True)
|
| 1990 |
+
```
|
| 1991 |
+
"""
|
| 1992 |
+
|
| 1993 |
+
if url.startswith("http://") or url.startswith("https://"):
|
| 1994 |
+
if _is_macos():
|
| 1995 |
+
return subprocess.Popen(
|
| 1996 |
+
["open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
|
| 1997 |
+
).wait()
|
| 1998 |
+
|
| 1999 |
+
has_xdg_open = _is_linux_or_bsd() and shutil.which("xdg-open") is not None
|
| 2000 |
+
|
| 2001 |
+
if has_xdg_open:
|
| 2002 |
+
return subprocess.Popen(
|
| 2003 |
+
["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
|
| 2004 |
+
).wait()
|
| 2005 |
+
|
| 2006 |
+
import webbrowser
|
| 2007 |
+
|
| 2008 |
+
webbrowser.open(url)
|
| 2009 |
+
|
| 2010 |
+
return 0
|
| 2011 |
+
|
| 2012 |
+
else:
|
| 2013 |
+
return click.launch(url)
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L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
|
| 10 |
+
|
| 11 |
+
import click
|
| 12 |
+
import click.shell_completion
|
| 13 |
+
|
| 14 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 15 |
+
from .core import TyperCommand, TyperGroup
|
| 16 |
+
from .main import Typer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
NoneType = type(None)
|
| 20 |
+
|
| 21 |
+
AnyType = type[Any]
|
| 22 |
+
|
| 23 |
+
Required = ...
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Context(click.Context):
|
| 27 |
+
"""
|
| 28 |
+
The [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) has some additional data about the current execution of your program.
|
| 29 |
+
When declaring it in a [callback](https://typer.tiangolo.com/tutorial/options/callback-and-context/) function,
|
| 30 |
+
you can access this additional information.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class FileText(io.TextIOWrapper):
|
| 37 |
+
"""
|
| 38 |
+
Gives you a file-like object for reading text, and you will get a `str` data from it.
|
| 39 |
+
The default mode of this class is `mode="r"`.
|
| 40 |
+
|
| 41 |
+
**Example**
|
| 42 |
+
|
| 43 |
+
```python
|
| 44 |
+
from typing import Annotated
|
| 45 |
+
|
| 46 |
+
import typer
|
| 47 |
+
|
| 48 |
+
app = typer.Typer()
|
| 49 |
+
|
| 50 |
+
@app.command()
|
| 51 |
+
def main(config: Annotated[typer.FileText, typer.Option()]):
|
| 52 |
+
for line in config:
|
| 53 |
+
print(f"Config line: {line}")
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
app()
|
| 57 |
+
```
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class FileTextWrite(FileText):
|
| 64 |
+
"""
|
| 65 |
+
You can use this class for writing text. Alternatively, you can use `FileText` with `mode="w"`.
|
| 66 |
+
The default mode of this class is `mode="w"`.
|
| 67 |
+
|
| 68 |
+
**Example**
|
| 69 |
+
|
| 70 |
+
```python
|
| 71 |
+
from typing import Annotated
|
| 72 |
+
|
| 73 |
+
import typer
|
| 74 |
+
|
| 75 |
+
app = typer.Typer()
|
| 76 |
+
|
| 77 |
+
@app.command()
|
| 78 |
+
def main(config: Annotated[typer.FileTextWrite, typer.Option()]):
|
| 79 |
+
config.write("Some config written by the app")
|
| 80 |
+
print("Config written")
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
app()
|
| 84 |
+
```
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
pass
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class FileBinaryRead(io.BufferedReader):
|
| 91 |
+
"""
|
| 92 |
+
You can use this class to read binary data, receiving `bytes`.
|
| 93 |
+
The default mode of this class is `mode="rb"`.
|
| 94 |
+
It is useful for reading binary files like images:
|
| 95 |
+
|
| 96 |
+
**Example**
|
| 97 |
+
|
| 98 |
+
```python
|
| 99 |
+
from typing import Annotated
|
| 100 |
+
|
| 101 |
+
import typer
|
| 102 |
+
|
| 103 |
+
app = typer.Typer()
|
| 104 |
+
|
| 105 |
+
@app.command()
|
| 106 |
+
def main(file: Annotated[typer.FileBinaryRead, typer.Option()]):
|
| 107 |
+
processed_total = 0
|
| 108 |
+
for bytes_chunk in file:
|
| 109 |
+
# Process the bytes in bytes_chunk
|
| 110 |
+
processed_total += len(bytes_chunk)
|
| 111 |
+
print(f"Processed bytes total: {processed_total}")
|
| 112 |
+
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
app()
|
| 115 |
+
```
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
pass
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class FileBinaryWrite(io.BufferedWriter):
|
| 122 |
+
"""
|
| 123 |
+
You can use this class to write binary data: you pass `bytes` to it instead of strings.
|
| 124 |
+
The default mode of this class is `mode="wb"`.
|
| 125 |
+
It is useful for writing binary files like images:
|
| 126 |
+
|
| 127 |
+
**Example**
|
| 128 |
+
|
| 129 |
+
```python
|
| 130 |
+
from typing import Annotated
|
| 131 |
+
|
| 132 |
+
import typer
|
| 133 |
+
|
| 134 |
+
app = typer.Typer()
|
| 135 |
+
|
| 136 |
+
@app.command()
|
| 137 |
+
def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]):
|
| 138 |
+
first_line_str = "some settings\\n"
|
| 139 |
+
# You cannot write str directly to a binary file; encode it first
|
| 140 |
+
first_line_bytes = first_line_str.encode("utf-8")
|
| 141 |
+
# Then you can write the bytes
|
| 142 |
+
file.write(first_line_bytes)
|
| 143 |
+
# This is already bytes, it starts with b"
|
| 144 |
+
second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"
|
| 145 |
+
file.write(second_line)
|
| 146 |
+
print("Binary file written")
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
app()
|
| 150 |
+
```
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
pass
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class CallbackParam(click.Parameter):
|
| 157 |
+
"""
|
| 158 |
+
In a callback function, you can declare a function parameter with type `CallbackParam`
|
| 159 |
+
to access the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
pass
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class DefaultPlaceholder:
|
| 166 |
+
"""
|
| 167 |
+
You shouldn't use this class directly.
|
| 168 |
+
|
| 169 |
+
It's used internally to recognize when a default value has been overwritten, even
|
| 170 |
+
if the new value is `None`.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
def __init__(self, value: Any):
|
| 174 |
+
self.value = value
|
| 175 |
+
|
| 176 |
+
def __bool__(self) -> bool:
|
| 177 |
+
return bool(self.value)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
DefaultType = TypeVar("DefaultType")
|
| 181 |
+
|
| 182 |
+
CommandFunctionType = TypeVar("CommandFunctionType", bound=Callable[..., Any])
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def Default(value: DefaultType) -> DefaultType:
|
| 186 |
+
"""
|
| 187 |
+
You shouldn't use this function directly.
|
| 188 |
+
|
| 189 |
+
It's used internally to recognize when a default value has been overwritten, even
|
| 190 |
+
if the new value is `None`.
|
| 191 |
+
"""
|
| 192 |
+
return DefaultPlaceholder(value) # type: ignore
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class CommandInfo:
|
| 196 |
+
def __init__(
|
| 197 |
+
self,
|
| 198 |
+
name: str | None = None,
|
| 199 |
+
*,
|
| 200 |
+
cls: type["TyperCommand"] | None = None,
|
| 201 |
+
context_settings: dict[Any, Any] | None = None,
|
| 202 |
+
callback: Callable[..., Any] | None = None,
|
| 203 |
+
help: str | None = None,
|
| 204 |
+
epilog: str | None = None,
|
| 205 |
+
short_help: str | None = None,
|
| 206 |
+
options_metavar: str = "[OPTIONS]",
|
| 207 |
+
add_help_option: bool = True,
|
| 208 |
+
no_args_is_help: bool = False,
|
| 209 |
+
hidden: bool = False,
|
| 210 |
+
deprecated: bool = False,
|
| 211 |
+
# Rich settings
|
| 212 |
+
rich_help_panel: str | None = None,
|
| 213 |
+
):
|
| 214 |
+
self.name = name
|
| 215 |
+
self.cls = cls
|
| 216 |
+
self.context_settings = context_settings
|
| 217 |
+
self.callback = callback
|
| 218 |
+
self.help = help
|
| 219 |
+
self.epilog = epilog
|
| 220 |
+
self.short_help = short_help
|
| 221 |
+
self.options_metavar = options_metavar
|
| 222 |
+
self.add_help_option = add_help_option
|
| 223 |
+
self.no_args_is_help = no_args_is_help
|
| 224 |
+
self.hidden = hidden
|
| 225 |
+
self.deprecated = deprecated
|
| 226 |
+
# Rich settings
|
| 227 |
+
self.rich_help_panel = rich_help_panel
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class TyperInfo:
|
| 231 |
+
def __init__(
|
| 232 |
+
self,
|
| 233 |
+
typer_instance: Optional["Typer"] = Default(None),
|
| 234 |
+
*,
|
| 235 |
+
name: str | None = Default(None),
|
| 236 |
+
cls: type["TyperGroup"] | None = Default(None),
|
| 237 |
+
invoke_without_command: bool = Default(False),
|
| 238 |
+
no_args_is_help: bool = Default(False),
|
| 239 |
+
subcommand_metavar: str | None = Default(None),
|
| 240 |
+
chain: bool = Default(False),
|
| 241 |
+
result_callback: Callable[..., Any] | None = Default(None),
|
| 242 |
+
# Command
|
| 243 |
+
context_settings: dict[Any, Any] | None = Default(None),
|
| 244 |
+
callback: Callable[..., Any] | None = Default(None),
|
| 245 |
+
help: str | None = Default(None),
|
| 246 |
+
epilog: str | None = Default(None),
|
| 247 |
+
short_help: str | None = Default(None),
|
| 248 |
+
options_metavar: str = Default("[OPTIONS]"),
|
| 249 |
+
add_help_option: bool = Default(True),
|
| 250 |
+
hidden: bool = Default(False),
|
| 251 |
+
deprecated: bool = Default(False),
|
| 252 |
+
# Rich settings
|
| 253 |
+
rich_help_panel: str | None = Default(None),
|
| 254 |
+
):
|
| 255 |
+
self.typer_instance = typer_instance
|
| 256 |
+
self.name = name
|
| 257 |
+
self.cls = cls
|
| 258 |
+
self.invoke_without_command = invoke_without_command
|
| 259 |
+
self.no_args_is_help = no_args_is_help
|
| 260 |
+
self.subcommand_metavar = subcommand_metavar
|
| 261 |
+
self.chain = chain
|
| 262 |
+
self.result_callback = result_callback
|
| 263 |
+
self.context_settings = context_settings
|
| 264 |
+
self.callback = callback
|
| 265 |
+
self.help = help
|
| 266 |
+
self.epilog = epilog
|
| 267 |
+
self.short_help = short_help
|
| 268 |
+
self.options_metavar = options_metavar
|
| 269 |
+
self.add_help_option = add_help_option
|
| 270 |
+
self.hidden = hidden
|
| 271 |
+
self.deprecated = deprecated
|
| 272 |
+
self.rich_help_panel = rich_help_panel
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class ParameterInfo:
|
| 276 |
+
def __init__(
|
| 277 |
+
self,
|
| 278 |
+
*,
|
| 279 |
+
default: Any | None = None,
|
| 280 |
+
param_decls: Sequence[str] | None = None,
|
| 281 |
+
callback: Callable[..., Any] | None = None,
|
| 282 |
+
metavar: str | None = None,
|
| 283 |
+
expose_value: bool = True,
|
| 284 |
+
is_eager: bool = False,
|
| 285 |
+
envvar: str | list[str] | None = None,
|
| 286 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 287 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 288 |
+
shell_complete: Callable[
|
| 289 |
+
[click.Context, click.Parameter, str],
|
| 290 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 291 |
+
]
|
| 292 |
+
| None = None,
|
| 293 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 294 |
+
default_factory: Callable[[], Any] | None = None,
|
| 295 |
+
# Custom type
|
| 296 |
+
parser: Callable[[str], Any] | None = None,
|
| 297 |
+
click_type: click.ParamType | None = None,
|
| 298 |
+
# TyperArgument
|
| 299 |
+
show_default: bool | str = True,
|
| 300 |
+
show_choices: bool = True,
|
| 301 |
+
show_envvar: bool = True,
|
| 302 |
+
help: str | None = None,
|
| 303 |
+
hidden: bool = False,
|
| 304 |
+
# Choice
|
| 305 |
+
case_sensitive: bool = True,
|
| 306 |
+
# Numbers
|
| 307 |
+
min: int | float | None = None,
|
| 308 |
+
max: int | float | None = None,
|
| 309 |
+
clamp: bool = False,
|
| 310 |
+
# DateTime
|
| 311 |
+
formats: list[str] | None = None,
|
| 312 |
+
# File
|
| 313 |
+
mode: str | None = None,
|
| 314 |
+
encoding: str | None = None,
|
| 315 |
+
errors: str | None = "strict",
|
| 316 |
+
lazy: bool | None = None,
|
| 317 |
+
atomic: bool = False,
|
| 318 |
+
# Path
|
| 319 |
+
exists: bool = False,
|
| 320 |
+
file_okay: bool = True,
|
| 321 |
+
dir_okay: bool = True,
|
| 322 |
+
writable: bool = False,
|
| 323 |
+
readable: bool = True,
|
| 324 |
+
resolve_path: bool = False,
|
| 325 |
+
allow_dash: bool = False,
|
| 326 |
+
path_type: None | type[str] | type[bytes] = None,
|
| 327 |
+
# Rich settings
|
| 328 |
+
rich_help_panel: str | None = None,
|
| 329 |
+
):
|
| 330 |
+
# Check if user has provided multiple custom parsers
|
| 331 |
+
if parser and click_type:
|
| 332 |
+
raise ValueError(
|
| 333 |
+
"Multiple custom type parsers provided. "
|
| 334 |
+
"`parser` and `click_type` may not both be provided."
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
self.default = default
|
| 338 |
+
self.param_decls = param_decls
|
| 339 |
+
self.callback = callback
|
| 340 |
+
self.metavar = metavar
|
| 341 |
+
self.expose_value = expose_value
|
| 342 |
+
self.is_eager = is_eager
|
| 343 |
+
self.envvar = envvar
|
| 344 |
+
self.shell_complete = shell_complete
|
| 345 |
+
self.autocompletion = autocompletion
|
| 346 |
+
self.default_factory = default_factory
|
| 347 |
+
# Custom type
|
| 348 |
+
self.parser = parser
|
| 349 |
+
self.click_type = click_type
|
| 350 |
+
# TyperArgument
|
| 351 |
+
self.show_default = show_default
|
| 352 |
+
self.show_choices = show_choices
|
| 353 |
+
self.show_envvar = show_envvar
|
| 354 |
+
self.help = help
|
| 355 |
+
self.hidden = hidden
|
| 356 |
+
# Choice
|
| 357 |
+
self.case_sensitive = case_sensitive
|
| 358 |
+
# Numbers
|
| 359 |
+
self.min = min
|
| 360 |
+
self.max = max
|
| 361 |
+
self.clamp = clamp
|
| 362 |
+
# DateTime
|
| 363 |
+
self.formats = formats
|
| 364 |
+
# File
|
| 365 |
+
self.mode = mode
|
| 366 |
+
self.encoding = encoding
|
| 367 |
+
self.errors = errors
|
| 368 |
+
self.lazy = lazy
|
| 369 |
+
self.atomic = atomic
|
| 370 |
+
# Path
|
| 371 |
+
self.exists = exists
|
| 372 |
+
self.file_okay = file_okay
|
| 373 |
+
self.dir_okay = dir_okay
|
| 374 |
+
self.writable = writable
|
| 375 |
+
self.readable = readable
|
| 376 |
+
self.resolve_path = resolve_path
|
| 377 |
+
self.allow_dash = allow_dash
|
| 378 |
+
self.path_type = path_type
|
| 379 |
+
# Rich settings
|
| 380 |
+
self.rich_help_panel = rich_help_panel
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
class OptionInfo(ParameterInfo):
|
| 384 |
+
def __init__(
|
| 385 |
+
self,
|
| 386 |
+
*,
|
| 387 |
+
# ParameterInfo
|
| 388 |
+
default: Any | None = None,
|
| 389 |
+
param_decls: Sequence[str] | None = None,
|
| 390 |
+
callback: Callable[..., Any] | None = None,
|
| 391 |
+
metavar: str | None = None,
|
| 392 |
+
expose_value: bool = True,
|
| 393 |
+
is_eager: bool = False,
|
| 394 |
+
envvar: str | list[str] | None = None,
|
| 395 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 396 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 397 |
+
shell_complete: Callable[
|
| 398 |
+
[click.Context, click.Parameter, str],
|
| 399 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 400 |
+
]
|
| 401 |
+
| None = None,
|
| 402 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 403 |
+
default_factory: Callable[[], Any] | None = None,
|
| 404 |
+
# Custom type
|
| 405 |
+
parser: Callable[[str], Any] | None = None,
|
| 406 |
+
click_type: click.ParamType | None = None,
|
| 407 |
+
# Option
|
| 408 |
+
show_default: bool | str = True,
|
| 409 |
+
prompt: bool | str = False,
|
| 410 |
+
confirmation_prompt: bool = False,
|
| 411 |
+
prompt_required: bool = True,
|
| 412 |
+
hide_input: bool = False,
|
| 413 |
+
# TODO: remove is_flag and flag_value in a future release
|
| 414 |
+
is_flag: bool | None = None,
|
| 415 |
+
flag_value: Any | None = None,
|
| 416 |
+
count: bool = False,
|
| 417 |
+
allow_from_autoenv: bool = True,
|
| 418 |
+
help: str | None = None,
|
| 419 |
+
hidden: bool = False,
|
| 420 |
+
show_choices: bool = True,
|
| 421 |
+
show_envvar: bool = True,
|
| 422 |
+
# Choice
|
| 423 |
+
case_sensitive: bool = True,
|
| 424 |
+
# Numbers
|
| 425 |
+
min: int | float | None = None,
|
| 426 |
+
max: int | float | None = None,
|
| 427 |
+
clamp: bool = False,
|
| 428 |
+
# DateTime
|
| 429 |
+
formats: list[str] | None = None,
|
| 430 |
+
# File
|
| 431 |
+
mode: str | None = None,
|
| 432 |
+
encoding: str | None = None,
|
| 433 |
+
errors: str | None = "strict",
|
| 434 |
+
lazy: bool | None = None,
|
| 435 |
+
atomic: bool = False,
|
| 436 |
+
# Path
|
| 437 |
+
exists: bool = False,
|
| 438 |
+
file_okay: bool = True,
|
| 439 |
+
dir_okay: bool = True,
|
| 440 |
+
writable: bool = False,
|
| 441 |
+
readable: bool = True,
|
| 442 |
+
resolve_path: bool = False,
|
| 443 |
+
allow_dash: bool = False,
|
| 444 |
+
path_type: None | type[str] | type[bytes] = None,
|
| 445 |
+
# Rich settings
|
| 446 |
+
rich_help_panel: str | None = None,
|
| 447 |
+
):
|
| 448 |
+
super().__init__(
|
| 449 |
+
default=default,
|
| 450 |
+
param_decls=param_decls,
|
| 451 |
+
callback=callback,
|
| 452 |
+
metavar=metavar,
|
| 453 |
+
expose_value=expose_value,
|
| 454 |
+
is_eager=is_eager,
|
| 455 |
+
envvar=envvar,
|
| 456 |
+
shell_complete=shell_complete,
|
| 457 |
+
autocompletion=autocompletion,
|
| 458 |
+
default_factory=default_factory,
|
| 459 |
+
# Custom type
|
| 460 |
+
parser=parser,
|
| 461 |
+
click_type=click_type,
|
| 462 |
+
# TyperArgument
|
| 463 |
+
show_default=show_default,
|
| 464 |
+
show_choices=show_choices,
|
| 465 |
+
show_envvar=show_envvar,
|
| 466 |
+
help=help,
|
| 467 |
+
hidden=hidden,
|
| 468 |
+
# Choice
|
| 469 |
+
case_sensitive=case_sensitive,
|
| 470 |
+
# Numbers
|
| 471 |
+
min=min,
|
| 472 |
+
max=max,
|
| 473 |
+
clamp=clamp,
|
| 474 |
+
# DateTime
|
| 475 |
+
formats=formats,
|
| 476 |
+
# File
|
| 477 |
+
mode=mode,
|
| 478 |
+
encoding=encoding,
|
| 479 |
+
errors=errors,
|
| 480 |
+
lazy=lazy,
|
| 481 |
+
atomic=atomic,
|
| 482 |
+
# Path
|
| 483 |
+
exists=exists,
|
| 484 |
+
file_okay=file_okay,
|
| 485 |
+
dir_okay=dir_okay,
|
| 486 |
+
writable=writable,
|
| 487 |
+
readable=readable,
|
| 488 |
+
resolve_path=resolve_path,
|
| 489 |
+
allow_dash=allow_dash,
|
| 490 |
+
path_type=path_type,
|
| 491 |
+
# Rich settings
|
| 492 |
+
rich_help_panel=rich_help_panel,
|
| 493 |
+
)
|
| 494 |
+
if is_flag is not None or flag_value is not None:
|
| 495 |
+
import warnings
|
| 496 |
+
|
| 497 |
+
warnings.warn(
|
| 498 |
+
"The 'is_flag' and 'flag_value' parameters are not supported by Typer "
|
| 499 |
+
"and will be removed entirely in a future release.",
|
| 500 |
+
DeprecationWarning,
|
| 501 |
+
stacklevel=2,
|
| 502 |
+
)
|
| 503 |
+
self.prompt = prompt
|
| 504 |
+
self.confirmation_prompt = confirmation_prompt
|
| 505 |
+
self.prompt_required = prompt_required
|
| 506 |
+
self.hide_input = hide_input
|
| 507 |
+
self.count = count
|
| 508 |
+
self.allow_from_autoenv = allow_from_autoenv
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
class ArgumentInfo(ParameterInfo):
|
| 512 |
+
def __init__(
|
| 513 |
+
self,
|
| 514 |
+
*,
|
| 515 |
+
# ParameterInfo
|
| 516 |
+
default: Any | None = None,
|
| 517 |
+
param_decls: Sequence[str] | None = None,
|
| 518 |
+
callback: Callable[..., Any] | None = None,
|
| 519 |
+
metavar: str | None = None,
|
| 520 |
+
expose_value: bool = True,
|
| 521 |
+
is_eager: bool = False,
|
| 522 |
+
envvar: str | list[str] | None = None,
|
| 523 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 524 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 525 |
+
shell_complete: Callable[
|
| 526 |
+
[click.Context, click.Parameter, str],
|
| 527 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 528 |
+
]
|
| 529 |
+
| None = None,
|
| 530 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 531 |
+
default_factory: Callable[[], Any] | None = None,
|
| 532 |
+
# Custom type
|
| 533 |
+
parser: Callable[[str], Any] | None = None,
|
| 534 |
+
click_type: click.ParamType | None = None,
|
| 535 |
+
# TyperArgument
|
| 536 |
+
show_default: bool | str = True,
|
| 537 |
+
show_choices: bool = True,
|
| 538 |
+
show_envvar: bool = True,
|
| 539 |
+
help: str | None = None,
|
| 540 |
+
hidden: bool = False,
|
| 541 |
+
# Choice
|
| 542 |
+
case_sensitive: bool = True,
|
| 543 |
+
# Numbers
|
| 544 |
+
min: int | float | None = None,
|
| 545 |
+
max: int | float | None = None,
|
| 546 |
+
clamp: bool = False,
|
| 547 |
+
# DateTime
|
| 548 |
+
formats: list[str] | None = None,
|
| 549 |
+
# File
|
| 550 |
+
mode: str | None = None,
|
| 551 |
+
encoding: str | None = None,
|
| 552 |
+
errors: str | None = "strict",
|
| 553 |
+
lazy: bool | None = None,
|
| 554 |
+
atomic: bool = False,
|
| 555 |
+
# Path
|
| 556 |
+
exists: bool = False,
|
| 557 |
+
file_okay: bool = True,
|
| 558 |
+
dir_okay: bool = True,
|
| 559 |
+
writable: bool = False,
|
| 560 |
+
readable: bool = True,
|
| 561 |
+
resolve_path: bool = False,
|
| 562 |
+
allow_dash: bool = False,
|
| 563 |
+
path_type: None | type[str] | type[bytes] = None,
|
| 564 |
+
# Rich settings
|
| 565 |
+
rich_help_panel: str | None = None,
|
| 566 |
+
):
|
| 567 |
+
super().__init__(
|
| 568 |
+
default=default,
|
| 569 |
+
param_decls=param_decls,
|
| 570 |
+
callback=callback,
|
| 571 |
+
metavar=metavar,
|
| 572 |
+
expose_value=expose_value,
|
| 573 |
+
is_eager=is_eager,
|
| 574 |
+
envvar=envvar,
|
| 575 |
+
shell_complete=shell_complete,
|
| 576 |
+
autocompletion=autocompletion,
|
| 577 |
+
default_factory=default_factory,
|
| 578 |
+
# Custom type
|
| 579 |
+
parser=parser,
|
| 580 |
+
click_type=click_type,
|
| 581 |
+
# TyperArgument
|
| 582 |
+
show_default=show_default,
|
| 583 |
+
show_choices=show_choices,
|
| 584 |
+
show_envvar=show_envvar,
|
| 585 |
+
help=help,
|
| 586 |
+
hidden=hidden,
|
| 587 |
+
# Choice
|
| 588 |
+
case_sensitive=case_sensitive,
|
| 589 |
+
# Numbers
|
| 590 |
+
min=min,
|
| 591 |
+
max=max,
|
| 592 |
+
clamp=clamp,
|
| 593 |
+
# DateTime
|
| 594 |
+
formats=formats,
|
| 595 |
+
# File
|
| 596 |
+
mode=mode,
|
| 597 |
+
encoding=encoding,
|
| 598 |
+
errors=errors,
|
| 599 |
+
lazy=lazy,
|
| 600 |
+
atomic=atomic,
|
| 601 |
+
# Path
|
| 602 |
+
exists=exists,
|
| 603 |
+
file_okay=file_okay,
|
| 604 |
+
dir_okay=dir_okay,
|
| 605 |
+
writable=writable,
|
| 606 |
+
readable=readable,
|
| 607 |
+
resolve_path=resolve_path,
|
| 608 |
+
allow_dash=allow_dash,
|
| 609 |
+
path_type=path_type,
|
| 610 |
+
# Rich settings
|
| 611 |
+
rich_help_panel=rich_help_panel,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class ParamMeta:
|
| 616 |
+
empty = inspect.Parameter.empty
|
| 617 |
+
|
| 618 |
+
def __init__(
|
| 619 |
+
self,
|
| 620 |
+
*,
|
| 621 |
+
name: str,
|
| 622 |
+
default: Any = inspect.Parameter.empty,
|
| 623 |
+
annotation: Any = inspect.Parameter.empty,
|
| 624 |
+
) -> None:
|
| 625 |
+
self.name = name
|
| 626 |
+
self.default = default
|
| 627 |
+
self.annotation = annotation
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class DeveloperExceptionConfig:
|
| 631 |
+
def __init__(
|
| 632 |
+
self,
|
| 633 |
+
*,
|
| 634 |
+
pretty_exceptions_enable: bool = True,
|
| 635 |
+
pretty_exceptions_show_locals: bool = True,
|
| 636 |
+
pretty_exceptions_short: bool = True,
|
| 637 |
+
) -> None:
|
| 638 |
+
self.pretty_exceptions_enable = pretty_exceptions_enable
|
| 639 |
+
self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
|
| 640 |
+
self.pretty_exceptions_short = pretty_exceptions_short
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
class TyperPath(click.Path):
|
| 644 |
+
# Overwrite Click's behaviour to be compatible with Typer's autocompletion system
|
| 645 |
+
def shell_complete(
|
| 646 |
+
self, ctx: click.Context, param: click.Parameter, incomplete: str
|
| 647 |
+
) -> list[click.shell_completion.CompletionItem]:
|
| 648 |
+
"""Return an empty list so that the autocompletion functionality
|
| 649 |
+
will work properly from the commandline.
|
| 650 |
+
"""
|
| 651 |
+
return []
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/params.py
ADDED
|
@@ -0,0 +1,1831 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
from typing import TYPE_CHECKING, Annotated, Any, overload
|
| 3 |
+
|
| 4 |
+
import click
|
| 5 |
+
from annotated_doc import Doc
|
| 6 |
+
|
| 7 |
+
from .models import ArgumentInfo, OptionInfo
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 10 |
+
import click.shell_completion
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# Overload for Option created with custom type 'parser'
|
| 14 |
+
@overload
|
| 15 |
+
def Option(
|
| 16 |
+
# Parameter
|
| 17 |
+
default: Any | None = ...,
|
| 18 |
+
*param_decls: str,
|
| 19 |
+
callback: Callable[..., Any] | None = None,
|
| 20 |
+
metavar: str | None = None,
|
| 21 |
+
expose_value: bool = True,
|
| 22 |
+
is_eager: bool = False,
|
| 23 |
+
envvar: str | list[str] | None = None,
|
| 24 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 25 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 26 |
+
shell_complete: Callable[
|
| 27 |
+
[click.Context, click.Parameter, str],
|
| 28 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 29 |
+
]
|
| 30 |
+
| None = None,
|
| 31 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 32 |
+
default_factory: Callable[[], Any] | None = None,
|
| 33 |
+
# Custom type
|
| 34 |
+
parser: Callable[[str], Any] | None = None,
|
| 35 |
+
# Option
|
| 36 |
+
show_default: bool | str = True,
|
| 37 |
+
prompt: bool | str = False,
|
| 38 |
+
confirmation_prompt: bool = False,
|
| 39 |
+
prompt_required: bool = True,
|
| 40 |
+
hide_input: bool = False,
|
| 41 |
+
# TODO: remove is_flag and flag_value in a future release
|
| 42 |
+
is_flag: bool | None = None,
|
| 43 |
+
flag_value: Any | None = None,
|
| 44 |
+
count: bool = False,
|
| 45 |
+
allow_from_autoenv: bool = True,
|
| 46 |
+
help: str | None = None,
|
| 47 |
+
hidden: bool = False,
|
| 48 |
+
show_choices: bool = True,
|
| 49 |
+
show_envvar: bool = True,
|
| 50 |
+
# Choice
|
| 51 |
+
case_sensitive: bool = True,
|
| 52 |
+
# Numbers
|
| 53 |
+
min: int | float | None = None,
|
| 54 |
+
max: int | float | None = None,
|
| 55 |
+
clamp: bool = False,
|
| 56 |
+
# DateTime
|
| 57 |
+
formats: list[str] | None = None,
|
| 58 |
+
# File
|
| 59 |
+
mode: str | None = None,
|
| 60 |
+
encoding: str | None = None,
|
| 61 |
+
errors: str | None = "strict",
|
| 62 |
+
lazy: bool | None = None,
|
| 63 |
+
atomic: bool = False,
|
| 64 |
+
# Path
|
| 65 |
+
exists: bool = False,
|
| 66 |
+
file_okay: bool = True,
|
| 67 |
+
dir_okay: bool = True,
|
| 68 |
+
writable: bool = False,
|
| 69 |
+
readable: bool = True,
|
| 70 |
+
resolve_path: bool = False,
|
| 71 |
+
allow_dash: bool = False,
|
| 72 |
+
path_type: None | type[str] | type[bytes] = None,
|
| 73 |
+
# Rich settings
|
| 74 |
+
rich_help_panel: str | None = None,
|
| 75 |
+
) -> Any: ...
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Overload for Option created with custom type 'click_type'
|
| 79 |
+
@overload
|
| 80 |
+
def Option(
|
| 81 |
+
# Parameter
|
| 82 |
+
default: Any | None = ...,
|
| 83 |
+
*param_decls: str,
|
| 84 |
+
callback: Callable[..., Any] | None = None,
|
| 85 |
+
metavar: str | None = None,
|
| 86 |
+
expose_value: bool = True,
|
| 87 |
+
is_eager: bool = False,
|
| 88 |
+
envvar: str | list[str] | None = None,
|
| 89 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 90 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 91 |
+
shell_complete: Callable[
|
| 92 |
+
[click.Context, click.Parameter, str],
|
| 93 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 94 |
+
]
|
| 95 |
+
| None = None,
|
| 96 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 97 |
+
default_factory: Callable[[], Any] | None = None,
|
| 98 |
+
# Custom type
|
| 99 |
+
click_type: click.ParamType | None = None,
|
| 100 |
+
# Option
|
| 101 |
+
show_default: bool | str = True,
|
| 102 |
+
prompt: bool | str = False,
|
| 103 |
+
confirmation_prompt: bool = False,
|
| 104 |
+
prompt_required: bool = True,
|
| 105 |
+
hide_input: bool = False,
|
| 106 |
+
# TODO: remove is_flag and flag_value in a future release
|
| 107 |
+
is_flag: bool | None = None,
|
| 108 |
+
flag_value: Any | None = None,
|
| 109 |
+
count: bool = False,
|
| 110 |
+
allow_from_autoenv: bool = True,
|
| 111 |
+
help: str | None = None,
|
| 112 |
+
hidden: bool = False,
|
| 113 |
+
show_choices: bool = True,
|
| 114 |
+
show_envvar: bool = True,
|
| 115 |
+
# Choice
|
| 116 |
+
case_sensitive: bool = True,
|
| 117 |
+
# Numbers
|
| 118 |
+
min: int | float | None = None,
|
| 119 |
+
max: int | float | None = None,
|
| 120 |
+
clamp: bool = False,
|
| 121 |
+
# DateTime
|
| 122 |
+
formats: list[str] | None = None,
|
| 123 |
+
# File
|
| 124 |
+
mode: str | None = None,
|
| 125 |
+
encoding: str | None = None,
|
| 126 |
+
errors: str | None = "strict",
|
| 127 |
+
lazy: bool | None = None,
|
| 128 |
+
atomic: bool = False,
|
| 129 |
+
# Path
|
| 130 |
+
exists: bool = False,
|
| 131 |
+
file_okay: bool = True,
|
| 132 |
+
dir_okay: bool = True,
|
| 133 |
+
writable: bool = False,
|
| 134 |
+
readable: bool = True,
|
| 135 |
+
resolve_path: bool = False,
|
| 136 |
+
allow_dash: bool = False,
|
| 137 |
+
path_type: None | type[str] | type[bytes] = None,
|
| 138 |
+
# Rich settings
|
| 139 |
+
rich_help_panel: str | None = None,
|
| 140 |
+
) -> Any: ...
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def Option(
|
| 144 |
+
# Parameter
|
| 145 |
+
default: Annotated[
|
| 146 |
+
Any | None,
|
| 147 |
+
Doc(
|
| 148 |
+
"""
|
| 149 |
+
Usually, [CLI options](https://typer.tiangolo.com/tutorial/options/) are optional and have a default value, passed on like this:
|
| 150 |
+
|
| 151 |
+
**Example**
|
| 152 |
+
|
| 153 |
+
```python
|
| 154 |
+
@app.command()
|
| 155 |
+
def main(network: str = typer.Option("CNN")):
|
| 156 |
+
print(f"Training neural network of type: {network}")
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
Note that this usage is deprecated, and we recommend to use `Annotated` instead:
|
| 160 |
+
```
|
| 161 |
+
@app.command()
|
| 162 |
+
def main(network: Annotated[str, typer.Option()] = "CNN"):
|
| 163 |
+
print(f"Hello {name}!")
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
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.
|
| 167 |
+
"""
|
| 168 |
+
),
|
| 169 |
+
] = ...,
|
| 170 |
+
*param_decls: Annotated[
|
| 171 |
+
str,
|
| 172 |
+
Doc(
|
| 173 |
+
"""
|
| 174 |
+
Positional argument that defines how users can call this option on the command line. This may be one or multiple aliases, all strings.
|
| 175 |
+
If not defined, Typer will automatically use the function parameter as default name.
|
| 176 |
+
See [the tutorial about CLI Option Names](https://typer.tiangolo.com/tutorial/options/name/) for more details.
|
| 177 |
+
|
| 178 |
+
**Example**
|
| 179 |
+
|
| 180 |
+
```python
|
| 181 |
+
@app.command()
|
| 182 |
+
def main(user_name: Annotated[str, typer.Option("--user", "-u", "-x")]):
|
| 183 |
+
print(f"Hello {user_name}")
|
| 184 |
+
```
|
| 185 |
+
"""
|
| 186 |
+
),
|
| 187 |
+
],
|
| 188 |
+
callback: Annotated[
|
| 189 |
+
Callable[..., Any] | None,
|
| 190 |
+
Doc(
|
| 191 |
+
"""
|
| 192 |
+
Add a callback to this CLI Option, to execute additional logic after its value was received from the terminal.
|
| 193 |
+
See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.
|
| 194 |
+
|
| 195 |
+
**Example**
|
| 196 |
+
|
| 197 |
+
```python
|
| 198 |
+
def name_callback(value: str):
|
| 199 |
+
if value != "Deadpool":
|
| 200 |
+
raise typer.BadParameter("Only Deadpool is allowed")
|
| 201 |
+
return value
|
| 202 |
+
|
| 203 |
+
@app.command()
|
| 204 |
+
def main(name: Annotated[str, typer.Option(callback=name_callback)]):
|
| 205 |
+
print(f"Hello {name}")
|
| 206 |
+
```
|
| 207 |
+
"""
|
| 208 |
+
),
|
| 209 |
+
] = None,
|
| 210 |
+
metavar: Annotated[
|
| 211 |
+
str | None,
|
| 212 |
+
Doc(
|
| 213 |
+
"""
|
| 214 |
+
Customize the name displayed in the [help text](https://typer.tiangolo.com/tutorial/options/help/) to represent this CLI option.
|
| 215 |
+
Note that this doesn't influence the way the option must be called.
|
| 216 |
+
|
| 217 |
+
**Example**
|
| 218 |
+
|
| 219 |
+
```python
|
| 220 |
+
@app.command()
|
| 221 |
+
def main(user: Annotated[str, typer.Option(metavar="User name")]):
|
| 222 |
+
print(f"Hello {user}")
|
| 223 |
+
```
|
| 224 |
+
"""
|
| 225 |
+
),
|
| 226 |
+
] = None,
|
| 227 |
+
expose_value: Annotated[
|
| 228 |
+
bool,
|
| 229 |
+
Doc(
|
| 230 |
+
"""
|
| 231 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 232 |
+
|
| 233 |
+
---
|
| 234 |
+
|
| 235 |
+
If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.
|
| 236 |
+
"""
|
| 237 |
+
),
|
| 238 |
+
] = True,
|
| 239 |
+
is_eager: Annotated[
|
| 240 |
+
bool,
|
| 241 |
+
Doc(
|
| 242 |
+
"""
|
| 243 |
+
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.
|
| 244 |
+
For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager).
|
| 245 |
+
"""
|
| 246 |
+
),
|
| 247 |
+
] = False,
|
| 248 |
+
envvar: Annotated[
|
| 249 |
+
str | list[str] | None,
|
| 250 |
+
Doc(
|
| 251 |
+
"""
|
| 252 |
+
Configure a CLI Option to read its value from an environment variable if it is not provided in the command line.
|
| 253 |
+
For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).
|
| 254 |
+
|
| 255 |
+
**Example**
|
| 256 |
+
|
| 257 |
+
```python
|
| 258 |
+
@app.command()
|
| 259 |
+
def main(user: Annotated[str, typer.Option(envvar="ME")]):
|
| 260 |
+
print(f"Hello {user}")
|
| 261 |
+
```
|
| 262 |
+
"""
|
| 263 |
+
),
|
| 264 |
+
] = None,
|
| 265 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 266 |
+
shell_complete: Annotated[
|
| 267 |
+
Callable[
|
| 268 |
+
[click.Context, click.Parameter, str],
|
| 269 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 270 |
+
]
|
| 271 |
+
| None,
|
| 272 |
+
Doc(
|
| 273 |
+
"""
|
| 274 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 275 |
+
It is however not fully functional, and will likely be removed in future versions.
|
| 276 |
+
"""
|
| 277 |
+
),
|
| 278 |
+
] = None,
|
| 279 |
+
autocompletion: Annotated[
|
| 280 |
+
Callable[..., Any] | None,
|
| 281 |
+
Doc(
|
| 282 |
+
"""
|
| 283 |
+
Provide a custom function that helps to autocomplete the values of this CLI Option.
|
| 284 |
+
See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.
|
| 285 |
+
|
| 286 |
+
**Example**
|
| 287 |
+
|
| 288 |
+
```python
|
| 289 |
+
def complete():
|
| 290 |
+
return ["Me", "Myself", "I"]
|
| 291 |
+
|
| 292 |
+
@app.command()
|
| 293 |
+
def main(name: Annotated[str, typer.Option(autocompletion=complete)]):
|
| 294 |
+
print(f"Hello {name}")
|
| 295 |
+
```
|
| 296 |
+
"""
|
| 297 |
+
),
|
| 298 |
+
] = None,
|
| 299 |
+
default_factory: Annotated[
|
| 300 |
+
Callable[[], Any] | None,
|
| 301 |
+
Doc(
|
| 302 |
+
"""
|
| 303 |
+
Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Option.
|
| 304 |
+
|
| 305 |
+
**Example**
|
| 306 |
+
|
| 307 |
+
```python
|
| 308 |
+
def get_name():
|
| 309 |
+
return random.choice(["Me", "Myself", "I"])
|
| 310 |
+
|
| 311 |
+
@app.command()
|
| 312 |
+
def main(name: Annotated[str, typer.Option(default_factory=get_name)]):
|
| 313 |
+
print(f"Hello {name}")
|
| 314 |
+
```
|
| 315 |
+
"""
|
| 316 |
+
),
|
| 317 |
+
] = None,
|
| 318 |
+
# Custom type
|
| 319 |
+
parser: Annotated[
|
| 320 |
+
Callable[[str], Any] | None,
|
| 321 |
+
Doc(
|
| 322 |
+
"""
|
| 323 |
+
Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:
|
| 324 |
+
|
| 325 |
+
**Example**
|
| 326 |
+
|
| 327 |
+
```python
|
| 328 |
+
class CustomClass:
|
| 329 |
+
def __init__(self, value: str):
|
| 330 |
+
self.value = value
|
| 331 |
+
|
| 332 |
+
def __str__(self):
|
| 333 |
+
return f"<CustomClass: value={self.value}>"
|
| 334 |
+
|
| 335 |
+
def my_parser(value: str):
|
| 336 |
+
return CustomClass(value * 2)
|
| 337 |
+
|
| 338 |
+
@app.command()
|
| 339 |
+
def main(opt: Annotated[CustomClass, typer.Option(parser=my_parser)] = "Foo"):
|
| 340 |
+
print(f"--opt is {opt}")
|
| 341 |
+
```
|
| 342 |
+
"""
|
| 343 |
+
),
|
| 344 |
+
] = None,
|
| 345 |
+
click_type: Annotated[
|
| 346 |
+
click.ParamType | None,
|
| 347 |
+
Doc(
|
| 348 |
+
"""
|
| 349 |
+
Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.
|
| 350 |
+
|
| 351 |
+
**Example**
|
| 352 |
+
|
| 353 |
+
```python
|
| 354 |
+
class MyClass:
|
| 355 |
+
def __init__(self, value: str):
|
| 356 |
+
self.value = value
|
| 357 |
+
|
| 358 |
+
def __str__(self):
|
| 359 |
+
return f"<MyClass: value={self.value}>"
|
| 360 |
+
|
| 361 |
+
class MyParser(click.ParamType):
|
| 362 |
+
name = "MyClass"
|
| 363 |
+
|
| 364 |
+
def convert(self, value, param, ctx):
|
| 365 |
+
return MyClass(value * 3)
|
| 366 |
+
|
| 367 |
+
@app.command()
|
| 368 |
+
def main(opt: Annotated[MyClass, typer.Option(click_type=MyParser())] = "Foo"):
|
| 369 |
+
print(f"--opt is {opt}")
|
| 370 |
+
```
|
| 371 |
+
"""
|
| 372 |
+
),
|
| 373 |
+
] = None,
|
| 374 |
+
# Option
|
| 375 |
+
show_default: Annotated[
|
| 376 |
+
bool | str,
|
| 377 |
+
Doc(
|
| 378 |
+
"""
|
| 379 |
+
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/).
|
| 380 |
+
|
| 381 |
+
**Example**
|
| 382 |
+
|
| 383 |
+
```python
|
| 384 |
+
@app.command()
|
| 385 |
+
def main(name: Annotated[str, typer.Option(show_default=False)] = "Rick"):
|
| 386 |
+
print(f"Hello {name}")
|
| 387 |
+
```
|
| 388 |
+
"""
|
| 389 |
+
),
|
| 390 |
+
] = True,
|
| 391 |
+
prompt: Annotated[
|
| 392 |
+
bool | str,
|
| 393 |
+
Doc(
|
| 394 |
+
"""
|
| 395 |
+
When set to `True`, a prompt will appear to ask for the value of this CLI Option if it was not provided:
|
| 396 |
+
|
| 397 |
+
**Example**
|
| 398 |
+
|
| 399 |
+
```python
|
| 400 |
+
@app.command()
|
| 401 |
+
def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]):
|
| 402 |
+
print(f"Hello {name} {lastname}")
|
| 403 |
+
```
|
| 404 |
+
"""
|
| 405 |
+
),
|
| 406 |
+
] = False,
|
| 407 |
+
confirmation_prompt: Annotated[
|
| 408 |
+
bool,
|
| 409 |
+
Doc(
|
| 410 |
+
"""
|
| 411 |
+
When set to `True`, a user will need to type a prompted value twice (may be useful for passwords etc.).
|
| 412 |
+
|
| 413 |
+
**Example**
|
| 414 |
+
|
| 415 |
+
```python
|
| 416 |
+
@app.command()
|
| 417 |
+
def main(project: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]):
|
| 418 |
+
print(f"Deleting project {project}")
|
| 419 |
+
```
|
| 420 |
+
"""
|
| 421 |
+
),
|
| 422 |
+
] = False,
|
| 423 |
+
prompt_required: Annotated[
|
| 424 |
+
bool,
|
| 425 |
+
Doc(
|
| 426 |
+
"""
|
| 427 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 428 |
+
|
| 429 |
+
---
|
| 430 |
+
|
| 431 |
+
If this is `False` then a prompt is only shown if the option's flag is given without a value.
|
| 432 |
+
"""
|
| 433 |
+
),
|
| 434 |
+
] = True,
|
| 435 |
+
hide_input: Annotated[
|
| 436 |
+
bool,
|
| 437 |
+
Doc(
|
| 438 |
+
"""
|
| 439 |
+
When you've configured a prompt, for instance for [querying a password](https://typer.tiangolo.com/tutorial/options/password/),
|
| 440 |
+
don't show anything on the screen while the user is typing the value.
|
| 441 |
+
|
| 442 |
+
**Example**
|
| 443 |
+
|
| 444 |
+
```python
|
| 445 |
+
@app.command()
|
| 446 |
+
def login(
|
| 447 |
+
name: str,
|
| 448 |
+
password: Annotated[str, typer.Option(prompt=True, hide_input=True)],
|
| 449 |
+
):
|
| 450 |
+
print(f"Hello {name}. Doing something very secure with password.")
|
| 451 |
+
```
|
| 452 |
+
"""
|
| 453 |
+
),
|
| 454 |
+
] = False,
|
| 455 |
+
# TODO: remove is_flag and flag_value in a future release
|
| 456 |
+
is_flag: Annotated[
|
| 457 |
+
bool | None,
|
| 458 |
+
Doc(
|
| 459 |
+
"""
|
| 460 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 461 |
+
It is however not fully functional, and will likely be removed in future versions.
|
| 462 |
+
"""
|
| 463 |
+
),
|
| 464 |
+
] = None,
|
| 465 |
+
flag_value: Annotated[
|
| 466 |
+
Any | None,
|
| 467 |
+
Doc(
|
| 468 |
+
"""
|
| 469 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 470 |
+
It is however not fully functional, and will likely be removed in future versions.
|
| 471 |
+
"""
|
| 472 |
+
),
|
| 473 |
+
] = None,
|
| 474 |
+
count: Annotated[
|
| 475 |
+
bool,
|
| 476 |
+
Doc(
|
| 477 |
+
"""
|
| 478 |
+
Make a CLI Option work as a [counter](https://typer.tiangolo.com/tutorial/parameter-types/number/#counter-cli-options).
|
| 479 |
+
The CLI option will have the `int` value representing the number of times the option was used on the command line.
|
| 480 |
+
|
| 481 |
+
**Example**
|
| 482 |
+
|
| 483 |
+
```python
|
| 484 |
+
@app.command()
|
| 485 |
+
def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):
|
| 486 |
+
print(f"Verbose level is {verbose}")
|
| 487 |
+
```
|
| 488 |
+
"""
|
| 489 |
+
),
|
| 490 |
+
] = False,
|
| 491 |
+
allow_from_autoenv: Annotated[
|
| 492 |
+
bool,
|
| 493 |
+
Doc(
|
| 494 |
+
"""
|
| 495 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 496 |
+
|
| 497 |
+
---
|
| 498 |
+
|
| 499 |
+
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.
|
| 500 |
+
"""
|
| 501 |
+
),
|
| 502 |
+
] = True,
|
| 503 |
+
help: Annotated[
|
| 504 |
+
str | None,
|
| 505 |
+
Doc(
|
| 506 |
+
"""
|
| 507 |
+
Help text for this CLI Option.
|
| 508 |
+
See [the tutorial about CLI Options with help](https://typer.tiangolo.com/tutorial/options/help/) for more dedails.
|
| 509 |
+
|
| 510 |
+
**Example**
|
| 511 |
+
|
| 512 |
+
```python
|
| 513 |
+
@app.command()
|
| 514 |
+
def greet(name: Annotated[str, typer.Option(help="Person to greet")] = "Deadpool"):
|
| 515 |
+
print(f"Hello {name}")
|
| 516 |
+
```
|
| 517 |
+
"""
|
| 518 |
+
),
|
| 519 |
+
] = None,
|
| 520 |
+
hidden: Annotated[
|
| 521 |
+
bool,
|
| 522 |
+
Doc(
|
| 523 |
+
"""
|
| 524 |
+
Hide this CLI Option from [help outputs](https://typer.tiangolo.com/tutorial/options/help). `False` by default.
|
| 525 |
+
|
| 526 |
+
**Example**
|
| 527 |
+
|
| 528 |
+
```python
|
| 529 |
+
@app.command()
|
| 530 |
+
def greet(name: Annotated[str, typer.Option(hidden=True)] = "Deadpool"):
|
| 531 |
+
print(f"Hello {name}")
|
| 532 |
+
```
|
| 533 |
+
"""
|
| 534 |
+
),
|
| 535 |
+
] = False,
|
| 536 |
+
show_choices: Annotated[
|
| 537 |
+
bool,
|
| 538 |
+
Doc(
|
| 539 |
+
"""
|
| 540 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 541 |
+
|
| 542 |
+
---
|
| 543 |
+
|
| 544 |
+
When set to `False`, this suppresses choices from being displayed inline when `prompt` is used.
|
| 545 |
+
"""
|
| 546 |
+
),
|
| 547 |
+
] = True,
|
| 548 |
+
show_envvar: Annotated[
|
| 549 |
+
bool,
|
| 550 |
+
Doc(
|
| 551 |
+
"""
|
| 552 |
+
When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text:
|
| 553 |
+
|
| 554 |
+
**Example**
|
| 555 |
+
|
| 556 |
+
```python
|
| 557 |
+
@app.command()
|
| 558 |
+
def main(user: Annotated[str, typer.Option(envvar="ME", show_envvar=False)]):
|
| 559 |
+
print(f"Hello {user}")
|
| 560 |
+
```
|
| 561 |
+
"""
|
| 562 |
+
),
|
| 563 |
+
] = True,
|
| 564 |
+
# Choice
|
| 565 |
+
case_sensitive: Annotated[
|
| 566 |
+
bool,
|
| 567 |
+
Doc(
|
| 568 |
+
"""
|
| 569 |
+
For a CLI Option representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum),
|
| 570 |
+
you can allow case-insensitive matching with this parameter:
|
| 571 |
+
|
| 572 |
+
**Example**
|
| 573 |
+
|
| 574 |
+
```python
|
| 575 |
+
from enum import Enum
|
| 576 |
+
|
| 577 |
+
class NeuralNetwork(str, Enum):
|
| 578 |
+
simple = "simple"
|
| 579 |
+
conv = "conv"
|
| 580 |
+
lstm = "lstm"
|
| 581 |
+
|
| 582 |
+
@app.command()
|
| 583 |
+
def main(
|
| 584 |
+
network: Annotated[NeuralNetwork, typer.Option(case_sensitive=False)]):
|
| 585 |
+
print(f"Training neural network of type: {network.value}")
|
| 586 |
+
```
|
| 587 |
+
|
| 588 |
+
With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`.
|
| 589 |
+
"""
|
| 590 |
+
),
|
| 591 |
+
] = True,
|
| 592 |
+
# Numbers
|
| 593 |
+
min: Annotated[
|
| 594 |
+
int | float | None,
|
| 595 |
+
Doc(
|
| 596 |
+
"""
|
| 597 |
+
For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
|
| 598 |
+
you can define numeric validations with `min` and `max` values:
|
| 599 |
+
|
| 600 |
+
**Example**
|
| 601 |
+
|
| 602 |
+
```python
|
| 603 |
+
@app.command()
|
| 604 |
+
def main(
|
| 605 |
+
user: Annotated[str, typer.Argument()],
|
| 606 |
+
user_id: Annotated[int, typer.Option(min=1, max=1000)],
|
| 607 |
+
):
|
| 608 |
+
print(f"ID for {user} is {user_id}")
|
| 609 |
+
```
|
| 610 |
+
|
| 611 |
+
If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
|
| 612 |
+
"""
|
| 613 |
+
),
|
| 614 |
+
] = None,
|
| 615 |
+
max: Annotated[
|
| 616 |
+
int | float | None,
|
| 617 |
+
Doc(
|
| 618 |
+
"""
|
| 619 |
+
For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
|
| 620 |
+
you can define numeric validations with `min` and `max` values:
|
| 621 |
+
|
| 622 |
+
**Example**
|
| 623 |
+
|
| 624 |
+
```python
|
| 625 |
+
@app.command()
|
| 626 |
+
def main(
|
| 627 |
+
user: Annotated[str, typer.Argument()],
|
| 628 |
+
user_id: Annotated[int, typer.Option(min=1, max=1000)],
|
| 629 |
+
):
|
| 630 |
+
print(f"ID for {user} is {user_id}")
|
| 631 |
+
```
|
| 632 |
+
|
| 633 |
+
If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
|
| 634 |
+
"""
|
| 635 |
+
),
|
| 636 |
+
] = None,
|
| 637 |
+
clamp: Annotated[
|
| 638 |
+
bool,
|
| 639 |
+
Doc(
|
| 640 |
+
"""
|
| 641 |
+
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`,
|
| 642 |
+
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`.
|
| 643 |
+
|
| 644 |
+
**Example**
|
| 645 |
+
|
| 646 |
+
```python
|
| 647 |
+
@app.command()
|
| 648 |
+
def main(
|
| 649 |
+
user: Annotated[str, typer.Argument()],
|
| 650 |
+
user_id: Annotated[int, typer.Option(min=1, max=1000, clamp=True)],
|
| 651 |
+
):
|
| 652 |
+
print(f"ID for {user} is {user_id}")
|
| 653 |
+
```
|
| 654 |
+
|
| 655 |
+
If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`.
|
| 656 |
+
"""
|
| 657 |
+
),
|
| 658 |
+
] = False,
|
| 659 |
+
# DateTime
|
| 660 |
+
formats: Annotated[
|
| 661 |
+
list[str] | None,
|
| 662 |
+
Doc(
|
| 663 |
+
"""
|
| 664 |
+
For a CLI Option representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),
|
| 665 |
+
you can customize the formats that can be parsed automatically:
|
| 666 |
+
|
| 667 |
+
**Example**
|
| 668 |
+
|
| 669 |
+
```python
|
| 670 |
+
from datetime import datetime
|
| 671 |
+
|
| 672 |
+
@app.command()
|
| 673 |
+
def main(
|
| 674 |
+
birthday: Annotated[
|
| 675 |
+
datetime,
|
| 676 |
+
typer.Option(
|
| 677 |
+
formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]
|
| 678 |
+
),
|
| 679 |
+
],
|
| 680 |
+
):
|
| 681 |
+
print(f"Birthday defined at: {birthday}")
|
| 682 |
+
```
|
| 683 |
+
"""
|
| 684 |
+
),
|
| 685 |
+
] = None,
|
| 686 |
+
# File
|
| 687 |
+
mode: Annotated[
|
| 688 |
+
str | None,
|
| 689 |
+
Doc(
|
| 690 |
+
"""
|
| 691 |
+
For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
|
| 692 |
+
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).
|
| 693 |
+
|
| 694 |
+
**Example**
|
| 695 |
+
|
| 696 |
+
```python
|
| 697 |
+
@app.command()
|
| 698 |
+
def main(config: Annotated[typer.FileText, typer.Option(mode="a")]):
|
| 699 |
+
config.write("This is a single line\\n")
|
| 700 |
+
print("Config line written")
|
| 701 |
+
```
|
| 702 |
+
"""
|
| 703 |
+
),
|
| 704 |
+
] = None,
|
| 705 |
+
encoding: Annotated[
|
| 706 |
+
str | None,
|
| 707 |
+
Doc(
|
| 708 |
+
"""
|
| 709 |
+
Customize the encoding of this CLI Option represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).
|
| 710 |
+
|
| 711 |
+
**Example**
|
| 712 |
+
|
| 713 |
+
```python
|
| 714 |
+
@app.command()
|
| 715 |
+
def main(config: Annotated[typer.FileText, typer.Option(encoding="utf-8")]):
|
| 716 |
+
config.write("All the text gets written\\n")
|
| 717 |
+
```
|
| 718 |
+
"""
|
| 719 |
+
),
|
| 720 |
+
] = None,
|
| 721 |
+
errors: Annotated[
|
| 722 |
+
str | None,
|
| 723 |
+
Doc(
|
| 724 |
+
"""
|
| 725 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 726 |
+
|
| 727 |
+
---
|
| 728 |
+
|
| 729 |
+
The error handling mode.
|
| 730 |
+
"""
|
| 731 |
+
),
|
| 732 |
+
] = "strict",
|
| 733 |
+
lazy: Annotated[
|
| 734 |
+
bool | None,
|
| 735 |
+
Doc(
|
| 736 |
+
"""
|
| 737 |
+
For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
|
| 738 |
+
by default the file will not be created until you actually start writing to it.
|
| 739 |
+
You can change this behaviour by setting this parameter.
|
| 740 |
+
By default, it's set to `True` for writing and to `False` for reading.
|
| 741 |
+
|
| 742 |
+
**Example**
|
| 743 |
+
|
| 744 |
+
```python
|
| 745 |
+
@app.command()
|
| 746 |
+
def main(config: Annotated[typer.FileText, typer.Option(mode="a", lazy=False)]):
|
| 747 |
+
config.write("This is a single line\\n")
|
| 748 |
+
print("Config line written")
|
| 749 |
+
```
|
| 750 |
+
"""
|
| 751 |
+
),
|
| 752 |
+
] = None,
|
| 753 |
+
atomic: Annotated[
|
| 754 |
+
bool,
|
| 755 |
+
Doc(
|
| 756 |
+
"""
|
| 757 |
+
For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
|
| 758 |
+
you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing
|
| 759 |
+
by setting `atomic` to `True`. This can be useful for files with potential concurrent access.
|
| 760 |
+
|
| 761 |
+
**Example**
|
| 762 |
+
|
| 763 |
+
```python
|
| 764 |
+
@app.command()
|
| 765 |
+
def main(config: Annotated[typer.FileText, typer.Option(mode="a", atomic=True)]):
|
| 766 |
+
config.write("All the text")
|
| 767 |
+
```
|
| 768 |
+
"""
|
| 769 |
+
),
|
| 770 |
+
] = False,
|
| 771 |
+
# Path
|
| 772 |
+
exists: Annotated[
|
| 773 |
+
bool,
|
| 774 |
+
Doc(
|
| 775 |
+
"""
|
| 776 |
+
When set to `True` for a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/),
|
| 777 |
+
additional validation is performed to check that the file or directory exists. If not, the value will be invalid.
|
| 778 |
+
|
| 779 |
+
**Example**
|
| 780 |
+
|
| 781 |
+
```python
|
| 782 |
+
from pathlib import Path
|
| 783 |
+
|
| 784 |
+
@app.command()
|
| 785 |
+
def main(config: Annotated[Path, typer.Option(exists=True)]):
|
| 786 |
+
text = config.read_text()
|
| 787 |
+
print(f"Config file contents: {text}")
|
| 788 |
+
```
|
| 789 |
+
"""
|
| 790 |
+
),
|
| 791 |
+
] = False,
|
| 792 |
+
file_okay: Annotated[
|
| 793 |
+
bool,
|
| 794 |
+
Doc(
|
| 795 |
+
"""
|
| 796 |
+
Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)
|
| 797 |
+
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.
|
| 798 |
+
|
| 799 |
+
**Example**
|
| 800 |
+
|
| 801 |
+
```python
|
| 802 |
+
from pathlib import Path
|
| 803 |
+
|
| 804 |
+
@app.command()
|
| 805 |
+
def main(config: Annotated[Path, typer.Option(exists=True, file_okay=False)]):
|
| 806 |
+
print(f"Directory listing: {[x.name for x in config.iterdir()]}")
|
| 807 |
+
```
|
| 808 |
+
"""
|
| 809 |
+
),
|
| 810 |
+
] = True,
|
| 811 |
+
dir_okay: Annotated[
|
| 812 |
+
bool,
|
| 813 |
+
Doc(
|
| 814 |
+
"""
|
| 815 |
+
Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)
|
| 816 |
+
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.
|
| 817 |
+
|
| 818 |
+
**Example**
|
| 819 |
+
|
| 820 |
+
```python
|
| 821 |
+
from pathlib import Path
|
| 822 |
+
|
| 823 |
+
@app.command()
|
| 824 |
+
def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]):
|
| 825 |
+
text = config.read_text()
|
| 826 |
+
print(f"Config file contents: {text}")
|
| 827 |
+
```
|
| 828 |
+
"""
|
| 829 |
+
),
|
| 830 |
+
] = True,
|
| 831 |
+
writable: Annotated[
|
| 832 |
+
bool,
|
| 833 |
+
Doc(
|
| 834 |
+
"""
|
| 835 |
+
Whether or not to perform a writable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/).
|
| 836 |
+
|
| 837 |
+
**Example**
|
| 838 |
+
|
| 839 |
+
```python
|
| 840 |
+
from pathlib import Path
|
| 841 |
+
|
| 842 |
+
@app.command()
|
| 843 |
+
def main(config: Annotated[Path, typer.Option(writable=True)]):
|
| 844 |
+
config.write_text("All the text")
|
| 845 |
+
```
|
| 846 |
+
"""
|
| 847 |
+
),
|
| 848 |
+
] = False,
|
| 849 |
+
readable: Annotated[
|
| 850 |
+
bool,
|
| 851 |
+
Doc(
|
| 852 |
+
"""
|
| 853 |
+
Whether or not to perform a readable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/).
|
| 854 |
+
|
| 855 |
+
**Example**
|
| 856 |
+
|
| 857 |
+
```python
|
| 858 |
+
from pathlib import Path
|
| 859 |
+
|
| 860 |
+
@app.command()
|
| 861 |
+
def main(config: Annotated[Path, typer.Option(readable=True)]):
|
| 862 |
+
config.read_text("All the text")
|
| 863 |
+
```
|
| 864 |
+
"""
|
| 865 |
+
),
|
| 866 |
+
] = True,
|
| 867 |
+
resolve_path: Annotated[
|
| 868 |
+
bool,
|
| 869 |
+
Doc(
|
| 870 |
+
"""
|
| 871 |
+
Whether or not to fully resolve the path of this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/),
|
| 872 |
+
meaning that the path becomes absolute and symlinks are resolved.
|
| 873 |
+
|
| 874 |
+
**Example**
|
| 875 |
+
|
| 876 |
+
```python
|
| 877 |
+
from pathlib import Path
|
| 878 |
+
|
| 879 |
+
@app.command()
|
| 880 |
+
def main(config: Annotated[Path, typer.Option(resolve_path=True)]):
|
| 881 |
+
config.read_text("All the text")
|
| 882 |
+
```
|
| 883 |
+
"""
|
| 884 |
+
),
|
| 885 |
+
] = False,
|
| 886 |
+
allow_dash: Annotated[
|
| 887 |
+
bool,
|
| 888 |
+
Doc(
|
| 889 |
+
"""
|
| 890 |
+
When set to `True`, a single dash for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)
|
| 891 |
+
would be a valid value, indicating standard streams. This is a more advanced use-case.
|
| 892 |
+
"""
|
| 893 |
+
),
|
| 894 |
+
] = False,
|
| 895 |
+
path_type: Annotated[
|
| 896 |
+
None | type[str] | type[bytes],
|
| 897 |
+
Doc(
|
| 898 |
+
"""
|
| 899 |
+
A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
|
| 900 |
+
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.
|
| 901 |
+
This is a more advanced use-case.
|
| 902 |
+
"""
|
| 903 |
+
),
|
| 904 |
+
] = None,
|
| 905 |
+
# Rich settings
|
| 906 |
+
rich_help_panel: Annotated[
|
| 907 |
+
str | None,
|
| 908 |
+
Doc(
|
| 909 |
+
"""
|
| 910 |
+
Set the panel name where you want this CLI Option to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).
|
| 911 |
+
|
| 912 |
+
**Example**
|
| 913 |
+
|
| 914 |
+
```python
|
| 915 |
+
@app.command()
|
| 916 |
+
def main(
|
| 917 |
+
name: Annotated[str, typer.Argument(help="Who to greet")],
|
| 918 |
+
age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")],
|
| 919 |
+
):
|
| 920 |
+
print(f"Hello {name} of age {age}")
|
| 921 |
+
```
|
| 922 |
+
"""
|
| 923 |
+
),
|
| 924 |
+
] = None,
|
| 925 |
+
) -> Any:
|
| 926 |
+
"""
|
| 927 |
+
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`.
|
| 928 |
+
|
| 929 |
+
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`
|
| 930 |
+
and omitting a default value.
|
| 931 |
+
|
| 932 |
+
## Example
|
| 933 |
+
|
| 934 |
+
```python
|
| 935 |
+
@app.command()
|
| 936 |
+
def register(
|
| 937 |
+
user: Annotated[str, typer.Argument()],
|
| 938 |
+
age: Annotated[int, typer.Option(min=18)],
|
| 939 |
+
):
|
| 940 |
+
print(f"User is {user}")
|
| 941 |
+
print(f"--age is {age}")
|
| 942 |
+
```
|
| 943 |
+
|
| 944 |
+
Note how in this example, `--age` is a required CLI Option.
|
| 945 |
+
"""
|
| 946 |
+
return OptionInfo(
|
| 947 |
+
# Parameter
|
| 948 |
+
default=default,
|
| 949 |
+
param_decls=param_decls,
|
| 950 |
+
callback=callback,
|
| 951 |
+
metavar=metavar,
|
| 952 |
+
expose_value=expose_value,
|
| 953 |
+
is_eager=is_eager,
|
| 954 |
+
envvar=envvar,
|
| 955 |
+
shell_complete=shell_complete,
|
| 956 |
+
autocompletion=autocompletion,
|
| 957 |
+
default_factory=default_factory,
|
| 958 |
+
# Custom type
|
| 959 |
+
parser=parser,
|
| 960 |
+
click_type=click_type,
|
| 961 |
+
# Option
|
| 962 |
+
show_default=show_default,
|
| 963 |
+
prompt=prompt,
|
| 964 |
+
confirmation_prompt=confirmation_prompt,
|
| 965 |
+
prompt_required=prompt_required,
|
| 966 |
+
hide_input=hide_input,
|
| 967 |
+
is_flag=is_flag,
|
| 968 |
+
flag_value=flag_value,
|
| 969 |
+
count=count,
|
| 970 |
+
allow_from_autoenv=allow_from_autoenv,
|
| 971 |
+
help=help,
|
| 972 |
+
hidden=hidden,
|
| 973 |
+
show_choices=show_choices,
|
| 974 |
+
show_envvar=show_envvar,
|
| 975 |
+
# Choice
|
| 976 |
+
case_sensitive=case_sensitive,
|
| 977 |
+
# Numbers
|
| 978 |
+
min=min,
|
| 979 |
+
max=max,
|
| 980 |
+
clamp=clamp,
|
| 981 |
+
# DateTime
|
| 982 |
+
formats=formats,
|
| 983 |
+
# File
|
| 984 |
+
mode=mode,
|
| 985 |
+
encoding=encoding,
|
| 986 |
+
errors=errors,
|
| 987 |
+
lazy=lazy,
|
| 988 |
+
atomic=atomic,
|
| 989 |
+
# Path
|
| 990 |
+
exists=exists,
|
| 991 |
+
file_okay=file_okay,
|
| 992 |
+
dir_okay=dir_okay,
|
| 993 |
+
writable=writable,
|
| 994 |
+
readable=readable,
|
| 995 |
+
resolve_path=resolve_path,
|
| 996 |
+
allow_dash=allow_dash,
|
| 997 |
+
path_type=path_type,
|
| 998 |
+
# Rich settings
|
| 999 |
+
rich_help_panel=rich_help_panel,
|
| 1000 |
+
)
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
# Overload for Argument created with custom type 'parser'
|
| 1004 |
+
@overload
|
| 1005 |
+
def Argument(
|
| 1006 |
+
# Parameter
|
| 1007 |
+
default: Any | None = ...,
|
| 1008 |
+
*,
|
| 1009 |
+
callback: Callable[..., Any] | None = None,
|
| 1010 |
+
metavar: str | None = None,
|
| 1011 |
+
expose_value: bool = True,
|
| 1012 |
+
is_eager: bool = False,
|
| 1013 |
+
envvar: str | list[str] | None = None,
|
| 1014 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 1015 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 1016 |
+
shell_complete: Callable[
|
| 1017 |
+
[click.Context, click.Parameter, str],
|
| 1018 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 1019 |
+
]
|
| 1020 |
+
| None = None,
|
| 1021 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 1022 |
+
default_factory: Callable[[], Any] | None = None,
|
| 1023 |
+
# Custom type
|
| 1024 |
+
parser: Callable[[str], Any] | None = None,
|
| 1025 |
+
# TyperArgument
|
| 1026 |
+
show_default: bool | str = True,
|
| 1027 |
+
show_choices: bool = True,
|
| 1028 |
+
show_envvar: bool = True,
|
| 1029 |
+
help: str | None = None,
|
| 1030 |
+
hidden: bool = False,
|
| 1031 |
+
# Choice
|
| 1032 |
+
case_sensitive: bool = True,
|
| 1033 |
+
# Numbers
|
| 1034 |
+
min: int | float | None = None,
|
| 1035 |
+
max: int | float | None = None,
|
| 1036 |
+
clamp: bool = False,
|
| 1037 |
+
# DateTime
|
| 1038 |
+
formats: list[str] | None = None,
|
| 1039 |
+
# File
|
| 1040 |
+
mode: str | None = None,
|
| 1041 |
+
encoding: str | None = None,
|
| 1042 |
+
errors: str | None = "strict",
|
| 1043 |
+
lazy: bool | None = None,
|
| 1044 |
+
atomic: bool = False,
|
| 1045 |
+
# Path
|
| 1046 |
+
exists: bool = False,
|
| 1047 |
+
file_okay: bool = True,
|
| 1048 |
+
dir_okay: bool = True,
|
| 1049 |
+
writable: bool = False,
|
| 1050 |
+
readable: bool = True,
|
| 1051 |
+
resolve_path: bool = False,
|
| 1052 |
+
allow_dash: bool = False,
|
| 1053 |
+
path_type: None | type[str] | type[bytes] = None,
|
| 1054 |
+
# Rich settings
|
| 1055 |
+
rich_help_panel: str | None = None,
|
| 1056 |
+
) -> Any: ...
|
| 1057 |
+
|
| 1058 |
+
|
| 1059 |
+
# Overload for Argument created with custom type 'click_type'
|
| 1060 |
+
@overload
|
| 1061 |
+
def Argument(
|
| 1062 |
+
# Parameter
|
| 1063 |
+
default: Any | None = ...,
|
| 1064 |
+
*,
|
| 1065 |
+
callback: Callable[..., Any] | None = None,
|
| 1066 |
+
metavar: str | None = None,
|
| 1067 |
+
expose_value: bool = True,
|
| 1068 |
+
is_eager: bool = False,
|
| 1069 |
+
envvar: str | list[str] | None = None,
|
| 1070 |
+
# Note that shell_complete is not fully supported and will be removed in future versions
|
| 1071 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 1072 |
+
shell_complete: Callable[
|
| 1073 |
+
[click.Context, click.Parameter, str],
|
| 1074 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 1075 |
+
]
|
| 1076 |
+
| None = None,
|
| 1077 |
+
autocompletion: Callable[..., Any] | None = None,
|
| 1078 |
+
default_factory: Callable[[], Any] | None = None,
|
| 1079 |
+
# Custom type
|
| 1080 |
+
click_type: click.ParamType | None = None,
|
| 1081 |
+
# TyperArgument
|
| 1082 |
+
show_default: bool | str = True,
|
| 1083 |
+
show_choices: bool = True,
|
| 1084 |
+
show_envvar: bool = True,
|
| 1085 |
+
help: str | None = None,
|
| 1086 |
+
hidden: bool = False,
|
| 1087 |
+
# Choice
|
| 1088 |
+
case_sensitive: bool = True,
|
| 1089 |
+
# Numbers
|
| 1090 |
+
min: int | float | None = None,
|
| 1091 |
+
max: int | float | None = None,
|
| 1092 |
+
clamp: bool = False,
|
| 1093 |
+
# DateTime
|
| 1094 |
+
formats: list[str] | None = None,
|
| 1095 |
+
# File
|
| 1096 |
+
mode: str | None = None,
|
| 1097 |
+
encoding: str | None = None,
|
| 1098 |
+
errors: str | None = "strict",
|
| 1099 |
+
lazy: bool | None = None,
|
| 1100 |
+
atomic: bool = False,
|
| 1101 |
+
# Path
|
| 1102 |
+
exists: bool = False,
|
| 1103 |
+
file_okay: bool = True,
|
| 1104 |
+
dir_okay: bool = True,
|
| 1105 |
+
writable: bool = False,
|
| 1106 |
+
readable: bool = True,
|
| 1107 |
+
resolve_path: bool = False,
|
| 1108 |
+
allow_dash: bool = False,
|
| 1109 |
+
path_type: None | type[str] | type[bytes] = None,
|
| 1110 |
+
# Rich settings
|
| 1111 |
+
rich_help_panel: str | None = None,
|
| 1112 |
+
) -> Any: ...
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
def Argument(
|
| 1116 |
+
# Parameter
|
| 1117 |
+
default: Annotated[
|
| 1118 |
+
Any | None,
|
| 1119 |
+
Doc(
|
| 1120 |
+
"""
|
| 1121 |
+
By default, CLI arguments are required. However, by giving them a default value they become [optional](https://typer.tiangolo.com/tutorial/arguments/optional):
|
| 1122 |
+
|
| 1123 |
+
**Example**
|
| 1124 |
+
|
| 1125 |
+
```python
|
| 1126 |
+
@app.command()
|
| 1127 |
+
def main(name: str = typer.Argument("World")):
|
| 1128 |
+
print(f"Hello {name}!")
|
| 1129 |
+
```
|
| 1130 |
+
|
| 1131 |
+
Note that this usage is deprecated, and we recommend to use `Annotated` instead:
|
| 1132 |
+
```python
|
| 1133 |
+
@app.command()
|
| 1134 |
+
def main(name: Annotated[str, typer.Argument()] = "World"):
|
| 1135 |
+
print(f"Hello {name}!")
|
| 1136 |
+
```
|
| 1137 |
+
"""
|
| 1138 |
+
),
|
| 1139 |
+
] = ...,
|
| 1140 |
+
*,
|
| 1141 |
+
callback: Annotated[
|
| 1142 |
+
Callable[..., Any] | None,
|
| 1143 |
+
Doc(
|
| 1144 |
+
"""
|
| 1145 |
+
Add a callback to this CLI Argument, to execute additional logic with the value received from the terminal.
|
| 1146 |
+
See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.
|
| 1147 |
+
|
| 1148 |
+
**Example**
|
| 1149 |
+
|
| 1150 |
+
```python
|
| 1151 |
+
def name_callback(value: str):
|
| 1152 |
+
if value != "Deadpool":
|
| 1153 |
+
raise typer.BadParameter("Only Deadpool is allowed")
|
| 1154 |
+
return value
|
| 1155 |
+
|
| 1156 |
+
@app.command()
|
| 1157 |
+
def main(name: Annotated[str, typer.Argument(callback=name_callback)]):
|
| 1158 |
+
print(f"Hello {name}")
|
| 1159 |
+
```
|
| 1160 |
+
"""
|
| 1161 |
+
),
|
| 1162 |
+
] = None,
|
| 1163 |
+
metavar: Annotated[
|
| 1164 |
+
str | None,
|
| 1165 |
+
Doc(
|
| 1166 |
+
"""
|
| 1167 |
+
Customize the name displayed in the help text to represent this CLI Argument.
|
| 1168 |
+
By default, it will be the same name you declared, in uppercase.
|
| 1169 |
+
See [the tutorial about CLI Arguments with Help](https://typer.tiangolo.com/tutorial/arguments/help/#custom-help-name-metavar) for more details.
|
| 1170 |
+
|
| 1171 |
+
**Example**
|
| 1172 |
+
|
| 1173 |
+
```python
|
| 1174 |
+
@app.command()
|
| 1175 |
+
def main(name: Annotated[str, typer.Argument(metavar="✨username✨")]):
|
| 1176 |
+
print(f"Hello {name}")
|
| 1177 |
+
```
|
| 1178 |
+
"""
|
| 1179 |
+
),
|
| 1180 |
+
] = None,
|
| 1181 |
+
expose_value: Annotated[
|
| 1182 |
+
bool,
|
| 1183 |
+
Doc(
|
| 1184 |
+
"""
|
| 1185 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 1186 |
+
|
| 1187 |
+
---
|
| 1188 |
+
|
| 1189 |
+
If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.
|
| 1190 |
+
"""
|
| 1191 |
+
),
|
| 1192 |
+
] = True,
|
| 1193 |
+
is_eager: Annotated[
|
| 1194 |
+
bool,
|
| 1195 |
+
Doc(
|
| 1196 |
+
"""
|
| 1197 |
+
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.
|
| 1198 |
+
For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager).
|
| 1199 |
+
"""
|
| 1200 |
+
),
|
| 1201 |
+
] = False,
|
| 1202 |
+
envvar: Annotated[
|
| 1203 |
+
str | list[str] | None,
|
| 1204 |
+
Doc(
|
| 1205 |
+
"""
|
| 1206 |
+
Configure an argument to read a value from an environment variable if it is not provided in the command line as a CLI argument.
|
| 1207 |
+
For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).
|
| 1208 |
+
|
| 1209 |
+
**Example**
|
| 1210 |
+
|
| 1211 |
+
```python
|
| 1212 |
+
@app.command()
|
| 1213 |
+
def main(name: Annotated[str, typer.Argument(envvar="ME")]):
|
| 1214 |
+
print(f"Hello Mr. {name}")
|
| 1215 |
+
```
|
| 1216 |
+
"""
|
| 1217 |
+
),
|
| 1218 |
+
] = None,
|
| 1219 |
+
# TODO: Remove shell_complete in a future version (after 0.16.0)
|
| 1220 |
+
shell_complete: Annotated[
|
| 1221 |
+
Callable[
|
| 1222 |
+
[click.Context, click.Parameter, str],
|
| 1223 |
+
list["click.shell_completion.CompletionItem"] | list[str],
|
| 1224 |
+
]
|
| 1225 |
+
| None,
|
| 1226 |
+
Doc(
|
| 1227 |
+
"""
|
| 1228 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 1229 |
+
It is however not fully functional, and will likely be removed in future versions.
|
| 1230 |
+
"""
|
| 1231 |
+
),
|
| 1232 |
+
] = None,
|
| 1233 |
+
autocompletion: Annotated[
|
| 1234 |
+
Callable[..., Any] | None,
|
| 1235 |
+
Doc(
|
| 1236 |
+
"""
|
| 1237 |
+
Provide a custom function that helps to autocomplete the values of this CLI Argument.
|
| 1238 |
+
See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.
|
| 1239 |
+
|
| 1240 |
+
**Example**
|
| 1241 |
+
|
| 1242 |
+
```python
|
| 1243 |
+
def complete():
|
| 1244 |
+
return ["Me", "Myself", "I"]
|
| 1245 |
+
|
| 1246 |
+
@app.command()
|
| 1247 |
+
def main(name: Annotated[str, typer.Argument(autocompletion=complete)]):
|
| 1248 |
+
print(f"Hello {name}")
|
| 1249 |
+
```
|
| 1250 |
+
"""
|
| 1251 |
+
),
|
| 1252 |
+
] = None,
|
| 1253 |
+
default_factory: Annotated[
|
| 1254 |
+
Callable[[], Any] | None,
|
| 1255 |
+
Doc(
|
| 1256 |
+
"""
|
| 1257 |
+
Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Argument.
|
| 1258 |
+
|
| 1259 |
+
**Example**
|
| 1260 |
+
|
| 1261 |
+
```python
|
| 1262 |
+
def get_name():
|
| 1263 |
+
return random.choice(["Me", "Myself", "I"])
|
| 1264 |
+
|
| 1265 |
+
@app.command()
|
| 1266 |
+
def main(name: Annotated[str, typer.Argument(default_factory=get_name)]):
|
| 1267 |
+
print(f"Hello {name}")
|
| 1268 |
+
```
|
| 1269 |
+
"""
|
| 1270 |
+
),
|
| 1271 |
+
] = None,
|
| 1272 |
+
# Custom type
|
| 1273 |
+
parser: Annotated[
|
| 1274 |
+
Callable[[str], Any] | None,
|
| 1275 |
+
Doc(
|
| 1276 |
+
"""
|
| 1277 |
+
Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:
|
| 1278 |
+
|
| 1279 |
+
**Example**
|
| 1280 |
+
|
| 1281 |
+
```python
|
| 1282 |
+
class CustomClass:
|
| 1283 |
+
def __init__(self, value: str):
|
| 1284 |
+
self.value = value
|
| 1285 |
+
|
| 1286 |
+
def __str__(self):
|
| 1287 |
+
return f"<CustomClass: value={self.value}>"
|
| 1288 |
+
|
| 1289 |
+
def my_parser(value: str):
|
| 1290 |
+
return CustomClass(value * 2)
|
| 1291 |
+
|
| 1292 |
+
@app.command()
|
| 1293 |
+
def main(arg: Annotated[CustomClass, typer.Argument(parser=my_parser):
|
| 1294 |
+
print(f"arg is {arg}")
|
| 1295 |
+
```
|
| 1296 |
+
"""
|
| 1297 |
+
),
|
| 1298 |
+
] = None,
|
| 1299 |
+
click_type: Annotated[
|
| 1300 |
+
click.ParamType | None,
|
| 1301 |
+
Doc(
|
| 1302 |
+
"""
|
| 1303 |
+
Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.
|
| 1304 |
+
|
| 1305 |
+
**Example**
|
| 1306 |
+
|
| 1307 |
+
```python
|
| 1308 |
+
class MyClass:
|
| 1309 |
+
def __init__(self, value: str):
|
| 1310 |
+
self.value = value
|
| 1311 |
+
|
| 1312 |
+
def __str__(self):
|
| 1313 |
+
return f"<MyClass: value={self.value}>"
|
| 1314 |
+
|
| 1315 |
+
class MyParser(click.ParamType):
|
| 1316 |
+
name = "MyClass"
|
| 1317 |
+
|
| 1318 |
+
def convert(self, value, param, ctx):
|
| 1319 |
+
return MyClass(value * 3)
|
| 1320 |
+
|
| 1321 |
+
@app.command()
|
| 1322 |
+
def main(arg: Annotated[MyClass, typer.Argument(click_type=MyParser())]):
|
| 1323 |
+
print(f"arg is {arg}")
|
| 1324 |
+
```
|
| 1325 |
+
"""
|
| 1326 |
+
),
|
| 1327 |
+
] = None,
|
| 1328 |
+
# TyperArgument
|
| 1329 |
+
show_default: Annotated[
|
| 1330 |
+
bool | str,
|
| 1331 |
+
Doc(
|
| 1332 |
+
"""
|
| 1333 |
+
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/).
|
| 1334 |
+
|
| 1335 |
+
**Example**
|
| 1336 |
+
|
| 1337 |
+
```python
|
| 1338 |
+
@app.command()
|
| 1339 |
+
def main(name: Annotated[str, typer.Argument(show_default=False)] = "Rick"):
|
| 1340 |
+
print(f"Hello {name}")
|
| 1341 |
+
```
|
| 1342 |
+
"""
|
| 1343 |
+
),
|
| 1344 |
+
] = True,
|
| 1345 |
+
show_choices: Annotated[
|
| 1346 |
+
bool,
|
| 1347 |
+
Doc(
|
| 1348 |
+
"""
|
| 1349 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 1350 |
+
|
| 1351 |
+
---
|
| 1352 |
+
|
| 1353 |
+
When set to `False`, this suppresses choices from being displayed inline when `prompt` is used.
|
| 1354 |
+
"""
|
| 1355 |
+
),
|
| 1356 |
+
] = True,
|
| 1357 |
+
show_envvar: Annotated[
|
| 1358 |
+
bool,
|
| 1359 |
+
Doc(
|
| 1360 |
+
"""
|
| 1361 |
+
When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text:
|
| 1362 |
+
|
| 1363 |
+
**Example**
|
| 1364 |
+
|
| 1365 |
+
```python
|
| 1366 |
+
@app.command()
|
| 1367 |
+
def main(name: Annotated[str, typer.Argument(envvar="ME", show_envvar=False)]):
|
| 1368 |
+
print(f"Hello Mr. {name}")
|
| 1369 |
+
```
|
| 1370 |
+
"""
|
| 1371 |
+
),
|
| 1372 |
+
] = True,
|
| 1373 |
+
help: Annotated[
|
| 1374 |
+
str | None,
|
| 1375 |
+
Doc(
|
| 1376 |
+
"""
|
| 1377 |
+
Help text for this CLI Argument.
|
| 1378 |
+
See [the tutorial about CLI Arguments with help](https://typer.tiangolo.com/tutorial/arguments/help/) for more dedails.
|
| 1379 |
+
|
| 1380 |
+
**Example**
|
| 1381 |
+
|
| 1382 |
+
```python
|
| 1383 |
+
@app.command()
|
| 1384 |
+
def greet(name: Annotated[str, typer.Argument(help="Person to greet")]):
|
| 1385 |
+
print(f"Hello {name}")
|
| 1386 |
+
```
|
| 1387 |
+
"""
|
| 1388 |
+
),
|
| 1389 |
+
] = None,
|
| 1390 |
+
hidden: Annotated[
|
| 1391 |
+
bool,
|
| 1392 |
+
Doc(
|
| 1393 |
+
"""
|
| 1394 |
+
Hide this CLI Argument from [help outputs](https://typer.tiangolo.com/tutorial/arguments/help). `False` by default.
|
| 1395 |
+
|
| 1396 |
+
**Example**
|
| 1397 |
+
|
| 1398 |
+
```python
|
| 1399 |
+
@app.command()
|
| 1400 |
+
def main(name: Annotated[str, typer.Argument(hidden=True)] = "World"):
|
| 1401 |
+
print(f"Hello {name}")
|
| 1402 |
+
```
|
| 1403 |
+
"""
|
| 1404 |
+
),
|
| 1405 |
+
] = False,
|
| 1406 |
+
# Choice
|
| 1407 |
+
case_sensitive: Annotated[
|
| 1408 |
+
bool,
|
| 1409 |
+
Doc(
|
| 1410 |
+
"""
|
| 1411 |
+
For a CLI Argument representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum),
|
| 1412 |
+
you can allow case-insensitive matching with this parameter:
|
| 1413 |
+
|
| 1414 |
+
**Example**
|
| 1415 |
+
|
| 1416 |
+
```python
|
| 1417 |
+
from enum import Enum
|
| 1418 |
+
|
| 1419 |
+
class NeuralNetwork(str, Enum):
|
| 1420 |
+
simple = "simple"
|
| 1421 |
+
conv = "conv"
|
| 1422 |
+
lstm = "lstm"
|
| 1423 |
+
|
| 1424 |
+
@app.command()
|
| 1425 |
+
def main(
|
| 1426 |
+
network: Annotated[NeuralNetwork, typer.Argument(case_sensitive=False)]):
|
| 1427 |
+
print(f"Training neural network of type: {network.value}")
|
| 1428 |
+
```
|
| 1429 |
+
|
| 1430 |
+
With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`.
|
| 1431 |
+
"""
|
| 1432 |
+
),
|
| 1433 |
+
] = True,
|
| 1434 |
+
# Numbers
|
| 1435 |
+
min: Annotated[
|
| 1436 |
+
int | float | None,
|
| 1437 |
+
Doc(
|
| 1438 |
+
"""
|
| 1439 |
+
For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
|
| 1440 |
+
you can define numeric validations with `min` and `max` values:
|
| 1441 |
+
|
| 1442 |
+
**Example**
|
| 1443 |
+
|
| 1444 |
+
```python
|
| 1445 |
+
@app.command()
|
| 1446 |
+
def main(
|
| 1447 |
+
user: Annotated[str, typer.Argument()],
|
| 1448 |
+
user_id: Annotated[int, typer.Argument(min=1, max=1000)],
|
| 1449 |
+
):
|
| 1450 |
+
print(f"ID for {user} is {user_id}")
|
| 1451 |
+
```
|
| 1452 |
+
|
| 1453 |
+
If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
|
| 1454 |
+
"""
|
| 1455 |
+
),
|
| 1456 |
+
] = None,
|
| 1457 |
+
max: Annotated[
|
| 1458 |
+
int | float | None,
|
| 1459 |
+
Doc(
|
| 1460 |
+
"""
|
| 1461 |
+
For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
|
| 1462 |
+
you can define numeric validations with `min` and `max` values:
|
| 1463 |
+
|
| 1464 |
+
**Example**
|
| 1465 |
+
|
| 1466 |
+
```python
|
| 1467 |
+
@app.command()
|
| 1468 |
+
def main(
|
| 1469 |
+
user: Annotated[str, typer.Argument()],
|
| 1470 |
+
user_id: Annotated[int, typer.Argument(min=1, max=1000)],
|
| 1471 |
+
):
|
| 1472 |
+
print(f"ID for {user} is {user_id}")
|
| 1473 |
+
```
|
| 1474 |
+
|
| 1475 |
+
If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
|
| 1476 |
+
"""
|
| 1477 |
+
),
|
| 1478 |
+
] = None,
|
| 1479 |
+
clamp: Annotated[
|
| 1480 |
+
bool,
|
| 1481 |
+
Doc(
|
| 1482 |
+
"""
|
| 1483 |
+
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`,
|
| 1484 |
+
you can opt to use the closest minimum or maximum value instead of raising an error. This is done by setting `clamp` to `True`.
|
| 1485 |
+
|
| 1486 |
+
**Example**
|
| 1487 |
+
|
| 1488 |
+
```python
|
| 1489 |
+
@app.command()
|
| 1490 |
+
def main(
|
| 1491 |
+
user: Annotated[str, typer.Argument()],
|
| 1492 |
+
user_id: Annotated[int, typer.Argument(min=1, max=1000, clamp=True)],
|
| 1493 |
+
):
|
| 1494 |
+
print(f"ID for {user} is {user_id}")
|
| 1495 |
+
```
|
| 1496 |
+
|
| 1497 |
+
If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`.
|
| 1498 |
+
"""
|
| 1499 |
+
),
|
| 1500 |
+
] = False,
|
| 1501 |
+
# DateTime
|
| 1502 |
+
formats: Annotated[
|
| 1503 |
+
list[str] | None,
|
| 1504 |
+
Doc(
|
| 1505 |
+
"""
|
| 1506 |
+
For a CLI Argument representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),
|
| 1507 |
+
you can customize the formats that can be parsed automatically:
|
| 1508 |
+
|
| 1509 |
+
**Example**
|
| 1510 |
+
|
| 1511 |
+
```python
|
| 1512 |
+
from datetime import datetime
|
| 1513 |
+
|
| 1514 |
+
@app.command()
|
| 1515 |
+
def main(
|
| 1516 |
+
birthday: Annotated[
|
| 1517 |
+
datetime,
|
| 1518 |
+
typer.Argument(
|
| 1519 |
+
formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]
|
| 1520 |
+
),
|
| 1521 |
+
],
|
| 1522 |
+
):
|
| 1523 |
+
print(f"Birthday defined at: {birthday}")
|
| 1524 |
+
```
|
| 1525 |
+
"""
|
| 1526 |
+
),
|
| 1527 |
+
] = None,
|
| 1528 |
+
# File
|
| 1529 |
+
mode: Annotated[
|
| 1530 |
+
str | None,
|
| 1531 |
+
Doc(
|
| 1532 |
+
"""
|
| 1533 |
+
For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
|
| 1534 |
+
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).
|
| 1535 |
+
|
| 1536 |
+
**Example**
|
| 1537 |
+
|
| 1538 |
+
```python
|
| 1539 |
+
@app.command()
|
| 1540 |
+
def main(config: Annotated[typer.FileText, typer.Argument(mode="a")]):
|
| 1541 |
+
config.write("This is a single line\\n")
|
| 1542 |
+
print("Config line written")
|
| 1543 |
+
```
|
| 1544 |
+
"""
|
| 1545 |
+
),
|
| 1546 |
+
] = None,
|
| 1547 |
+
encoding: Annotated[
|
| 1548 |
+
str | None,
|
| 1549 |
+
Doc(
|
| 1550 |
+
"""
|
| 1551 |
+
Customize the encoding of this CLI Argument represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).
|
| 1552 |
+
|
| 1553 |
+
**Example**
|
| 1554 |
+
|
| 1555 |
+
```python
|
| 1556 |
+
@app.command()
|
| 1557 |
+
def main(config: Annotated[typer.FileText, typer.Argument(encoding="utf-8")]):
|
| 1558 |
+
config.write("All the text gets written\\n")
|
| 1559 |
+
```
|
| 1560 |
+
"""
|
| 1561 |
+
),
|
| 1562 |
+
] = None,
|
| 1563 |
+
errors: Annotated[
|
| 1564 |
+
str | None,
|
| 1565 |
+
Doc(
|
| 1566 |
+
"""
|
| 1567 |
+
**Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
|
| 1568 |
+
|
| 1569 |
+
---
|
| 1570 |
+
|
| 1571 |
+
The error handling mode.
|
| 1572 |
+
"""
|
| 1573 |
+
),
|
| 1574 |
+
] = "strict",
|
| 1575 |
+
lazy: Annotated[
|
| 1576 |
+
bool | None,
|
| 1577 |
+
Doc(
|
| 1578 |
+
"""
|
| 1579 |
+
For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
|
| 1580 |
+
by default the file will not be created until you actually start writing to it.
|
| 1581 |
+
You can change this behaviour by setting this parameter.
|
| 1582 |
+
By default, it's set to `True` for writing and to `False` for reading.
|
| 1583 |
+
|
| 1584 |
+
**Example**
|
| 1585 |
+
|
| 1586 |
+
```python
|
| 1587 |
+
@app.command()
|
| 1588 |
+
def main(config: Annotated[typer.FileText, typer.Argument(mode="a", lazy=False)]):
|
| 1589 |
+
config.write("This is a single line\\n")
|
| 1590 |
+
print("Config line written")
|
| 1591 |
+
```
|
| 1592 |
+
"""
|
| 1593 |
+
),
|
| 1594 |
+
] = None,
|
| 1595 |
+
atomic: Annotated[
|
| 1596 |
+
bool,
|
| 1597 |
+
Doc(
|
| 1598 |
+
"""
|
| 1599 |
+
For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
|
| 1600 |
+
you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing
|
| 1601 |
+
by setting `atomic` to `True`. This can be useful for files with potential concurrent access.
|
| 1602 |
+
|
| 1603 |
+
**Example**
|
| 1604 |
+
|
| 1605 |
+
```python
|
| 1606 |
+
@app.command()
|
| 1607 |
+
def main(config: Annotated[typer.FileText, typer.Argument(mode="a", atomic=True)]):
|
| 1608 |
+
config.write("All the text")
|
| 1609 |
+
```
|
| 1610 |
+
"""
|
| 1611 |
+
),
|
| 1612 |
+
] = False,
|
| 1613 |
+
# Path
|
| 1614 |
+
exists: Annotated[
|
| 1615 |
+
bool,
|
| 1616 |
+
Doc(
|
| 1617 |
+
"""
|
| 1618 |
+
When set to `True` for a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/),
|
| 1619 |
+
additional validation is performed to check that the file or directory exists. If not, the value will be invalid.
|
| 1620 |
+
|
| 1621 |
+
**Example**
|
| 1622 |
+
|
| 1623 |
+
```python
|
| 1624 |
+
from pathlib import Path
|
| 1625 |
+
|
| 1626 |
+
@app.command()
|
| 1627 |
+
def main(config: Annotated[Path, typer.Argument(exists=True)]):
|
| 1628 |
+
text = config.read_text()
|
| 1629 |
+
print(f"Config file contents: {text}")
|
| 1630 |
+
```
|
| 1631 |
+
"""
|
| 1632 |
+
),
|
| 1633 |
+
] = False,
|
| 1634 |
+
file_okay: Annotated[
|
| 1635 |
+
bool,
|
| 1636 |
+
Doc(
|
| 1637 |
+
"""
|
| 1638 |
+
Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)
|
| 1639 |
+
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.
|
| 1640 |
+
|
| 1641 |
+
**Example**
|
| 1642 |
+
|
| 1643 |
+
```python
|
| 1644 |
+
from pathlib import Path
|
| 1645 |
+
|
| 1646 |
+
@app.command()
|
| 1647 |
+
def main(config: Annotated[Path, typer.Argument(exists=True, file_okay=False)]):
|
| 1648 |
+
print(f"Directory listing: {[x.name for x in config.iterdir()]}")
|
| 1649 |
+
```
|
| 1650 |
+
"""
|
| 1651 |
+
),
|
| 1652 |
+
] = True,
|
| 1653 |
+
dir_okay: Annotated[
|
| 1654 |
+
bool,
|
| 1655 |
+
Doc(
|
| 1656 |
+
"""
|
| 1657 |
+
Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)
|
| 1658 |
+
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.
|
| 1659 |
+
|
| 1660 |
+
**Example**
|
| 1661 |
+
|
| 1662 |
+
```python
|
| 1663 |
+
from pathlib import Path
|
| 1664 |
+
|
| 1665 |
+
@app.command()
|
| 1666 |
+
def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]):
|
| 1667 |
+
text = config.read_text()
|
| 1668 |
+
print(f"Config file contents: {text}")
|
| 1669 |
+
```
|
| 1670 |
+
"""
|
| 1671 |
+
),
|
| 1672 |
+
] = True,
|
| 1673 |
+
writable: Annotated[
|
| 1674 |
+
bool,
|
| 1675 |
+
Doc(
|
| 1676 |
+
"""
|
| 1677 |
+
Whether or not to perform a writable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
|
| 1678 |
+
|
| 1679 |
+
**Example**
|
| 1680 |
+
|
| 1681 |
+
```python
|
| 1682 |
+
from pathlib import Path
|
| 1683 |
+
|
| 1684 |
+
@app.command()
|
| 1685 |
+
def main(config: Annotated[Path, typer.Argument(writable=True)]):
|
| 1686 |
+
config.write_text("All the text")
|
| 1687 |
+
```
|
| 1688 |
+
"""
|
| 1689 |
+
),
|
| 1690 |
+
] = False,
|
| 1691 |
+
readable: Annotated[
|
| 1692 |
+
bool,
|
| 1693 |
+
Doc(
|
| 1694 |
+
"""
|
| 1695 |
+
Whether or not to perform a readable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
|
| 1696 |
+
|
| 1697 |
+
**Example**
|
| 1698 |
+
|
| 1699 |
+
```python
|
| 1700 |
+
from pathlib import Path
|
| 1701 |
+
|
| 1702 |
+
@app.command()
|
| 1703 |
+
def main(config: Annotated[Path, typer.Argument(readable=True)]):
|
| 1704 |
+
config.read_text("All the text")
|
| 1705 |
+
```
|
| 1706 |
+
"""
|
| 1707 |
+
),
|
| 1708 |
+
] = True,
|
| 1709 |
+
resolve_path: Annotated[
|
| 1710 |
+
bool,
|
| 1711 |
+
Doc(
|
| 1712 |
+
"""
|
| 1713 |
+
Whether or not to fully resolve the path of this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/),
|
| 1714 |
+
meaning that the path becomes absolute and symlinks are resolved.
|
| 1715 |
+
|
| 1716 |
+
**Example**
|
| 1717 |
+
|
| 1718 |
+
```python
|
| 1719 |
+
from pathlib import Path
|
| 1720 |
+
|
| 1721 |
+
@app.command()
|
| 1722 |
+
def main(config: Annotated[Path, typer.Argument(resolve_path=True)]):
|
| 1723 |
+
config.read_text("All the text")
|
| 1724 |
+
```
|
| 1725 |
+
"""
|
| 1726 |
+
),
|
| 1727 |
+
] = False,
|
| 1728 |
+
allow_dash: Annotated[
|
| 1729 |
+
bool,
|
| 1730 |
+
Doc(
|
| 1731 |
+
"""
|
| 1732 |
+
When set to `True`, a single dash for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)
|
| 1733 |
+
would be a valid value, indicating standard streams. This is a more advanced use-case.
|
| 1734 |
+
"""
|
| 1735 |
+
),
|
| 1736 |
+
] = False,
|
| 1737 |
+
path_type: Annotated[
|
| 1738 |
+
None | type[str] | type[bytes],
|
| 1739 |
+
Doc(
|
| 1740 |
+
"""
|
| 1741 |
+
A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
|
| 1742 |
+
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.
|
| 1743 |
+
This is a more advanced use-case.
|
| 1744 |
+
"""
|
| 1745 |
+
),
|
| 1746 |
+
] = None,
|
| 1747 |
+
# Rich settings
|
| 1748 |
+
rich_help_panel: Annotated[
|
| 1749 |
+
str | None,
|
| 1750 |
+
Doc(
|
| 1751 |
+
"""
|
| 1752 |
+
Set the panel name where you want this CLI Argument to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).
|
| 1753 |
+
|
| 1754 |
+
**Example**
|
| 1755 |
+
|
| 1756 |
+
```python
|
| 1757 |
+
@app.command()
|
| 1758 |
+
def main(
|
| 1759 |
+
name: Annotated[str, typer.Argument(help="Who to greet")],
|
| 1760 |
+
age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")],
|
| 1761 |
+
):
|
| 1762 |
+
print(f"Hello {name} of age {age}")
|
| 1763 |
+
```
|
| 1764 |
+
"""
|
| 1765 |
+
),
|
| 1766 |
+
] = None,
|
| 1767 |
+
) -> Any:
|
| 1768 |
+
"""
|
| 1769 |
+
A [CLI Argument](https://typer.tiangolo.com/tutorial/arguments) is a positional parameter to your command line application.
|
| 1770 |
+
|
| 1771 |
+
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:
|
| 1772 |
+
|
| 1773 |
+
## Example
|
| 1774 |
+
|
| 1775 |
+
```python
|
| 1776 |
+
@app.command()
|
| 1777 |
+
def main(name: Annotated[str, typer.Argument()] = "World"):
|
| 1778 |
+
print(f"Hello {name}!")
|
| 1779 |
+
```
|
| 1780 |
+
|
| 1781 |
+
Note how in this example, if `name` is not specified on the command line, the application will still execute normally and print "Hello World!".
|
| 1782 |
+
"""
|
| 1783 |
+
return ArgumentInfo(
|
| 1784 |
+
# Parameter
|
| 1785 |
+
default=default,
|
| 1786 |
+
# Arguments can only have one param declaration
|
| 1787 |
+
# it will be generated from the param name
|
| 1788 |
+
param_decls=None,
|
| 1789 |
+
callback=callback,
|
| 1790 |
+
metavar=metavar,
|
| 1791 |
+
expose_value=expose_value,
|
| 1792 |
+
is_eager=is_eager,
|
| 1793 |
+
envvar=envvar,
|
| 1794 |
+
shell_complete=shell_complete,
|
| 1795 |
+
autocompletion=autocompletion,
|
| 1796 |
+
default_factory=default_factory,
|
| 1797 |
+
# Custom type
|
| 1798 |
+
parser=parser,
|
| 1799 |
+
click_type=click_type,
|
| 1800 |
+
# TyperArgument
|
| 1801 |
+
show_default=show_default,
|
| 1802 |
+
show_choices=show_choices,
|
| 1803 |
+
show_envvar=show_envvar,
|
| 1804 |
+
help=help,
|
| 1805 |
+
hidden=hidden,
|
| 1806 |
+
# Choice
|
| 1807 |
+
case_sensitive=case_sensitive,
|
| 1808 |
+
# Numbers
|
| 1809 |
+
min=min,
|
| 1810 |
+
max=max,
|
| 1811 |
+
clamp=clamp,
|
| 1812 |
+
# DateTime
|
| 1813 |
+
formats=formats,
|
| 1814 |
+
# File
|
| 1815 |
+
mode=mode,
|
| 1816 |
+
encoding=encoding,
|
| 1817 |
+
errors=errors,
|
| 1818 |
+
lazy=lazy,
|
| 1819 |
+
atomic=atomic,
|
| 1820 |
+
# Path
|
| 1821 |
+
exists=exists,
|
| 1822 |
+
file_okay=file_okay,
|
| 1823 |
+
dir_okay=dir_okay,
|
| 1824 |
+
writable=writable,
|
| 1825 |
+
readable=readable,
|
| 1826 |
+
resolve_path=resolve_path,
|
| 1827 |
+
allow_dash=allow_dash,
|
| 1828 |
+
path_type=path_type,
|
| 1829 |
+
# Rich settings
|
| 1830 |
+
rich_help_panel=rich_help_panel,
|
| 1831 |
+
)
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/py.typed
ADDED
|
File without changes
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/rich_utils.py
ADDED
|
@@ -0,0 +1,753 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Extracted and modified from https://github.com/ewels/rich-click
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import io
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from collections.abc import Iterable
|
| 7 |
+
from gettext import gettext as _
|
| 8 |
+
from os import getenv
|
| 9 |
+
from typing import Any, Literal
|
| 10 |
+
|
| 11 |
+
import click
|
| 12 |
+
from rich import box
|
| 13 |
+
from rich.align import Align
|
| 14 |
+
from rich.columns import Columns
|
| 15 |
+
from rich.console import Console, RenderableType, group
|
| 16 |
+
from rich.emoji import Emoji
|
| 17 |
+
from rich.highlighter import RegexHighlighter
|
| 18 |
+
from rich.markdown import Markdown
|
| 19 |
+
from rich.markup import escape
|
| 20 |
+
from rich.padding import Padding
|
| 21 |
+
from rich.panel import Panel
|
| 22 |
+
from rich.table import Table
|
| 23 |
+
from rich.text import Text
|
| 24 |
+
from rich.theme import Theme
|
| 25 |
+
from rich.traceback import Traceback
|
| 26 |
+
from typer.models import DeveloperExceptionConfig
|
| 27 |
+
|
| 28 |
+
# Default styles
|
| 29 |
+
STYLE_OPTION = "bold cyan"
|
| 30 |
+
STYLE_SWITCH = "bold green"
|
| 31 |
+
STYLE_NEGATIVE_OPTION = "bold magenta"
|
| 32 |
+
STYLE_NEGATIVE_SWITCH = "bold red"
|
| 33 |
+
STYLE_METAVAR = "bold yellow"
|
| 34 |
+
STYLE_METAVAR_SEPARATOR = "dim"
|
| 35 |
+
STYLE_USAGE = "yellow"
|
| 36 |
+
STYLE_USAGE_COMMAND = "bold"
|
| 37 |
+
STYLE_DEPRECATED = "red"
|
| 38 |
+
STYLE_DEPRECATED_COMMAND = "dim"
|
| 39 |
+
STYLE_HELPTEXT_FIRST_LINE = ""
|
| 40 |
+
STYLE_HELPTEXT = "dim"
|
| 41 |
+
STYLE_OPTION_HELP = ""
|
| 42 |
+
STYLE_OPTION_DEFAULT = "dim"
|
| 43 |
+
STYLE_OPTION_ENVVAR = "dim yellow"
|
| 44 |
+
STYLE_REQUIRED_SHORT = "red"
|
| 45 |
+
STYLE_REQUIRED_LONG = "dim red"
|
| 46 |
+
STYLE_OPTIONS_PANEL_BORDER = "dim"
|
| 47 |
+
ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left"
|
| 48 |
+
STYLE_OPTIONS_TABLE_SHOW_LINES = False
|
| 49 |
+
STYLE_OPTIONS_TABLE_LEADING = 0
|
| 50 |
+
STYLE_OPTIONS_TABLE_PAD_EDGE = False
|
| 51 |
+
STYLE_OPTIONS_TABLE_PADDING = (0, 1)
|
| 52 |
+
STYLE_OPTIONS_TABLE_BOX = ""
|
| 53 |
+
STYLE_OPTIONS_TABLE_ROW_STYLES = None
|
| 54 |
+
STYLE_OPTIONS_TABLE_BORDER_STYLE = None
|
| 55 |
+
STYLE_COMMANDS_PANEL_BORDER = "dim"
|
| 56 |
+
ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left"
|
| 57 |
+
STYLE_COMMANDS_TABLE_SHOW_LINES = False
|
| 58 |
+
STYLE_COMMANDS_TABLE_LEADING = 0
|
| 59 |
+
STYLE_COMMANDS_TABLE_PAD_EDGE = False
|
| 60 |
+
STYLE_COMMANDS_TABLE_PADDING = (0, 1)
|
| 61 |
+
STYLE_COMMANDS_TABLE_BOX = ""
|
| 62 |
+
STYLE_COMMANDS_TABLE_ROW_STYLES = None
|
| 63 |
+
STYLE_COMMANDS_TABLE_BORDER_STYLE = None
|
| 64 |
+
STYLE_COMMANDS_TABLE_FIRST_COLUMN = "bold cyan"
|
| 65 |
+
STYLE_ERRORS_PANEL_BORDER = "red"
|
| 66 |
+
ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left"
|
| 67 |
+
STYLE_ERRORS_SUGGESTION = "dim"
|
| 68 |
+
STYLE_ABORTED = "red"
|
| 69 |
+
_TERMINAL_WIDTH = getenv("TERMINAL_WIDTH")
|
| 70 |
+
MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None
|
| 71 |
+
COLOR_SYSTEM: Literal["auto", "standard", "256", "truecolor", "windows"] | None = (
|
| 72 |
+
"auto" # Set to None to disable colors
|
| 73 |
+
)
|
| 74 |
+
_TYPER_FORCE_DISABLE_TERMINAL = getenv("_TYPER_FORCE_DISABLE_TERMINAL")
|
| 75 |
+
FORCE_TERMINAL = (
|
| 76 |
+
True
|
| 77 |
+
if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS")
|
| 78 |
+
else None
|
| 79 |
+
)
|
| 80 |
+
if _TYPER_FORCE_DISABLE_TERMINAL:
|
| 81 |
+
FORCE_TERMINAL = False
|
| 82 |
+
|
| 83 |
+
# Fixed strings
|
| 84 |
+
DEPRECATED_STRING = _("(deprecated) ")
|
| 85 |
+
DEFAULT_STRING = _("[default: {}]")
|
| 86 |
+
ENVVAR_STRING = _("[env var: {}]")
|
| 87 |
+
REQUIRED_SHORT_STRING = "*"
|
| 88 |
+
REQUIRED_LONG_STRING = _("[required]")
|
| 89 |
+
RANGE_STRING = " [{}]"
|
| 90 |
+
ARGUMENTS_PANEL_TITLE = _("Arguments")
|
| 91 |
+
OPTIONS_PANEL_TITLE = _("Options")
|
| 92 |
+
COMMANDS_PANEL_TITLE = _("Commands")
|
| 93 |
+
ERRORS_PANEL_TITLE = _("Error")
|
| 94 |
+
ABORTED_TEXT = _("Aborted.")
|
| 95 |
+
RICH_HELP = _("Try [blue]'{command_path} {help_option}'[/] for help.")
|
| 96 |
+
|
| 97 |
+
MARKUP_MODE_MARKDOWN = "markdown"
|
| 98 |
+
MARKUP_MODE_RICH = "rich"
|
| 99 |
+
_RICH_HELP_PANEL_NAME = "rich_help_panel"
|
| 100 |
+
ANSI_PREFIX = "\033["
|
| 101 |
+
|
| 102 |
+
MarkupModeStrict = Literal["markdown", "rich"]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# Rich regex highlighter
|
| 106 |
+
class OptionHighlighter(RegexHighlighter):
|
| 107 |
+
"""Highlights our special options."""
|
| 108 |
+
|
| 109 |
+
highlights = [
|
| 110 |
+
r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",
|
| 111 |
+
r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
|
| 112 |
+
r"(?P<metavar>\<[^\>]+\>)",
|
| 113 |
+
r"(?P<usage>Usage: )",
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class NegativeOptionHighlighter(RegexHighlighter):
|
| 118 |
+
highlights = [
|
| 119 |
+
r"(^|\W)(?P<negative_switch>\-\w+)(?![a-zA-Z0-9])",
|
| 120 |
+
r"(^|\W)(?P<negative_option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
|
| 121 |
+
]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# Highlighter to make [ | ] and <> dim
|
| 125 |
+
class MetavarHighlighter(RegexHighlighter):
|
| 126 |
+
highlights = [
|
| 127 |
+
r"^(?P<metavar_sep>(\[|<))",
|
| 128 |
+
r"(?P<metavar_sep>\|)",
|
| 129 |
+
r"(?P<metavar_sep>(\]|>))(\.\.\.)?$",
|
| 130 |
+
]
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
highlighter = OptionHighlighter()
|
| 134 |
+
negative_highlighter = NegativeOptionHighlighter()
|
| 135 |
+
metavar_highlighter = MetavarHighlighter()
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _has_ansi_character(text: str) -> bool:
|
| 139 |
+
return ANSI_PREFIX in text
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _get_rich_console(stderr: bool = False) -> Console:
|
| 143 |
+
return Console(
|
| 144 |
+
theme=Theme(
|
| 145 |
+
{
|
| 146 |
+
"option": STYLE_OPTION,
|
| 147 |
+
"switch": STYLE_SWITCH,
|
| 148 |
+
"negative_option": STYLE_NEGATIVE_OPTION,
|
| 149 |
+
"negative_switch": STYLE_NEGATIVE_SWITCH,
|
| 150 |
+
"metavar": STYLE_METAVAR,
|
| 151 |
+
"metavar_sep": STYLE_METAVAR_SEPARATOR,
|
| 152 |
+
"usage": STYLE_USAGE,
|
| 153 |
+
},
|
| 154 |
+
),
|
| 155 |
+
highlighter=highlighter,
|
| 156 |
+
color_system=COLOR_SYSTEM,
|
| 157 |
+
force_terminal=FORCE_TERMINAL,
|
| 158 |
+
width=MAX_WIDTH,
|
| 159 |
+
stderr=stderr,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _make_rich_text(
|
| 164 |
+
*, text: str, style: str = "", markup_mode: MarkupModeStrict
|
| 165 |
+
) -> Markdown | Text:
|
| 166 |
+
"""Take a string, remove indentations, and return styled text.
|
| 167 |
+
|
| 168 |
+
If `markup_mode` is `"rich"`, the text is parsed for Rich markup strings.
|
| 169 |
+
If `markup_mode` is `"markdown"`, parse as Markdown.
|
| 170 |
+
"""
|
| 171 |
+
# Remove indentations from input text
|
| 172 |
+
text = inspect.cleandoc(text)
|
| 173 |
+
if markup_mode == MARKUP_MODE_MARKDOWN:
|
| 174 |
+
text = Emoji.replace(text)
|
| 175 |
+
return Markdown(text, style=style)
|
| 176 |
+
else:
|
| 177 |
+
assert markup_mode == MARKUP_MODE_RICH
|
| 178 |
+
if _has_ansi_character(text):
|
| 179 |
+
return highlighter(Text.from_ansi(text, style=style))
|
| 180 |
+
else:
|
| 181 |
+
return highlighter(Text.from_markup(text, style=style))
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@group()
|
| 185 |
+
def _get_help_text(
|
| 186 |
+
*,
|
| 187 |
+
obj: click.Command | click.Group,
|
| 188 |
+
markup_mode: MarkupModeStrict,
|
| 189 |
+
) -> Iterable[Markdown | Text]:
|
| 190 |
+
"""Build primary help text for a click command or group.
|
| 191 |
+
|
| 192 |
+
Returns the prose help text for a command or group, rendered either as a
|
| 193 |
+
Rich Text object or as Markdown.
|
| 194 |
+
If the command is marked as deprecated, the deprecated string will be prepended.
|
| 195 |
+
"""
|
| 196 |
+
# Prepend deprecated status
|
| 197 |
+
if obj.deprecated:
|
| 198 |
+
yield Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)
|
| 199 |
+
|
| 200 |
+
# Fetch and dedent the help text
|
| 201 |
+
help_text = inspect.cleandoc(obj.help or "")
|
| 202 |
+
|
| 203 |
+
# Trim off anything that comes after \f on its own line
|
| 204 |
+
help_text = help_text.partition("\f")[0]
|
| 205 |
+
|
| 206 |
+
# Get the first paragraph
|
| 207 |
+
first_line, *remaining_paragraphs = help_text.split("\n\n")
|
| 208 |
+
|
| 209 |
+
# Remove single linebreaks
|
| 210 |
+
if markup_mode != MARKUP_MODE_MARKDOWN and not first_line.startswith("\b"):
|
| 211 |
+
first_line = first_line.replace("\n", " ")
|
| 212 |
+
yield _make_rich_text(
|
| 213 |
+
text=first_line.strip(),
|
| 214 |
+
style=STYLE_HELPTEXT_FIRST_LINE,
|
| 215 |
+
markup_mode=markup_mode,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
# Get remaining lines, remove single line breaks and format as dim
|
| 219 |
+
if remaining_paragraphs:
|
| 220 |
+
# Add a newline inbetween the header and the remaining paragraphs
|
| 221 |
+
yield Text("")
|
| 222 |
+
# Join with double linebreaks for markdown and Rich markup
|
| 223 |
+
remaining_lines = "\n\n".join(remaining_paragraphs)
|
| 224 |
+
|
| 225 |
+
yield _make_rich_text(
|
| 226 |
+
text=remaining_lines,
|
| 227 |
+
style=STYLE_HELPTEXT,
|
| 228 |
+
markup_mode=markup_mode,
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _get_parameter_help(
|
| 233 |
+
*,
|
| 234 |
+
param: click.Option | click.Argument | click.Parameter,
|
| 235 |
+
ctx: click.Context,
|
| 236 |
+
markup_mode: MarkupModeStrict,
|
| 237 |
+
) -> Columns:
|
| 238 |
+
"""Build primary help text for a click option or argument.
|
| 239 |
+
|
| 240 |
+
Returns the prose help text for an option or argument, rendered either
|
| 241 |
+
as a Rich Text object or as Markdown.
|
| 242 |
+
Additional elements are appended to show the default and required status if
|
| 243 |
+
applicable.
|
| 244 |
+
"""
|
| 245 |
+
# import here to avoid cyclic imports
|
| 246 |
+
from .core import TyperArgument, TyperOption
|
| 247 |
+
|
| 248 |
+
items: list[Text | Markdown] = []
|
| 249 |
+
|
| 250 |
+
# Get the environment variable first
|
| 251 |
+
|
| 252 |
+
envvar = getattr(param, "envvar", None)
|
| 253 |
+
var_str = ""
|
| 254 |
+
# https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L2720-L2726
|
| 255 |
+
if envvar is None:
|
| 256 |
+
if (
|
| 257 |
+
getattr(param, "allow_from_autoenv", None)
|
| 258 |
+
and getattr(ctx, "auto_envvar_prefix", None) is not None
|
| 259 |
+
and param.name is not None
|
| 260 |
+
):
|
| 261 |
+
envvar = f"{ctx.auto_envvar_prefix}_{param.name.upper()}"
|
| 262 |
+
if envvar is not None:
|
| 263 |
+
var_str = (
|
| 264 |
+
envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar)
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# Main help text
|
| 268 |
+
help_value: str | None = getattr(param, "help", None)
|
| 269 |
+
if help_value:
|
| 270 |
+
paragraphs = help_value.split("\n\n")
|
| 271 |
+
# Remove single linebreaks
|
| 272 |
+
if markup_mode != MARKUP_MODE_MARKDOWN:
|
| 273 |
+
paragraphs = [
|
| 274 |
+
x.replace("\n", " ").strip()
|
| 275 |
+
if not x.startswith("\b")
|
| 276 |
+
else "{}\n".format(x.strip("\b\n"))
|
| 277 |
+
for x in paragraphs
|
| 278 |
+
]
|
| 279 |
+
items.append(
|
| 280 |
+
_make_rich_text(
|
| 281 |
+
text="\n".join(paragraphs).strip(),
|
| 282 |
+
style=STYLE_OPTION_HELP,
|
| 283 |
+
markup_mode=markup_mode,
|
| 284 |
+
)
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
# Environment variable AFTER help text
|
| 288 |
+
if envvar and getattr(param, "show_envvar", None):
|
| 289 |
+
items.append(Text(ENVVAR_STRING.format(var_str), style=STYLE_OPTION_ENVVAR))
|
| 290 |
+
|
| 291 |
+
# Default value
|
| 292 |
+
# This uses Typer's specific param._get_default_string
|
| 293 |
+
if isinstance(param, (TyperOption, TyperArgument)):
|
| 294 |
+
default_value = param._extract_default_help_str(ctx=ctx)
|
| 295 |
+
show_default_is_str = isinstance(param.show_default, str)
|
| 296 |
+
if show_default_is_str or (
|
| 297 |
+
default_value is not None and (param.show_default or ctx.show_default)
|
| 298 |
+
):
|
| 299 |
+
default_str = param._get_default_string(
|
| 300 |
+
ctx=ctx,
|
| 301 |
+
show_default_is_str=show_default_is_str,
|
| 302 |
+
default_value=default_value,
|
| 303 |
+
)
|
| 304 |
+
if default_str:
|
| 305 |
+
items.append(
|
| 306 |
+
Text(
|
| 307 |
+
DEFAULT_STRING.format(default_str),
|
| 308 |
+
style=STYLE_OPTION_DEFAULT,
|
| 309 |
+
)
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
# Required?
|
| 313 |
+
if param.required:
|
| 314 |
+
items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG))
|
| 315 |
+
|
| 316 |
+
# Use Columns - this allows us to group different renderable types
|
| 317 |
+
# (Text, Markdown) onto a single line.
|
| 318 |
+
return Columns(items)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def _make_command_help(
|
| 322 |
+
*,
|
| 323 |
+
help_text: str,
|
| 324 |
+
markup_mode: MarkupModeStrict,
|
| 325 |
+
) -> Text | Markdown:
|
| 326 |
+
"""Build cli help text for a click group command.
|
| 327 |
+
|
| 328 |
+
That is, when calling help on groups with multiple subcommands
|
| 329 |
+
(not the main help text when calling the subcommand help).
|
| 330 |
+
|
| 331 |
+
Returns the first paragraph of help text for a command, rendered either as a
|
| 332 |
+
Rich Text object or as Markdown.
|
| 333 |
+
Ignores single newlines as paragraph markers, looks for double only.
|
| 334 |
+
"""
|
| 335 |
+
paragraphs = inspect.cleandoc(help_text).split("\n\n")
|
| 336 |
+
# Remove single linebreaks
|
| 337 |
+
if markup_mode != MARKUP_MODE_RICH and not paragraphs[0].startswith("\b"):
|
| 338 |
+
paragraphs[0] = paragraphs[0].replace("\n", " ")
|
| 339 |
+
elif paragraphs[0].startswith("\b"):
|
| 340 |
+
paragraphs[0] = paragraphs[0].replace("\b\n", "")
|
| 341 |
+
return _make_rich_text(
|
| 342 |
+
text=paragraphs[0].strip(),
|
| 343 |
+
style=STYLE_OPTION_HELP,
|
| 344 |
+
markup_mode=markup_mode,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def _print_options_panel(
|
| 349 |
+
*,
|
| 350 |
+
name: str,
|
| 351 |
+
params: list[click.Option] | list[click.Argument],
|
| 352 |
+
ctx: click.Context,
|
| 353 |
+
markup_mode: MarkupModeStrict,
|
| 354 |
+
console: Console,
|
| 355 |
+
) -> None:
|
| 356 |
+
options_rows: list[list[RenderableType]] = []
|
| 357 |
+
required_rows: list[str | Text] = []
|
| 358 |
+
for param in params:
|
| 359 |
+
# Short and long form
|
| 360 |
+
opt_long_strs = []
|
| 361 |
+
opt_short_strs = []
|
| 362 |
+
secondary_opt_long_strs = []
|
| 363 |
+
secondary_opt_short_strs = []
|
| 364 |
+
for opt_str in param.opts:
|
| 365 |
+
if "--" in opt_str:
|
| 366 |
+
opt_long_strs.append(opt_str)
|
| 367 |
+
else:
|
| 368 |
+
opt_short_strs.append(opt_str)
|
| 369 |
+
for opt_str in param.secondary_opts:
|
| 370 |
+
if "--" in opt_str:
|
| 371 |
+
secondary_opt_long_strs.append(opt_str)
|
| 372 |
+
else:
|
| 373 |
+
secondary_opt_short_strs.append(opt_str)
|
| 374 |
+
|
| 375 |
+
# Column for a metavar, if we have one
|
| 376 |
+
metavar = Text(style=STYLE_METAVAR, overflow="fold")
|
| 377 |
+
metavar_str = param.make_metavar(ctx=ctx)
|
| 378 |
+
# Do it ourselves if this is a positional argument
|
| 379 |
+
if (
|
| 380 |
+
isinstance(param, click.Argument)
|
| 381 |
+
and param.name
|
| 382 |
+
and metavar_str == param.name.upper()
|
| 383 |
+
):
|
| 384 |
+
metavar_str = param.type.name.upper()
|
| 385 |
+
|
| 386 |
+
# Skip booleans and choices (handled above)
|
| 387 |
+
if metavar_str != "BOOLEAN":
|
| 388 |
+
metavar.append(metavar_str)
|
| 389 |
+
|
| 390 |
+
# Range - from
|
| 391 |
+
# https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501
|
| 392 |
+
# skip count with default range type
|
| 393 |
+
if (
|
| 394 |
+
isinstance(param.type, click.types._NumberRangeBase)
|
| 395 |
+
and isinstance(param, click.Option)
|
| 396 |
+
and not (param.count and param.type.min == 0 and param.type.max is None)
|
| 397 |
+
):
|
| 398 |
+
range_str = param.type._describe_range()
|
| 399 |
+
if range_str:
|
| 400 |
+
metavar.append(RANGE_STRING.format(range_str))
|
| 401 |
+
|
| 402 |
+
# Required asterisk
|
| 403 |
+
required: str | Text = ""
|
| 404 |
+
if param.required:
|
| 405 |
+
required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT)
|
| 406 |
+
|
| 407 |
+
required_rows.append(required)
|
| 408 |
+
options_rows.append(
|
| 409 |
+
[
|
| 410 |
+
highlighter(",".join(opt_long_strs)),
|
| 411 |
+
highlighter(",".join(opt_short_strs)),
|
| 412 |
+
negative_highlighter(",".join(secondary_opt_long_strs)),
|
| 413 |
+
negative_highlighter(",".join(secondary_opt_short_strs)),
|
| 414 |
+
metavar_highlighter(metavar),
|
| 415 |
+
_get_parameter_help(
|
| 416 |
+
param=param,
|
| 417 |
+
ctx=ctx,
|
| 418 |
+
markup_mode=markup_mode,
|
| 419 |
+
),
|
| 420 |
+
]
|
| 421 |
+
)
|
| 422 |
+
rows_with_required: list[list[RenderableType]] = []
|
| 423 |
+
if any(required_rows):
|
| 424 |
+
for required, row in zip(required_rows, options_rows, strict=True):
|
| 425 |
+
rows_with_required.append([required, *row])
|
| 426 |
+
else:
|
| 427 |
+
rows_with_required = options_rows
|
| 428 |
+
if options_rows:
|
| 429 |
+
t_styles: dict[str, Any] = {
|
| 430 |
+
"show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES,
|
| 431 |
+
"leading": STYLE_OPTIONS_TABLE_LEADING,
|
| 432 |
+
"box": STYLE_OPTIONS_TABLE_BOX,
|
| 433 |
+
"border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE,
|
| 434 |
+
"row_styles": STYLE_OPTIONS_TABLE_ROW_STYLES,
|
| 435 |
+
"pad_edge": STYLE_OPTIONS_TABLE_PAD_EDGE,
|
| 436 |
+
"padding": STYLE_OPTIONS_TABLE_PADDING,
|
| 437 |
+
}
|
| 438 |
+
box_style = getattr(box, t_styles.pop("box"), None)
|
| 439 |
+
|
| 440 |
+
options_table = Table(
|
| 441 |
+
highlight=True,
|
| 442 |
+
show_header=False,
|
| 443 |
+
expand=True,
|
| 444 |
+
box=box_style,
|
| 445 |
+
**t_styles,
|
| 446 |
+
)
|
| 447 |
+
for row in rows_with_required:
|
| 448 |
+
options_table.add_row(*row)
|
| 449 |
+
console.print(
|
| 450 |
+
Panel(
|
| 451 |
+
options_table,
|
| 452 |
+
border_style=STYLE_OPTIONS_PANEL_BORDER,
|
| 453 |
+
title=name,
|
| 454 |
+
title_align=ALIGN_OPTIONS_PANEL,
|
| 455 |
+
)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def _print_commands_panel(
|
| 460 |
+
*,
|
| 461 |
+
name: str,
|
| 462 |
+
commands: list[click.Command],
|
| 463 |
+
markup_mode: MarkupModeStrict,
|
| 464 |
+
console: Console,
|
| 465 |
+
cmd_len: int,
|
| 466 |
+
) -> None:
|
| 467 |
+
t_styles: dict[str, Any] = {
|
| 468 |
+
"show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES,
|
| 469 |
+
"leading": STYLE_COMMANDS_TABLE_LEADING,
|
| 470 |
+
"box": STYLE_COMMANDS_TABLE_BOX,
|
| 471 |
+
"border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE,
|
| 472 |
+
"row_styles": STYLE_COMMANDS_TABLE_ROW_STYLES,
|
| 473 |
+
"pad_edge": STYLE_COMMANDS_TABLE_PAD_EDGE,
|
| 474 |
+
"padding": STYLE_COMMANDS_TABLE_PADDING,
|
| 475 |
+
}
|
| 476 |
+
box_style = getattr(box, t_styles.pop("box"), None)
|
| 477 |
+
|
| 478 |
+
commands_table = Table(
|
| 479 |
+
highlight=False,
|
| 480 |
+
show_header=False,
|
| 481 |
+
expand=True,
|
| 482 |
+
box=box_style,
|
| 483 |
+
**t_styles,
|
| 484 |
+
)
|
| 485 |
+
# Define formatting in first column, as commands don't match highlighter
|
| 486 |
+
# regex
|
| 487 |
+
commands_table.add_column(
|
| 488 |
+
style=STYLE_COMMANDS_TABLE_FIRST_COLUMN,
|
| 489 |
+
no_wrap=True,
|
| 490 |
+
width=cmd_len,
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
# A big ratio makes the description column be greedy and take all the space
|
| 494 |
+
# available instead of allowing the command column to grow and misalign with
|
| 495 |
+
# other panels.
|
| 496 |
+
commands_table.add_column("Description", justify="left", no_wrap=False, ratio=10)
|
| 497 |
+
rows: list[list[RenderableType | None]] = []
|
| 498 |
+
deprecated_rows: list[RenderableType | None] = []
|
| 499 |
+
for command in commands:
|
| 500 |
+
helptext = command.short_help or command.help or ""
|
| 501 |
+
command_name = command.name or ""
|
| 502 |
+
if command.deprecated:
|
| 503 |
+
command_name_text = Text(f"{command_name}", style=STYLE_DEPRECATED_COMMAND)
|
| 504 |
+
deprecated_rows.append(Text(DEPRECATED_STRING, style=STYLE_DEPRECATED))
|
| 505 |
+
else:
|
| 506 |
+
command_name_text = Text(command_name)
|
| 507 |
+
deprecated_rows.append(None)
|
| 508 |
+
rows.append(
|
| 509 |
+
[
|
| 510 |
+
command_name_text,
|
| 511 |
+
_make_command_help(
|
| 512 |
+
help_text=helptext,
|
| 513 |
+
markup_mode=markup_mode,
|
| 514 |
+
),
|
| 515 |
+
]
|
| 516 |
+
)
|
| 517 |
+
rows_with_deprecated = rows
|
| 518 |
+
if any(deprecated_rows):
|
| 519 |
+
rows_with_deprecated = []
|
| 520 |
+
for row, deprecated_text in zip(rows, deprecated_rows, strict=True):
|
| 521 |
+
rows_with_deprecated.append([*row, deprecated_text])
|
| 522 |
+
for row in rows_with_deprecated:
|
| 523 |
+
commands_table.add_row(*row)
|
| 524 |
+
if commands_table.row_count:
|
| 525 |
+
console.print(
|
| 526 |
+
Panel(
|
| 527 |
+
commands_table,
|
| 528 |
+
border_style=STYLE_COMMANDS_PANEL_BORDER,
|
| 529 |
+
title=name,
|
| 530 |
+
title_align=ALIGN_COMMANDS_PANEL,
|
| 531 |
+
)
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def rich_format_help(
|
| 536 |
+
*,
|
| 537 |
+
obj: click.Command | click.Group,
|
| 538 |
+
ctx: click.Context,
|
| 539 |
+
markup_mode: MarkupModeStrict,
|
| 540 |
+
) -> None:
|
| 541 |
+
"""Print nicely formatted help text using rich.
|
| 542 |
+
|
| 543 |
+
Based on original code from rich-cli, by @willmcgugan.
|
| 544 |
+
https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236
|
| 545 |
+
|
| 546 |
+
Replacement for the click function format_help().
|
| 547 |
+
Takes a command or group and builds the help text output.
|
| 548 |
+
"""
|
| 549 |
+
console = _get_rich_console()
|
| 550 |
+
|
| 551 |
+
# Print usage
|
| 552 |
+
console.print(
|
| 553 |
+
Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
# Print command / group help if we have some
|
| 557 |
+
if obj.help:
|
| 558 |
+
# Print with some padding
|
| 559 |
+
console.print(
|
| 560 |
+
Padding(
|
| 561 |
+
Align(
|
| 562 |
+
_get_help_text(
|
| 563 |
+
obj=obj,
|
| 564 |
+
markup_mode=markup_mode,
|
| 565 |
+
),
|
| 566 |
+
pad=False,
|
| 567 |
+
),
|
| 568 |
+
(0, 1, 1, 1),
|
| 569 |
+
)
|
| 570 |
+
)
|
| 571 |
+
panel_to_arguments: defaultdict[str, list[click.Argument]] = defaultdict(list)
|
| 572 |
+
panel_to_options: defaultdict[str, list[click.Option]] = defaultdict(list)
|
| 573 |
+
for param in obj.get_params(ctx):
|
| 574 |
+
# Skip if option is hidden
|
| 575 |
+
if getattr(param, "hidden", False):
|
| 576 |
+
continue
|
| 577 |
+
if isinstance(param, click.Argument):
|
| 578 |
+
panel_name = (
|
| 579 |
+
getattr(param, _RICH_HELP_PANEL_NAME, None) or ARGUMENTS_PANEL_TITLE
|
| 580 |
+
)
|
| 581 |
+
panel_to_arguments[panel_name].append(param)
|
| 582 |
+
elif isinstance(param, click.Option):
|
| 583 |
+
panel_name = (
|
| 584 |
+
getattr(param, _RICH_HELP_PANEL_NAME, None) or OPTIONS_PANEL_TITLE
|
| 585 |
+
)
|
| 586 |
+
panel_to_options[panel_name].append(param)
|
| 587 |
+
default_arguments = panel_to_arguments.get(ARGUMENTS_PANEL_TITLE, [])
|
| 588 |
+
_print_options_panel(
|
| 589 |
+
name=ARGUMENTS_PANEL_TITLE,
|
| 590 |
+
params=default_arguments,
|
| 591 |
+
ctx=ctx,
|
| 592 |
+
markup_mode=markup_mode,
|
| 593 |
+
console=console,
|
| 594 |
+
)
|
| 595 |
+
for panel_name, arguments in panel_to_arguments.items():
|
| 596 |
+
if panel_name == ARGUMENTS_PANEL_TITLE:
|
| 597 |
+
# Already printed above
|
| 598 |
+
continue
|
| 599 |
+
_print_options_panel(
|
| 600 |
+
name=panel_name,
|
| 601 |
+
params=arguments,
|
| 602 |
+
ctx=ctx,
|
| 603 |
+
markup_mode=markup_mode,
|
| 604 |
+
console=console,
|
| 605 |
+
)
|
| 606 |
+
default_options = panel_to_options.get(OPTIONS_PANEL_TITLE, [])
|
| 607 |
+
_print_options_panel(
|
| 608 |
+
name=OPTIONS_PANEL_TITLE,
|
| 609 |
+
params=default_options,
|
| 610 |
+
ctx=ctx,
|
| 611 |
+
markup_mode=markup_mode,
|
| 612 |
+
console=console,
|
| 613 |
+
)
|
| 614 |
+
for panel_name, options in panel_to_options.items():
|
| 615 |
+
if panel_name == OPTIONS_PANEL_TITLE:
|
| 616 |
+
# Already printed above
|
| 617 |
+
continue
|
| 618 |
+
_print_options_panel(
|
| 619 |
+
name=panel_name,
|
| 620 |
+
params=options,
|
| 621 |
+
ctx=ctx,
|
| 622 |
+
markup_mode=markup_mode,
|
| 623 |
+
console=console,
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
if isinstance(obj, click.Group):
|
| 627 |
+
panel_to_commands: defaultdict[str, list[click.Command]] = defaultdict(list)
|
| 628 |
+
for command_name in obj.list_commands(ctx):
|
| 629 |
+
command = obj.get_command(ctx, command_name)
|
| 630 |
+
if command and not command.hidden:
|
| 631 |
+
panel_name = (
|
| 632 |
+
getattr(command, _RICH_HELP_PANEL_NAME, None)
|
| 633 |
+
or COMMANDS_PANEL_TITLE
|
| 634 |
+
)
|
| 635 |
+
panel_to_commands[panel_name].append(command)
|
| 636 |
+
|
| 637 |
+
# Identify the longest command name in all panels
|
| 638 |
+
max_cmd_len = max(
|
| 639 |
+
[
|
| 640 |
+
len(command.name or "")
|
| 641 |
+
for commands in panel_to_commands.values()
|
| 642 |
+
for command in commands
|
| 643 |
+
],
|
| 644 |
+
default=0,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
# Print each command group panel
|
| 648 |
+
default_commands = panel_to_commands.get(COMMANDS_PANEL_TITLE, [])
|
| 649 |
+
_print_commands_panel(
|
| 650 |
+
name=COMMANDS_PANEL_TITLE,
|
| 651 |
+
commands=default_commands,
|
| 652 |
+
markup_mode=markup_mode,
|
| 653 |
+
console=console,
|
| 654 |
+
cmd_len=max_cmd_len,
|
| 655 |
+
)
|
| 656 |
+
for panel_name, commands in panel_to_commands.items():
|
| 657 |
+
if panel_name == COMMANDS_PANEL_TITLE:
|
| 658 |
+
# Already printed above
|
| 659 |
+
continue
|
| 660 |
+
_print_commands_panel(
|
| 661 |
+
name=panel_name,
|
| 662 |
+
commands=commands,
|
| 663 |
+
markup_mode=markup_mode,
|
| 664 |
+
console=console,
|
| 665 |
+
cmd_len=max_cmd_len,
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
# Epilogue if we have it
|
| 669 |
+
if obj.epilog:
|
| 670 |
+
# Remove single linebreaks, replace double with single
|
| 671 |
+
lines = obj.epilog.split("\n\n")
|
| 672 |
+
epilogue = "\n".join([x.replace("\n", " ").strip() for x in lines])
|
| 673 |
+
epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode)
|
| 674 |
+
console.print(Padding(Align(epilogue_text, pad=False), 1))
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def rich_format_error(self: click.ClickException) -> None:
|
| 678 |
+
"""Print richly formatted click errors.
|
| 679 |
+
|
| 680 |
+
Called by custom exception handler to print richly formatted click errors.
|
| 681 |
+
Mimics original click.ClickException.echo() function but with rich formatting.
|
| 682 |
+
"""
|
| 683 |
+
# Don't do anything when it's a NoArgsIsHelpError (without importing it, cf. #1278)
|
| 684 |
+
if self.__class__.__name__ == "NoArgsIsHelpError":
|
| 685 |
+
return
|
| 686 |
+
|
| 687 |
+
console = _get_rich_console(stderr=True)
|
| 688 |
+
ctx: click.Context | None = getattr(self, "ctx", None)
|
| 689 |
+
if ctx is not None:
|
| 690 |
+
console.print(ctx.get_usage())
|
| 691 |
+
|
| 692 |
+
if ctx is not None and ctx.command.get_help_option(ctx) is not None:
|
| 693 |
+
console.print(
|
| 694 |
+
RICH_HELP.format(
|
| 695 |
+
command_path=ctx.command_path, help_option=ctx.help_option_names[0]
|
| 696 |
+
),
|
| 697 |
+
style=STYLE_ERRORS_SUGGESTION,
|
| 698 |
+
)
|
| 699 |
+
|
| 700 |
+
console.print(
|
| 701 |
+
Panel(
|
| 702 |
+
highlighter(self.format_message()),
|
| 703 |
+
border_style=STYLE_ERRORS_PANEL_BORDER,
|
| 704 |
+
title=ERRORS_PANEL_TITLE,
|
| 705 |
+
title_align=ALIGN_ERRORS_PANEL,
|
| 706 |
+
)
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def rich_abort_error() -> None:
|
| 711 |
+
"""Print richly formatted abort error."""
|
| 712 |
+
console = _get_rich_console(stderr=True)
|
| 713 |
+
console.print(ABORTED_TEXT, style=STYLE_ABORTED)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def escape_before_html_export(input_text: str) -> str:
|
| 717 |
+
"""Ensure that the input string can be used for HTML export."""
|
| 718 |
+
return escape(input_text).strip()
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def rich_to_html(input_text: str) -> str:
|
| 722 |
+
"""Print the HTML version of a rich-formatted input string.
|
| 723 |
+
|
| 724 |
+
This function does not provide a full HTML page, but can be used to insert
|
| 725 |
+
HTML-formatted text spans into a markdown file.
|
| 726 |
+
"""
|
| 727 |
+
console = Console(record=True, highlight=False, file=io.StringIO())
|
| 728 |
+
|
| 729 |
+
console.print(input_text, overflow="ignore", crop=False)
|
| 730 |
+
|
| 731 |
+
return console.export_html(inline_styles=True, code_format="{code}").strip()
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def rich_render_text(text: str) -> str:
|
| 735 |
+
"""Remove rich tags and render a pure text representation"""
|
| 736 |
+
console = _get_rich_console()
|
| 737 |
+
return "".join(segment.text for segment in console.render(text)).rstrip("\n")
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def get_traceback(
|
| 741 |
+
exc: BaseException,
|
| 742 |
+
exception_config: DeveloperExceptionConfig,
|
| 743 |
+
internal_dir_names: list[str],
|
| 744 |
+
) -> Traceback:
|
| 745 |
+
rich_tb = Traceback.from_exception(
|
| 746 |
+
type(exc),
|
| 747 |
+
exc,
|
| 748 |
+
exc.__traceback__,
|
| 749 |
+
show_locals=exception_config.pretty_exceptions_show_locals,
|
| 750 |
+
suppress=internal_dir_names,
|
| 751 |
+
width=MAX_WIDTH,
|
| 752 |
+
)
|
| 753 |
+
return rich_tb
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/testing.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Mapping, Sequence
|
| 2 |
+
from typing import IO, Any
|
| 3 |
+
|
| 4 |
+
from click.testing import CliRunner as ClickCliRunner # noqa
|
| 5 |
+
from click.testing import Result
|
| 6 |
+
from typer.main import Typer
|
| 7 |
+
from typer.main import get_command as _get_command
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CliRunner(ClickCliRunner):
|
| 11 |
+
def invoke( # type: ignore
|
| 12 |
+
self,
|
| 13 |
+
app: Typer,
|
| 14 |
+
args: str | Sequence[str] | None = None,
|
| 15 |
+
input: bytes | str | IO[Any] | None = None,
|
| 16 |
+
env: Mapping[str, str | None] | None = None,
|
| 17 |
+
catch_exceptions: bool = True,
|
| 18 |
+
color: bool = False,
|
| 19 |
+
**extra: Any,
|
| 20 |
+
) -> Result:
|
| 21 |
+
use_cli = _get_command(app)
|
| 22 |
+
return super().invoke(
|
| 23 |
+
use_cli,
|
| 24 |
+
args=args,
|
| 25 |
+
input=input,
|
| 26 |
+
env=env,
|
| 27 |
+
catch_exceptions=catch_exceptions,
|
| 28 |
+
color=color,
|
| 29 |
+
**extra,
|
| 30 |
+
)
|
.cache/uv/archive-v0/2CYUca5dYUzMZnC9L8Unf/typer/utils.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from copy import copy
|
| 4 |
+
from typing import Any, cast
|
| 5 |
+
|
| 6 |
+
from ._typing import Annotated, get_args, get_origin, get_type_hints
|
| 7 |
+
from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _param_type_to_user_string(param_type: type[ParameterInfo]) -> str:
|
| 11 |
+
# Render a `ParameterInfo` subclass for use in error messages.
|
| 12 |
+
# User code doesn't call `*Info` directly, so errors should present the classes how
|
| 13 |
+
# they were (probably) defined in the user code.
|
| 14 |
+
if param_type is OptionInfo:
|
| 15 |
+
return "`Option`"
|
| 16 |
+
elif param_type is ArgumentInfo:
|
| 17 |
+
return "`Argument`"
|
| 18 |
+
# This line shouldn't be reachable during normal use.
|
| 19 |
+
return f"`{param_type.__name__}`" # pragma: no cover
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class AnnotatedParamWithDefaultValueError(Exception):
|
| 23 |
+
argument_name: str
|
| 24 |
+
param_type: type[ParameterInfo]
|
| 25 |
+
|
| 26 |
+
def __init__(self, argument_name: str, param_type: type[ParameterInfo]):
|
| 27 |
+
self.argument_name = argument_name
|
| 28 |
+
self.param_type = param_type
|
| 29 |
+
|
| 30 |
+
def __str__(self) -> str:
|
| 31 |
+
param_type_str = _param_type_to_user_string(self.param_type)
|
| 32 |
+
return (
|
| 33 |
+
f"{param_type_str} default value cannot be set in `Annotated`"
|
| 34 |
+
f" for {self.argument_name!r}. Set the default value with `=` instead."
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class MixedAnnotatedAndDefaultStyleError(Exception):
|
| 39 |
+
argument_name: str
|
| 40 |
+
annotated_param_type: type[ParameterInfo]
|
| 41 |
+
default_param_type: type[ParameterInfo]
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
argument_name: str,
|
| 46 |
+
annotated_param_type: type[ParameterInfo],
|
| 47 |
+
default_param_type: type[ParameterInfo],
|
| 48 |
+
):
|
| 49 |
+
self.argument_name = argument_name
|
| 50 |
+
self.annotated_param_type = annotated_param_type
|
| 51 |
+
self.default_param_type = default_param_type
|
| 52 |
+
|
| 53 |
+
def __str__(self) -> str:
|
| 54 |
+
annotated_param_type_str = _param_type_to_user_string(self.annotated_param_type)
|
| 55 |
+
default_param_type_str = _param_type_to_user_string(self.default_param_type)
|
| 56 |
+
msg = f"Cannot specify {annotated_param_type_str} in `Annotated` and"
|
| 57 |
+
if self.annotated_param_type is self.default_param_type:
|
| 58 |
+
msg += " default value"
|
| 59 |
+
else:
|
| 60 |
+
msg += f" {default_param_type_str} as a default value"
|
| 61 |
+
msg += f" together for {self.argument_name!r}"
|
| 62 |
+
return msg
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class MultipleTyperAnnotationsError(Exception):
|
| 66 |
+
argument_name: str
|
| 67 |
+
|
| 68 |
+
def __init__(self, argument_name: str):
|
| 69 |
+
self.argument_name = argument_name
|
| 70 |
+
|
| 71 |
+
def __str__(self) -> str:
|
| 72 |
+
return (
|
| 73 |
+
"Cannot specify multiple `Annotated` Typer arguments"
|
| 74 |
+
f" for {self.argument_name!r}"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class DefaultFactoryAndDefaultValueError(Exception):
|
| 79 |
+
argument_name: str
|
| 80 |
+
param_type: type[ParameterInfo]
|
| 81 |
+
|
| 82 |
+
def __init__(self, argument_name: str, param_type: type[ParameterInfo]):
|
| 83 |
+
self.argument_name = argument_name
|
| 84 |
+
self.param_type = param_type
|
| 85 |
+
|
| 86 |
+
def __str__(self) -> str:
|
| 87 |
+
param_type_str = _param_type_to_user_string(self.param_type)
|
| 88 |
+
return (
|
| 89 |
+
"Cannot specify `default_factory` and a default value together"
|
| 90 |
+
f" for {param_type_str}"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _split_annotation_from_typer_annotations(
|
| 95 |
+
base_annotation: type[Any],
|
| 96 |
+
) -> tuple[type[Any], list[ParameterInfo]]:
|
| 97 |
+
if get_origin(base_annotation) is not Annotated:
|
| 98 |
+
return base_annotation, []
|
| 99 |
+
base_annotation, *maybe_typer_annotations = get_args(base_annotation)
|
| 100 |
+
return base_annotation, [
|
| 101 |
+
annotation
|
| 102 |
+
for annotation in maybe_typer_annotations
|
| 103 |
+
if isinstance(annotation, ParameterInfo)
|
| 104 |
+
]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_params_from_function(func: Callable[..., Any]) -> dict[str, ParamMeta]:
|
| 108 |
+
signature = inspect.signature(func, eval_str=True)
|
| 109 |
+
type_hints = get_type_hints(func)
|
| 110 |
+
params = {}
|
| 111 |
+
for param in signature.parameters.values():
|
| 112 |
+
annotation, typer_annotations = _split_annotation_from_typer_annotations(
|
| 113 |
+
param.annotation,
|
| 114 |
+
)
|
| 115 |
+
if len(typer_annotations) > 1:
|
| 116 |
+
raise MultipleTyperAnnotationsError(param.name)
|
| 117 |
+
|
| 118 |
+
default = param.default
|
| 119 |
+
if typer_annotations:
|
| 120 |
+
# It's something like `my_param: Annotated[str, Argument()]`
|
| 121 |
+
[parameter_info] = typer_annotations
|
| 122 |
+
|
| 123 |
+
# Forbid `my_param: Annotated[str, Argument()] = Argument("...")`
|
| 124 |
+
if isinstance(param.default, ParameterInfo):
|
| 125 |
+
raise MixedAnnotatedAndDefaultStyleError(
|
| 126 |
+
argument_name=param.name,
|
| 127 |
+
annotated_param_type=type(parameter_info),
|
| 128 |
+
default_param_type=type(param.default),
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
parameter_info = copy(parameter_info)
|
| 132 |
+
|
| 133 |
+
# When used as a default, `Option` takes a default value and option names
|
| 134 |
+
# as positional arguments:
|
| 135 |
+
# `Option(some_value, "--some-argument", "-s")`
|
| 136 |
+
# When used in `Annotated` (ie, what this is handling), `Option` just takes
|
| 137 |
+
# option names as positional arguments:
|
| 138 |
+
# `Option("--some-argument", "-s")`
|
| 139 |
+
# In this case, the `default` attribute of `parameter_info` is actually
|
| 140 |
+
# meant to be the first item of `param_decls`.
|
| 141 |
+
if (
|
| 142 |
+
isinstance(parameter_info, OptionInfo)
|
| 143 |
+
and parameter_info.default is not ...
|
| 144 |
+
):
|
| 145 |
+
parameter_info.param_decls = (
|
| 146 |
+
cast(str, parameter_info.default),
|
| 147 |
+
*(parameter_info.param_decls or ()),
|
| 148 |
+
)
|
| 149 |
+
parameter_info.default = ...
|
| 150 |
+
|
| 151 |
+
# Forbid `my_param: Annotated[str, Argument('some-default')]`
|
| 152 |
+
if parameter_info.default is not ...:
|
| 153 |
+
raise AnnotatedParamWithDefaultValueError(
|
| 154 |
+
param_type=type(parameter_info),
|
| 155 |
+
argument_name=param.name,
|
| 156 |
+
)
|
| 157 |
+
if param.default is not param.empty:
|
| 158 |
+
# Put the parameter's default (set by `=`) into `parameter_info`, where
|
| 159 |
+
# typer can find it.
|
| 160 |
+
parameter_info.default = param.default
|
| 161 |
+
|
| 162 |
+
default = parameter_info
|
| 163 |
+
elif param.name in type_hints:
|
| 164 |
+
# Resolve forward references.
|
| 165 |
+
annotation = type_hints[param.name]
|
| 166 |
+
|
| 167 |
+
if isinstance(default, ParameterInfo):
|
| 168 |
+
parameter_info = copy(default)
|
| 169 |
+
# Click supports `default` as either
|
| 170 |
+
# - an actual value; or
|
| 171 |
+
# - a factory function (returning a default value.)
|
| 172 |
+
# The two are not interchangeable for static typing, so typer allows
|
| 173 |
+
# specifying `default_factory`. Move the `default_factory` into `default`
|
| 174 |
+
# so click can find it.
|
| 175 |
+
if parameter_info.default is ... and parameter_info.default_factory:
|
| 176 |
+
parameter_info.default = parameter_info.default_factory
|
| 177 |
+
elif parameter_info.default_factory:
|
| 178 |
+
raise DefaultFactoryAndDefaultValueError(
|
| 179 |
+
argument_name=param.name, param_type=type(parameter_info)
|
| 180 |
+
)
|
| 181 |
+
default = parameter_info
|
| 182 |
+
|
| 183 |
+
params[param.name] = ParamMeta(
|
| 184 |
+
name=param.name, default=default, annotation=annotation
|
| 185 |
+
)
|
| 186 |
+
return params
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def parse_boolean_env_var(env_var_value: str | None, default: bool) -> bool:
|
| 190 |
+
if env_var_value is None:
|
| 191 |
+
return default
|
| 192 |
+
value = env_var_value.lower()
|
| 193 |
+
if value in ("y", "yes", "t", "true", "on", "1"):
|
| 194 |
+
return True
|
| 195 |
+
if value in ("n", "no", "f", "false", "off", "0"):
|
| 196 |
+
return False
|
| 197 |
+
return default
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/METADATA
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: click
|
| 3 |
+
Version: 8.3.2
|
| 4 |
+
Summary: Composable command line interface toolkit
|
| 5 |
+
Maintainer-email: Pallets <contact@palletsprojects.com>
|
| 6 |
+
Requires-Python: >=3.10
|
| 7 |
+
Description-Content-Type: text/markdown
|
| 8 |
+
License-Expression: BSD-3-Clause
|
| 9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: Operating System :: OS Independent
|
| 12 |
+
Classifier: Programming Language :: Python
|
| 13 |
+
Classifier: Typing :: Typed
|
| 14 |
+
License-File: LICENSE.txt
|
| 15 |
+
Requires-Dist: colorama; platform_system == 'Windows'
|
| 16 |
+
Project-URL: Changes, https://click.palletsprojects.com/page/changes/
|
| 17 |
+
Project-URL: Chat, https://discord.gg/pallets
|
| 18 |
+
Project-URL: Documentation, https://click.palletsprojects.com/
|
| 19 |
+
Project-URL: Donate, https://palletsprojects.com/donate
|
| 20 |
+
Project-URL: Source, https://github.com/pallets/click/
|
| 21 |
+
|
| 22 |
+
<div align="center"><img src="https://raw.githubusercontent.com/pallets/click/refs/heads/stable/docs/_static/click-name.svg" alt="" height="150"></div>
|
| 23 |
+
|
| 24 |
+
# Click
|
| 25 |
+
|
| 26 |
+
Click is a Python package for creating beautiful command line interfaces
|
| 27 |
+
in a composable way with as little code as necessary. It's the "Command
|
| 28 |
+
Line Interface Creation Kit". It's highly configurable but comes with
|
| 29 |
+
sensible defaults out of the box.
|
| 30 |
+
|
| 31 |
+
It aims to make the process of writing command line tools quick and fun
|
| 32 |
+
while also preventing any frustration caused by the inability to
|
| 33 |
+
implement an intended CLI API.
|
| 34 |
+
|
| 35 |
+
Click in three points:
|
| 36 |
+
|
| 37 |
+
- Arbitrary nesting of commands
|
| 38 |
+
- Automatic help page generation
|
| 39 |
+
- Supports lazy loading of subcommands at runtime
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
## A Simple Example
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
import click
|
| 46 |
+
|
| 47 |
+
@click.command()
|
| 48 |
+
@click.option("--count", default=1, help="Number of greetings.")
|
| 49 |
+
@click.option("--name", prompt="Your name", help="The person to greet.")
|
| 50 |
+
def hello(count, name):
|
| 51 |
+
"""Simple program that greets NAME for a total of COUNT times."""
|
| 52 |
+
for _ in range(count):
|
| 53 |
+
click.echo(f"Hello, {name}!")
|
| 54 |
+
|
| 55 |
+
if __name__ == '__main__':
|
| 56 |
+
hello()
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
```
|
| 60 |
+
$ python hello.py --count=3
|
| 61 |
+
Your name: Click
|
| 62 |
+
Hello, Click!
|
| 63 |
+
Hello, Click!
|
| 64 |
+
Hello, Click!
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
## Donate
|
| 69 |
+
|
| 70 |
+
The Pallets organization develops and supports Click and other popular
|
| 71 |
+
packages. In order to grow the community of contributors and users, and
|
| 72 |
+
allow the maintainers to devote more time to the projects, [please
|
| 73 |
+
donate today][].
|
| 74 |
+
|
| 75 |
+
[please donate today]: https://palletsprojects.com/donate
|
| 76 |
+
|
| 77 |
+
## Contributing
|
| 78 |
+
|
| 79 |
+
See our [detailed contributing documentation][contrib] for many ways to
|
| 80 |
+
contribute, including reporting issues, requesting features, asking or answering
|
| 81 |
+
questions, and making PRs.
|
| 82 |
+
|
| 83 |
+
[contrib]: https://palletsprojects.com/contributing/
|
| 84 |
+
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/RECORD
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
click/__init__.py,sha256=6YyS1aeyknZ0LYweWozNZy0A9nZ_11wmYIhv3cbQrYo,4473
|
| 2 |
+
click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693
|
| 3 |
+
click/_termui_impl.py,sha256=rgCb3On8X5A4200rA5L6i13u5iapmFer7sru57Jy6zA,27093
|
| 4 |
+
click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400
|
| 5 |
+
click/_utils.py,sha256=kZwtTf5gMuCilJJceS2iTCvRvCY-0aN5rJq8gKw7p8g,943
|
| 6 |
+
click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465
|
| 7 |
+
click/core.py,sha256=7db9qr_wqXbQriDHCDc26OK0MsaLCSt4yrz14Kn7AEQ,132905
|
| 8 |
+
click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461
|
| 9 |
+
click/exceptions.py,sha256=8utf8w6V5hJXMnO_ic1FNrtbwuEn1NUu1aDwV8UqnG4,9954
|
| 10 |
+
click/formatting.py,sha256=RVfwwr0rwWNpgGr8NaHodPzkIr7_tUyVh_nDdanLMNc,9730
|
| 11 |
+
click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923
|
| 12 |
+
click/parser.py,sha256=Q31pH0FlQZEq-UXE_ABRzlygEfvxPTuZbWNh4xfXmzw,19010
|
| 13 |
+
click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 14 |
+
click/shell_completion.py,sha256=Cc4GQUFuWpfQBa9sF5qXeeYI7n3tI_1k6ZdSn4BZbT0,20994
|
| 15 |
+
click/termui.py,sha256=hqCEjNndU-nzW08nRAkBaVgfZp_FdCA9KxfIWlKYaMc,31037
|
| 16 |
+
click/testing.py,sha256=LjNfHqNctxc3GfRkLgifO6gnRetblh8yGXzjw4FPFCQ,18978
|
| 17 |
+
click/types.py,sha256=ek54BNSFwPKsqtfT7jsqcc4WHui8AIFVMKM4oVZIXhc,39927
|
| 18 |
+
click/utils.py,sha256=gCUoewdAhA-QLBUUHxrLh4uj6m7T1WjZZMNPvR0I7YA,20257
|
| 19 |
+
click-8.3.2.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475
|
| 20 |
+
click-8.3.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
|
| 21 |
+
click-8.3.2.dist-info/METADATA,sha256=yA3Hu5bMxtntTd4QrI8hTFAc58rHSPhDbP6bklbUQkA,2621
|
| 22 |
+
click-8.3.2.dist-info/RECORD,,
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: flit 3.12.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click-8.3.2.dist-info/licenses/LICENSE.txt
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright 2014 Pallets
|
| 2 |
+
|
| 3 |
+
Redistribution and use in source and binary forms, with or without
|
| 4 |
+
modification, are permitted provided that the following conditions are
|
| 5 |
+
met:
|
| 6 |
+
|
| 7 |
+
1. Redistributions of source code must retain the above copyright
|
| 8 |
+
notice, this list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
2. Redistributions in binary form must reproduce the above copyright
|
| 11 |
+
notice, this list of conditions and the following disclaimer in the
|
| 12 |
+
documentation and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
3. Neither the name of the copyright holder nor the names of its
|
| 15 |
+
contributors may be used to endorse or promote products derived from
|
| 16 |
+
this software without specific prior written permission.
|
| 17 |
+
|
| 18 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 19 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 20 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
| 21 |
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 22 |
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 23 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
| 24 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 25 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 26 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 27 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 28 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/__init__.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Click is a simple Python module inspired by the stdlib optparse to make
|
| 3 |
+
writing command line scripts fun. Unlike other modules, it's based
|
| 4 |
+
around a simple API that does not come with too much magic and is
|
| 5 |
+
composable.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from .core import Argument as Argument
|
| 11 |
+
from .core import Command as Command
|
| 12 |
+
from .core import CommandCollection as CommandCollection
|
| 13 |
+
from .core import Context as Context
|
| 14 |
+
from .core import Group as Group
|
| 15 |
+
from .core import Option as Option
|
| 16 |
+
from .core import Parameter as Parameter
|
| 17 |
+
from .decorators import argument as argument
|
| 18 |
+
from .decorators import command as command
|
| 19 |
+
from .decorators import confirmation_option as confirmation_option
|
| 20 |
+
from .decorators import group as group
|
| 21 |
+
from .decorators import help_option as help_option
|
| 22 |
+
from .decorators import make_pass_decorator as make_pass_decorator
|
| 23 |
+
from .decorators import option as option
|
| 24 |
+
from .decorators import pass_context as pass_context
|
| 25 |
+
from .decorators import pass_obj as pass_obj
|
| 26 |
+
from .decorators import password_option as password_option
|
| 27 |
+
from .decorators import version_option as version_option
|
| 28 |
+
from .exceptions import Abort as Abort
|
| 29 |
+
from .exceptions import BadArgumentUsage as BadArgumentUsage
|
| 30 |
+
from .exceptions import BadOptionUsage as BadOptionUsage
|
| 31 |
+
from .exceptions import BadParameter as BadParameter
|
| 32 |
+
from .exceptions import ClickException as ClickException
|
| 33 |
+
from .exceptions import FileError as FileError
|
| 34 |
+
from .exceptions import MissingParameter as MissingParameter
|
| 35 |
+
from .exceptions import NoSuchOption as NoSuchOption
|
| 36 |
+
from .exceptions import UsageError as UsageError
|
| 37 |
+
from .formatting import HelpFormatter as HelpFormatter
|
| 38 |
+
from .formatting import wrap_text as wrap_text
|
| 39 |
+
from .globals import get_current_context as get_current_context
|
| 40 |
+
from .termui import clear as clear
|
| 41 |
+
from .termui import confirm as confirm
|
| 42 |
+
from .termui import echo_via_pager as echo_via_pager
|
| 43 |
+
from .termui import edit as edit
|
| 44 |
+
from .termui import getchar as getchar
|
| 45 |
+
from .termui import launch as launch
|
| 46 |
+
from .termui import pause as pause
|
| 47 |
+
from .termui import progressbar as progressbar
|
| 48 |
+
from .termui import prompt as prompt
|
| 49 |
+
from .termui import secho as secho
|
| 50 |
+
from .termui import style as style
|
| 51 |
+
from .termui import unstyle as unstyle
|
| 52 |
+
from .types import BOOL as BOOL
|
| 53 |
+
from .types import Choice as Choice
|
| 54 |
+
from .types import DateTime as DateTime
|
| 55 |
+
from .types import File as File
|
| 56 |
+
from .types import FLOAT as FLOAT
|
| 57 |
+
from .types import FloatRange as FloatRange
|
| 58 |
+
from .types import INT as INT
|
| 59 |
+
from .types import IntRange as IntRange
|
| 60 |
+
from .types import ParamType as ParamType
|
| 61 |
+
from .types import Path as Path
|
| 62 |
+
from .types import STRING as STRING
|
| 63 |
+
from .types import Tuple as Tuple
|
| 64 |
+
from .types import UNPROCESSED as UNPROCESSED
|
| 65 |
+
from .types import UUID as UUID
|
| 66 |
+
from .utils import echo as echo
|
| 67 |
+
from .utils import format_filename as format_filename
|
| 68 |
+
from .utils import get_app_dir as get_app_dir
|
| 69 |
+
from .utils import get_binary_stream as get_binary_stream
|
| 70 |
+
from .utils import get_text_stream as get_text_stream
|
| 71 |
+
from .utils import open_file as open_file
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def __getattr__(name: str) -> object:
|
| 75 |
+
import warnings
|
| 76 |
+
|
| 77 |
+
if name == "BaseCommand":
|
| 78 |
+
from .core import _BaseCommand
|
| 79 |
+
|
| 80 |
+
warnings.warn(
|
| 81 |
+
"'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
|
| 82 |
+
" 'Command' instead.",
|
| 83 |
+
DeprecationWarning,
|
| 84 |
+
stacklevel=2,
|
| 85 |
+
)
|
| 86 |
+
return _BaseCommand
|
| 87 |
+
|
| 88 |
+
if name == "MultiCommand":
|
| 89 |
+
from .core import _MultiCommand
|
| 90 |
+
|
| 91 |
+
warnings.warn(
|
| 92 |
+
"'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
|
| 93 |
+
" 'Group' instead.",
|
| 94 |
+
DeprecationWarning,
|
| 95 |
+
stacklevel=2,
|
| 96 |
+
)
|
| 97 |
+
return _MultiCommand
|
| 98 |
+
|
| 99 |
+
if name == "OptionParser":
|
| 100 |
+
from .parser import _OptionParser
|
| 101 |
+
|
| 102 |
+
warnings.warn(
|
| 103 |
+
"'OptionParser' is deprecated and will be removed in Click 9.0. The"
|
| 104 |
+
" old parser is available in 'optparse'.",
|
| 105 |
+
DeprecationWarning,
|
| 106 |
+
stacklevel=2,
|
| 107 |
+
)
|
| 108 |
+
return _OptionParser
|
| 109 |
+
|
| 110 |
+
if name == "__version__":
|
| 111 |
+
import importlib.metadata
|
| 112 |
+
import warnings
|
| 113 |
+
|
| 114 |
+
warnings.warn(
|
| 115 |
+
"The '__version__' attribute is deprecated and will be removed in"
|
| 116 |
+
" Click 9.1. Use feature detection or"
|
| 117 |
+
" 'importlib.metadata.version(\"click\")' instead.",
|
| 118 |
+
DeprecationWarning,
|
| 119 |
+
stacklevel=2,
|
| 120 |
+
)
|
| 121 |
+
return importlib.metadata.version("click")
|
| 122 |
+
|
| 123 |
+
raise AttributeError(name)
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_compat.py
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import codecs
|
| 4 |
+
import collections.abc as cabc
|
| 5 |
+
import io
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
import typing as t
|
| 10 |
+
from types import TracebackType
|
| 11 |
+
from weakref import WeakKeyDictionary
|
| 12 |
+
|
| 13 |
+
CYGWIN = sys.platform.startswith("cygwin")
|
| 14 |
+
WIN = sys.platform.startswith("win")
|
| 15 |
+
auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None
|
| 16 |
+
_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _make_text_stream(
|
| 20 |
+
stream: t.BinaryIO,
|
| 21 |
+
encoding: str | None,
|
| 22 |
+
errors: str | None,
|
| 23 |
+
force_readable: bool = False,
|
| 24 |
+
force_writable: bool = False,
|
| 25 |
+
) -> t.TextIO:
|
| 26 |
+
if encoding is None:
|
| 27 |
+
encoding = get_best_encoding(stream)
|
| 28 |
+
if errors is None:
|
| 29 |
+
errors = "replace"
|
| 30 |
+
return _NonClosingTextIOWrapper(
|
| 31 |
+
stream,
|
| 32 |
+
encoding,
|
| 33 |
+
errors,
|
| 34 |
+
line_buffering=True,
|
| 35 |
+
force_readable=force_readable,
|
| 36 |
+
force_writable=force_writable,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def is_ascii_encoding(encoding: str) -> bool:
|
| 41 |
+
"""Checks if a given encoding is ascii."""
|
| 42 |
+
try:
|
| 43 |
+
return codecs.lookup(encoding).name == "ascii"
|
| 44 |
+
except LookupError:
|
| 45 |
+
return False
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_best_encoding(stream: t.IO[t.Any]) -> str:
|
| 49 |
+
"""Returns the default stream encoding if not found."""
|
| 50 |
+
rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()
|
| 51 |
+
if is_ascii_encoding(rv):
|
| 52 |
+
return "utf-8"
|
| 53 |
+
return rv
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class _NonClosingTextIOWrapper(io.TextIOWrapper):
|
| 57 |
+
def __init__(
|
| 58 |
+
self,
|
| 59 |
+
stream: t.BinaryIO,
|
| 60 |
+
encoding: str | None,
|
| 61 |
+
errors: str | None,
|
| 62 |
+
force_readable: bool = False,
|
| 63 |
+
force_writable: bool = False,
|
| 64 |
+
**extra: t.Any,
|
| 65 |
+
) -> None:
|
| 66 |
+
self._stream = stream = t.cast(
|
| 67 |
+
t.BinaryIO, _FixupStream(stream, force_readable, force_writable)
|
| 68 |
+
)
|
| 69 |
+
super().__init__(stream, encoding, errors, **extra)
|
| 70 |
+
|
| 71 |
+
def __del__(self) -> None:
|
| 72 |
+
try:
|
| 73 |
+
self.detach()
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
def isatty(self) -> bool:
|
| 78 |
+
# https://bitbucket.org/pypy/pypy/issue/1803
|
| 79 |
+
return self._stream.isatty()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class _FixupStream:
|
| 83 |
+
"""The new io interface needs more from streams than streams
|
| 84 |
+
traditionally implement. As such, this fix-up code is necessary in
|
| 85 |
+
some circumstances.
|
| 86 |
+
|
| 87 |
+
The forcing of readable and writable flags are there because some tools
|
| 88 |
+
put badly patched objects on sys (one such offender are certain version
|
| 89 |
+
of jupyter notebook).
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
def __init__(
|
| 93 |
+
self,
|
| 94 |
+
stream: t.BinaryIO,
|
| 95 |
+
force_readable: bool = False,
|
| 96 |
+
force_writable: bool = False,
|
| 97 |
+
):
|
| 98 |
+
self._stream = stream
|
| 99 |
+
self._force_readable = force_readable
|
| 100 |
+
self._force_writable = force_writable
|
| 101 |
+
|
| 102 |
+
def __getattr__(self, name: str) -> t.Any:
|
| 103 |
+
return getattr(self._stream, name)
|
| 104 |
+
|
| 105 |
+
def read1(self, size: int) -> bytes:
|
| 106 |
+
f = getattr(self._stream, "read1", None)
|
| 107 |
+
|
| 108 |
+
if f is not None:
|
| 109 |
+
return t.cast(bytes, f(size))
|
| 110 |
+
|
| 111 |
+
return self._stream.read(size)
|
| 112 |
+
|
| 113 |
+
def readable(self) -> bool:
|
| 114 |
+
if self._force_readable:
|
| 115 |
+
return True
|
| 116 |
+
x = getattr(self._stream, "readable", None)
|
| 117 |
+
if x is not None:
|
| 118 |
+
return t.cast(bool, x())
|
| 119 |
+
try:
|
| 120 |
+
self._stream.read(0)
|
| 121 |
+
except Exception:
|
| 122 |
+
return False
|
| 123 |
+
return True
|
| 124 |
+
|
| 125 |
+
def writable(self) -> bool:
|
| 126 |
+
if self._force_writable:
|
| 127 |
+
return True
|
| 128 |
+
x = getattr(self._stream, "writable", None)
|
| 129 |
+
if x is not None:
|
| 130 |
+
return t.cast(bool, x())
|
| 131 |
+
try:
|
| 132 |
+
self._stream.write(b"")
|
| 133 |
+
except Exception:
|
| 134 |
+
try:
|
| 135 |
+
self._stream.write(b"")
|
| 136 |
+
except Exception:
|
| 137 |
+
return False
|
| 138 |
+
return True
|
| 139 |
+
|
| 140 |
+
def seekable(self) -> bool:
|
| 141 |
+
x = getattr(self._stream, "seekable", None)
|
| 142 |
+
if x is not None:
|
| 143 |
+
return t.cast(bool, x())
|
| 144 |
+
try:
|
| 145 |
+
self._stream.seek(self._stream.tell())
|
| 146 |
+
except Exception:
|
| 147 |
+
return False
|
| 148 |
+
return True
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool:
|
| 152 |
+
try:
|
| 153 |
+
return isinstance(stream.read(0), bytes)
|
| 154 |
+
except Exception:
|
| 155 |
+
return default
|
| 156 |
+
# This happens in some cases where the stream was already
|
| 157 |
+
# closed. In this case, we assume the default.
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool:
|
| 161 |
+
try:
|
| 162 |
+
stream.write(b"")
|
| 163 |
+
except Exception:
|
| 164 |
+
try:
|
| 165 |
+
stream.write("")
|
| 166 |
+
return False
|
| 167 |
+
except Exception:
|
| 168 |
+
pass
|
| 169 |
+
return default
|
| 170 |
+
return True
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None:
|
| 174 |
+
# We need to figure out if the given stream is already binary.
|
| 175 |
+
# This can happen because the official docs recommend detaching
|
| 176 |
+
# the streams to get binary streams. Some code might do this, so
|
| 177 |
+
# we need to deal with this case explicitly.
|
| 178 |
+
if _is_binary_reader(stream, False):
|
| 179 |
+
return t.cast(t.BinaryIO, stream)
|
| 180 |
+
|
| 181 |
+
buf = getattr(stream, "buffer", None)
|
| 182 |
+
|
| 183 |
+
# Same situation here; this time we assume that the buffer is
|
| 184 |
+
# actually binary in case it's closed.
|
| 185 |
+
if buf is not None and _is_binary_reader(buf, True):
|
| 186 |
+
return t.cast(t.BinaryIO, buf)
|
| 187 |
+
|
| 188 |
+
return None
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None:
|
| 192 |
+
# We need to figure out if the given stream is already binary.
|
| 193 |
+
# This can happen because the official docs recommend detaching
|
| 194 |
+
# the streams to get binary streams. Some code might do this, so
|
| 195 |
+
# we need to deal with this case explicitly.
|
| 196 |
+
if _is_binary_writer(stream, False):
|
| 197 |
+
return t.cast(t.BinaryIO, stream)
|
| 198 |
+
|
| 199 |
+
buf = getattr(stream, "buffer", None)
|
| 200 |
+
|
| 201 |
+
# Same situation here; this time we assume that the buffer is
|
| 202 |
+
# actually binary in case it's closed.
|
| 203 |
+
if buf is not None and _is_binary_writer(buf, True):
|
| 204 |
+
return t.cast(t.BinaryIO, buf)
|
| 205 |
+
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _stream_is_misconfigured(stream: t.TextIO) -> bool:
|
| 210 |
+
"""A stream is misconfigured if its encoding is ASCII."""
|
| 211 |
+
# If the stream does not have an encoding set, we assume it's set
|
| 212 |
+
# to ASCII. This appears to happen in certain unittest
|
| 213 |
+
# environments. It's not quite clear what the correct behavior is
|
| 214 |
+
# but this at least will force Click to recover somehow.
|
| 215 |
+
return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool:
|
| 219 |
+
"""A stream attribute is compatible if it is equal to the
|
| 220 |
+
desired value or the desired value is unset and the attribute
|
| 221 |
+
has a value.
|
| 222 |
+
"""
|
| 223 |
+
stream_value = getattr(stream, attr, None)
|
| 224 |
+
return stream_value == value or (value is None and stream_value is not None)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _is_compatible_text_stream(
|
| 228 |
+
stream: t.TextIO, encoding: str | None, errors: str | None
|
| 229 |
+
) -> bool:
|
| 230 |
+
"""Check if a stream's encoding and errors attributes are
|
| 231 |
+
compatible with the desired values.
|
| 232 |
+
"""
|
| 233 |
+
return _is_compat_stream_attr(
|
| 234 |
+
stream, "encoding", encoding
|
| 235 |
+
) and _is_compat_stream_attr(stream, "errors", errors)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _force_correct_text_stream(
|
| 239 |
+
text_stream: t.IO[t.Any],
|
| 240 |
+
encoding: str | None,
|
| 241 |
+
errors: str | None,
|
| 242 |
+
is_binary: t.Callable[[t.IO[t.Any], bool], bool],
|
| 243 |
+
find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None],
|
| 244 |
+
force_readable: bool = False,
|
| 245 |
+
force_writable: bool = False,
|
| 246 |
+
) -> t.TextIO:
|
| 247 |
+
if is_binary(text_stream, False):
|
| 248 |
+
binary_reader = t.cast(t.BinaryIO, text_stream)
|
| 249 |
+
else:
|
| 250 |
+
text_stream = t.cast(t.TextIO, text_stream)
|
| 251 |
+
# If the stream looks compatible, and won't default to a
|
| 252 |
+
# misconfigured ascii encoding, return it as-is.
|
| 253 |
+
if _is_compatible_text_stream(text_stream, encoding, errors) and not (
|
| 254 |
+
encoding is None and _stream_is_misconfigured(text_stream)
|
| 255 |
+
):
|
| 256 |
+
return text_stream
|
| 257 |
+
|
| 258 |
+
# Otherwise, get the underlying binary reader.
|
| 259 |
+
possible_binary_reader = find_binary(text_stream)
|
| 260 |
+
|
| 261 |
+
# If that's not possible, silently use the original reader
|
| 262 |
+
# and get mojibake instead of exceptions.
|
| 263 |
+
if possible_binary_reader is None:
|
| 264 |
+
return text_stream
|
| 265 |
+
|
| 266 |
+
binary_reader = possible_binary_reader
|
| 267 |
+
|
| 268 |
+
# Default errors to replace instead of strict in order to get
|
| 269 |
+
# something that works.
|
| 270 |
+
if errors is None:
|
| 271 |
+
errors = "replace"
|
| 272 |
+
|
| 273 |
+
# Wrap the binary stream in a text stream with the correct
|
| 274 |
+
# encoding parameters.
|
| 275 |
+
return _make_text_stream(
|
| 276 |
+
binary_reader,
|
| 277 |
+
encoding,
|
| 278 |
+
errors,
|
| 279 |
+
force_readable=force_readable,
|
| 280 |
+
force_writable=force_writable,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _force_correct_text_reader(
|
| 285 |
+
text_reader: t.IO[t.Any],
|
| 286 |
+
encoding: str | None,
|
| 287 |
+
errors: str | None,
|
| 288 |
+
force_readable: bool = False,
|
| 289 |
+
) -> t.TextIO:
|
| 290 |
+
return _force_correct_text_stream(
|
| 291 |
+
text_reader,
|
| 292 |
+
encoding,
|
| 293 |
+
errors,
|
| 294 |
+
_is_binary_reader,
|
| 295 |
+
_find_binary_reader,
|
| 296 |
+
force_readable=force_readable,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _force_correct_text_writer(
|
| 301 |
+
text_writer: t.IO[t.Any],
|
| 302 |
+
encoding: str | None,
|
| 303 |
+
errors: str | None,
|
| 304 |
+
force_writable: bool = False,
|
| 305 |
+
) -> t.TextIO:
|
| 306 |
+
return _force_correct_text_stream(
|
| 307 |
+
text_writer,
|
| 308 |
+
encoding,
|
| 309 |
+
errors,
|
| 310 |
+
_is_binary_writer,
|
| 311 |
+
_find_binary_writer,
|
| 312 |
+
force_writable=force_writable,
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def get_binary_stdin() -> t.BinaryIO:
|
| 317 |
+
reader = _find_binary_reader(sys.stdin)
|
| 318 |
+
if reader is None:
|
| 319 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stdin.")
|
| 320 |
+
return reader
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def get_binary_stdout() -> t.BinaryIO:
|
| 324 |
+
writer = _find_binary_writer(sys.stdout)
|
| 325 |
+
if writer is None:
|
| 326 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stdout.")
|
| 327 |
+
return writer
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def get_binary_stderr() -> t.BinaryIO:
|
| 331 |
+
writer = _find_binary_writer(sys.stderr)
|
| 332 |
+
if writer is None:
|
| 333 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stderr.")
|
| 334 |
+
return writer
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
|
| 338 |
+
rv = _get_windows_console_stream(sys.stdin, encoding, errors)
|
| 339 |
+
if rv is not None:
|
| 340 |
+
return rv
|
| 341 |
+
return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
|
| 345 |
+
rv = _get_windows_console_stream(sys.stdout, encoding, errors)
|
| 346 |
+
if rv is not None:
|
| 347 |
+
return rv
|
| 348 |
+
return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
|
| 352 |
+
rv = _get_windows_console_stream(sys.stderr, encoding, errors)
|
| 353 |
+
if rv is not None:
|
| 354 |
+
return rv
|
| 355 |
+
return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def _wrap_io_open(
|
| 359 |
+
file: str | os.PathLike[str] | int,
|
| 360 |
+
mode: str,
|
| 361 |
+
encoding: str | None,
|
| 362 |
+
errors: str | None,
|
| 363 |
+
) -> t.IO[t.Any]:
|
| 364 |
+
"""Handles not passing ``encoding`` and ``errors`` in binary mode."""
|
| 365 |
+
if "b" in mode:
|
| 366 |
+
return open(file, mode)
|
| 367 |
+
|
| 368 |
+
return open(file, mode, encoding=encoding, errors=errors)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def open_stream(
|
| 372 |
+
filename: str | os.PathLike[str],
|
| 373 |
+
mode: str = "r",
|
| 374 |
+
encoding: str | None = None,
|
| 375 |
+
errors: str | None = "strict",
|
| 376 |
+
atomic: bool = False,
|
| 377 |
+
) -> tuple[t.IO[t.Any], bool]:
|
| 378 |
+
binary = "b" in mode
|
| 379 |
+
filename = os.fspath(filename)
|
| 380 |
+
|
| 381 |
+
# Standard streams first. These are simple because they ignore the
|
| 382 |
+
# atomic flag. Use fsdecode to handle Path("-").
|
| 383 |
+
if os.fsdecode(filename) == "-":
|
| 384 |
+
if any(m in mode for m in ["w", "a", "x"]):
|
| 385 |
+
if binary:
|
| 386 |
+
return get_binary_stdout(), False
|
| 387 |
+
return get_text_stdout(encoding=encoding, errors=errors), False
|
| 388 |
+
if binary:
|
| 389 |
+
return get_binary_stdin(), False
|
| 390 |
+
return get_text_stdin(encoding=encoding, errors=errors), False
|
| 391 |
+
|
| 392 |
+
# Non-atomic writes directly go out through the regular open functions.
|
| 393 |
+
if not atomic:
|
| 394 |
+
return _wrap_io_open(filename, mode, encoding, errors), True
|
| 395 |
+
|
| 396 |
+
# Some usability stuff for atomic writes
|
| 397 |
+
if "a" in mode:
|
| 398 |
+
raise ValueError(
|
| 399 |
+
"Appending to an existing file is not supported, because that"
|
| 400 |
+
" would involve an expensive `copy`-operation to a temporary"
|
| 401 |
+
" file. Open the file in normal `w`-mode and copy explicitly"
|
| 402 |
+
" if that's what you're after."
|
| 403 |
+
)
|
| 404 |
+
if "x" in mode:
|
| 405 |
+
raise ValueError("Use the `overwrite`-parameter instead.")
|
| 406 |
+
if "w" not in mode:
|
| 407 |
+
raise ValueError("Atomic writes only make sense with `w`-mode.")
|
| 408 |
+
|
| 409 |
+
# Atomic writes are more complicated. They work by opening a file
|
| 410 |
+
# as a proxy in the same folder and then using the fdopen
|
| 411 |
+
# functionality to wrap it in a Python file. Then we wrap it in an
|
| 412 |
+
# atomic file that moves the file over on close.
|
| 413 |
+
import errno
|
| 414 |
+
import random
|
| 415 |
+
|
| 416 |
+
try:
|
| 417 |
+
perm: int | None = os.stat(filename).st_mode
|
| 418 |
+
except OSError:
|
| 419 |
+
perm = None
|
| 420 |
+
|
| 421 |
+
flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
|
| 422 |
+
|
| 423 |
+
if binary:
|
| 424 |
+
flags |= getattr(os, "O_BINARY", 0)
|
| 425 |
+
|
| 426 |
+
while True:
|
| 427 |
+
tmp_filename = os.path.join(
|
| 428 |
+
os.path.dirname(filename),
|
| 429 |
+
f".__atomic-write{random.randrange(1 << 32):08x}",
|
| 430 |
+
)
|
| 431 |
+
try:
|
| 432 |
+
fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
|
| 433 |
+
break
|
| 434 |
+
except OSError as e:
|
| 435 |
+
if e.errno == errno.EEXIST or (
|
| 436 |
+
os.name == "nt"
|
| 437 |
+
and e.errno == errno.EACCES
|
| 438 |
+
and os.path.isdir(e.filename)
|
| 439 |
+
and os.access(e.filename, os.W_OK)
|
| 440 |
+
):
|
| 441 |
+
continue
|
| 442 |
+
raise
|
| 443 |
+
|
| 444 |
+
if perm is not None:
|
| 445 |
+
os.chmod(tmp_filename, perm) # in case perm includes bits in umask
|
| 446 |
+
|
| 447 |
+
f = _wrap_io_open(fd, mode, encoding, errors)
|
| 448 |
+
af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))
|
| 449 |
+
return t.cast(t.IO[t.Any], af), True
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
class _AtomicFile:
|
| 453 |
+
def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None:
|
| 454 |
+
self._f = f
|
| 455 |
+
self._tmp_filename = tmp_filename
|
| 456 |
+
self._real_filename = real_filename
|
| 457 |
+
self.closed = False
|
| 458 |
+
|
| 459 |
+
@property
|
| 460 |
+
def name(self) -> str:
|
| 461 |
+
return self._real_filename
|
| 462 |
+
|
| 463 |
+
def close(self, delete: bool = False) -> None:
|
| 464 |
+
if self.closed:
|
| 465 |
+
return
|
| 466 |
+
self._f.close()
|
| 467 |
+
os.replace(self._tmp_filename, self._real_filename)
|
| 468 |
+
self.closed = True
|
| 469 |
+
|
| 470 |
+
def __getattr__(self, name: str) -> t.Any:
|
| 471 |
+
return getattr(self._f, name)
|
| 472 |
+
|
| 473 |
+
def __enter__(self) -> _AtomicFile:
|
| 474 |
+
return self
|
| 475 |
+
|
| 476 |
+
def __exit__(
|
| 477 |
+
self,
|
| 478 |
+
exc_type: type[BaseException] | None,
|
| 479 |
+
exc_value: BaseException | None,
|
| 480 |
+
tb: TracebackType | None,
|
| 481 |
+
) -> None:
|
| 482 |
+
self.close(delete=exc_type is not None)
|
| 483 |
+
|
| 484 |
+
def __repr__(self) -> str:
|
| 485 |
+
return repr(self._f)
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def strip_ansi(value: str) -> str:
|
| 489 |
+
return _ansi_re.sub("", value)
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:
|
| 493 |
+
while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
|
| 494 |
+
stream = stream._stream
|
| 495 |
+
|
| 496 |
+
return stream.__class__.__module__.startswith("ipykernel.")
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def should_strip_ansi(
|
| 500 |
+
stream: t.IO[t.Any] | None = None, color: bool | None = None
|
| 501 |
+
) -> bool:
|
| 502 |
+
if color is None:
|
| 503 |
+
if stream is None:
|
| 504 |
+
stream = sys.stdin
|
| 505 |
+
return not isatty(stream) and not _is_jupyter_kernel_output(stream)
|
| 506 |
+
return not color
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# On Windows, wrap the output streams with colorama to support ANSI
|
| 510 |
+
# color codes.
|
| 511 |
+
# NOTE: double check is needed so mypy does not analyze this on Linux
|
| 512 |
+
if sys.platform.startswith("win") and WIN:
|
| 513 |
+
from ._winconsole import _get_windows_console_stream
|
| 514 |
+
|
| 515 |
+
def _get_argv_encoding() -> str:
|
| 516 |
+
import locale
|
| 517 |
+
|
| 518 |
+
return locale.getpreferredencoding()
|
| 519 |
+
|
| 520 |
+
_ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
|
| 521 |
+
|
| 522 |
+
def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO:
|
| 523 |
+
"""Support ANSI color and style codes on Windows by wrapping a
|
| 524 |
+
stream with colorama.
|
| 525 |
+
"""
|
| 526 |
+
try:
|
| 527 |
+
cached = _ansi_stream_wrappers.get(stream)
|
| 528 |
+
except Exception:
|
| 529 |
+
cached = None
|
| 530 |
+
|
| 531 |
+
if cached is not None:
|
| 532 |
+
return cached
|
| 533 |
+
|
| 534 |
+
import colorama
|
| 535 |
+
|
| 536 |
+
strip = should_strip_ansi(stream, color)
|
| 537 |
+
ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
|
| 538 |
+
rv = t.cast(t.TextIO, ansi_wrapper.stream)
|
| 539 |
+
_write = rv.write
|
| 540 |
+
|
| 541 |
+
def _safe_write(s: str) -> int:
|
| 542 |
+
try:
|
| 543 |
+
return _write(s)
|
| 544 |
+
except BaseException:
|
| 545 |
+
ansi_wrapper.reset_all()
|
| 546 |
+
raise
|
| 547 |
+
|
| 548 |
+
rv.write = _safe_write # type: ignore[method-assign]
|
| 549 |
+
|
| 550 |
+
try:
|
| 551 |
+
_ansi_stream_wrappers[stream] = rv
|
| 552 |
+
except Exception:
|
| 553 |
+
pass
|
| 554 |
+
|
| 555 |
+
return rv
|
| 556 |
+
|
| 557 |
+
else:
|
| 558 |
+
|
| 559 |
+
def _get_argv_encoding() -> str:
|
| 560 |
+
return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()
|
| 561 |
+
|
| 562 |
+
def _get_windows_console_stream(
|
| 563 |
+
f: t.TextIO, encoding: str | None, errors: str | None
|
| 564 |
+
) -> t.TextIO | None:
|
| 565 |
+
return None
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def term_len(x: str) -> int:
|
| 569 |
+
return len(strip_ansi(x))
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def isatty(stream: t.IO[t.Any]) -> bool:
|
| 573 |
+
try:
|
| 574 |
+
return stream.isatty()
|
| 575 |
+
except Exception:
|
| 576 |
+
return False
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def _make_cached_stream_func(
|
| 580 |
+
src_func: t.Callable[[], t.TextIO | None],
|
| 581 |
+
wrapper_func: t.Callable[[], t.TextIO],
|
| 582 |
+
) -> t.Callable[[], t.TextIO | None]:
|
| 583 |
+
cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
|
| 584 |
+
|
| 585 |
+
def func() -> t.TextIO | None:
|
| 586 |
+
stream = src_func()
|
| 587 |
+
|
| 588 |
+
if stream is None:
|
| 589 |
+
return None
|
| 590 |
+
|
| 591 |
+
try:
|
| 592 |
+
rv = cache.get(stream)
|
| 593 |
+
except Exception:
|
| 594 |
+
rv = None
|
| 595 |
+
if rv is not None:
|
| 596 |
+
return rv
|
| 597 |
+
rv = wrapper_func()
|
| 598 |
+
try:
|
| 599 |
+
cache[stream] = rv
|
| 600 |
+
except Exception:
|
| 601 |
+
pass
|
| 602 |
+
return rv
|
| 603 |
+
|
| 604 |
+
return func
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
|
| 608 |
+
_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
|
| 609 |
+
_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = {
|
| 613 |
+
"stdin": get_binary_stdin,
|
| 614 |
+
"stdout": get_binary_stdout,
|
| 615 |
+
"stderr": get_binary_stderr,
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = {
|
| 619 |
+
"stdin": get_text_stdin,
|
| 620 |
+
"stdout": get_text_stdout,
|
| 621 |
+
"stderr": get_text_stderr,
|
| 622 |
+
}
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_termui_impl.py
ADDED
|
@@ -0,0 +1,852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|
|
| 1 |
+
"""
|
| 2 |
+
This module contains implementations for the termui module. To keep the
|
| 3 |
+
import time of Click down, some infrequently used functionality is
|
| 4 |
+
placed in this module and only imported as needed.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import collections.abc as cabc
|
| 10 |
+
import contextlib
|
| 11 |
+
import math
|
| 12 |
+
import os
|
| 13 |
+
import shlex
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
import typing as t
|
| 17 |
+
from gettext import gettext as _
|
| 18 |
+
from io import StringIO
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from types import TracebackType
|
| 21 |
+
|
| 22 |
+
from ._compat import _default_text_stdout
|
| 23 |
+
from ._compat import CYGWIN
|
| 24 |
+
from ._compat import get_best_encoding
|
| 25 |
+
from ._compat import isatty
|
| 26 |
+
from ._compat import open_stream
|
| 27 |
+
from ._compat import strip_ansi
|
| 28 |
+
from ._compat import term_len
|
| 29 |
+
from ._compat import WIN
|
| 30 |
+
from .exceptions import ClickException
|
| 31 |
+
from .utils import echo
|
| 32 |
+
|
| 33 |
+
V = t.TypeVar("V")
|
| 34 |
+
|
| 35 |
+
if os.name == "nt":
|
| 36 |
+
BEFORE_BAR = "\r"
|
| 37 |
+
AFTER_BAR = "\n"
|
| 38 |
+
else:
|
| 39 |
+
BEFORE_BAR = "\r\033[?25l"
|
| 40 |
+
AFTER_BAR = "\033[?25h\n"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ProgressBar(t.Generic[V]):
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
iterable: cabc.Iterable[V] | None,
|
| 47 |
+
length: int | None = None,
|
| 48 |
+
fill_char: str = "#",
|
| 49 |
+
empty_char: str = " ",
|
| 50 |
+
bar_template: str = "%(bar)s",
|
| 51 |
+
info_sep: str = " ",
|
| 52 |
+
hidden: bool = False,
|
| 53 |
+
show_eta: bool = True,
|
| 54 |
+
show_percent: bool | None = None,
|
| 55 |
+
show_pos: bool = False,
|
| 56 |
+
item_show_func: t.Callable[[V | None], str | None] | None = None,
|
| 57 |
+
label: str | None = None,
|
| 58 |
+
file: t.TextIO | None = None,
|
| 59 |
+
color: bool | None = None,
|
| 60 |
+
update_min_steps: int = 1,
|
| 61 |
+
width: int = 30,
|
| 62 |
+
) -> None:
|
| 63 |
+
self.fill_char = fill_char
|
| 64 |
+
self.empty_char = empty_char
|
| 65 |
+
self.bar_template = bar_template
|
| 66 |
+
self.info_sep = info_sep
|
| 67 |
+
self.hidden = hidden
|
| 68 |
+
self.show_eta = show_eta
|
| 69 |
+
self.show_percent = show_percent
|
| 70 |
+
self.show_pos = show_pos
|
| 71 |
+
self.item_show_func = item_show_func
|
| 72 |
+
self.label: str = label or ""
|
| 73 |
+
|
| 74 |
+
if file is None:
|
| 75 |
+
file = _default_text_stdout()
|
| 76 |
+
|
| 77 |
+
# There are no standard streams attached to write to. For example,
|
| 78 |
+
# pythonw on Windows.
|
| 79 |
+
if file is None:
|
| 80 |
+
file = StringIO()
|
| 81 |
+
|
| 82 |
+
self.file = file
|
| 83 |
+
self.color = color
|
| 84 |
+
self.update_min_steps = update_min_steps
|
| 85 |
+
self._completed_intervals = 0
|
| 86 |
+
self.width: int = width
|
| 87 |
+
self.autowidth: bool = width == 0
|
| 88 |
+
|
| 89 |
+
if length is None:
|
| 90 |
+
from operator import length_hint
|
| 91 |
+
|
| 92 |
+
length = length_hint(iterable, -1)
|
| 93 |
+
|
| 94 |
+
if length == -1:
|
| 95 |
+
length = None
|
| 96 |
+
if iterable is None:
|
| 97 |
+
if length is None:
|
| 98 |
+
raise TypeError("iterable or length is required")
|
| 99 |
+
iterable = t.cast("cabc.Iterable[V]", range(length))
|
| 100 |
+
self.iter: cabc.Iterable[V] = iter(iterable)
|
| 101 |
+
self.length = length
|
| 102 |
+
self.pos: int = 0
|
| 103 |
+
self.avg: list[float] = []
|
| 104 |
+
self.last_eta: float
|
| 105 |
+
self.start: float
|
| 106 |
+
self.start = self.last_eta = time.time()
|
| 107 |
+
self.eta_known: bool = False
|
| 108 |
+
self.finished: bool = False
|
| 109 |
+
self.max_width: int | None = None
|
| 110 |
+
self.entered: bool = False
|
| 111 |
+
self.current_item: V | None = None
|
| 112 |
+
self._is_atty = isatty(self.file)
|
| 113 |
+
self._last_line: str | None = None
|
| 114 |
+
|
| 115 |
+
def __enter__(self) -> ProgressBar[V]:
|
| 116 |
+
self.entered = True
|
| 117 |
+
self.render_progress()
|
| 118 |
+
return self
|
| 119 |
+
|
| 120 |
+
def __exit__(
|
| 121 |
+
self,
|
| 122 |
+
exc_type: type[BaseException] | None,
|
| 123 |
+
exc_value: BaseException | None,
|
| 124 |
+
tb: TracebackType | None,
|
| 125 |
+
) -> None:
|
| 126 |
+
self.render_finish()
|
| 127 |
+
|
| 128 |
+
def __iter__(self) -> cabc.Iterator[V]:
|
| 129 |
+
if not self.entered:
|
| 130 |
+
raise RuntimeError("You need to use progress bars in a with block.")
|
| 131 |
+
self.render_progress()
|
| 132 |
+
return self.generator()
|
| 133 |
+
|
| 134 |
+
def __next__(self) -> V:
|
| 135 |
+
# Iteration is defined in terms of a generator function,
|
| 136 |
+
# returned by iter(self); use that to define next(). This works
|
| 137 |
+
# because `self.iter` is an iterable consumed by that generator,
|
| 138 |
+
# so it is re-entry safe. Calling `next(self.generator())`
|
| 139 |
+
# twice works and does "what you want".
|
| 140 |
+
return next(iter(self))
|
| 141 |
+
|
| 142 |
+
def render_finish(self) -> None:
|
| 143 |
+
if self.hidden or not self._is_atty:
|
| 144 |
+
return
|
| 145 |
+
self.file.write(AFTER_BAR)
|
| 146 |
+
self.file.flush()
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def pct(self) -> float:
|
| 150 |
+
if self.finished:
|
| 151 |
+
return 1.0
|
| 152 |
+
return min(self.pos / (float(self.length or 1) or 1), 1.0)
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def time_per_iteration(self) -> float:
|
| 156 |
+
if not self.avg:
|
| 157 |
+
return 0.0
|
| 158 |
+
return sum(self.avg) / float(len(self.avg))
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def eta(self) -> float:
|
| 162 |
+
if self.length is not None and not self.finished:
|
| 163 |
+
return self.time_per_iteration * (self.length - self.pos)
|
| 164 |
+
return 0.0
|
| 165 |
+
|
| 166 |
+
def format_eta(self) -> str:
|
| 167 |
+
if self.eta_known:
|
| 168 |
+
t = int(self.eta)
|
| 169 |
+
seconds = t % 60
|
| 170 |
+
t //= 60
|
| 171 |
+
minutes = t % 60
|
| 172 |
+
t //= 60
|
| 173 |
+
hours = t % 24
|
| 174 |
+
t //= 24
|
| 175 |
+
if t > 0:
|
| 176 |
+
return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"
|
| 177 |
+
else:
|
| 178 |
+
return f"{hours:02}:{minutes:02}:{seconds:02}"
|
| 179 |
+
return ""
|
| 180 |
+
|
| 181 |
+
def format_pos(self) -> str:
|
| 182 |
+
pos = str(self.pos)
|
| 183 |
+
if self.length is not None:
|
| 184 |
+
pos += f"/{self.length}"
|
| 185 |
+
return pos
|
| 186 |
+
|
| 187 |
+
def format_pct(self) -> str:
|
| 188 |
+
return f"{int(self.pct * 100): 4}%"[1:]
|
| 189 |
+
|
| 190 |
+
def format_bar(self) -> str:
|
| 191 |
+
if self.length is not None:
|
| 192 |
+
bar_length = int(self.pct * self.width)
|
| 193 |
+
bar = self.fill_char * bar_length
|
| 194 |
+
bar += self.empty_char * (self.width - bar_length)
|
| 195 |
+
elif self.finished:
|
| 196 |
+
bar = self.fill_char * self.width
|
| 197 |
+
else:
|
| 198 |
+
chars = list(self.empty_char * (self.width or 1))
|
| 199 |
+
if self.time_per_iteration != 0:
|
| 200 |
+
chars[
|
| 201 |
+
int(
|
| 202 |
+
(math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)
|
| 203 |
+
* self.width
|
| 204 |
+
)
|
| 205 |
+
] = self.fill_char
|
| 206 |
+
bar = "".join(chars)
|
| 207 |
+
return bar
|
| 208 |
+
|
| 209 |
+
def format_progress_line(self) -> str:
|
| 210 |
+
show_percent = self.show_percent
|
| 211 |
+
|
| 212 |
+
info_bits = []
|
| 213 |
+
if self.length is not None and show_percent is None:
|
| 214 |
+
show_percent = not self.show_pos
|
| 215 |
+
|
| 216 |
+
if self.show_pos:
|
| 217 |
+
info_bits.append(self.format_pos())
|
| 218 |
+
if show_percent:
|
| 219 |
+
info_bits.append(self.format_pct())
|
| 220 |
+
if self.show_eta and self.eta_known and not self.finished:
|
| 221 |
+
info_bits.append(self.format_eta())
|
| 222 |
+
if self.item_show_func is not None:
|
| 223 |
+
item_info = self.item_show_func(self.current_item)
|
| 224 |
+
if item_info is not None:
|
| 225 |
+
info_bits.append(item_info)
|
| 226 |
+
|
| 227 |
+
return (
|
| 228 |
+
self.bar_template
|
| 229 |
+
% {
|
| 230 |
+
"label": self.label,
|
| 231 |
+
"bar": self.format_bar(),
|
| 232 |
+
"info": self.info_sep.join(info_bits),
|
| 233 |
+
}
|
| 234 |
+
).rstrip()
|
| 235 |
+
|
| 236 |
+
def render_progress(self) -> None:
|
| 237 |
+
if self.hidden:
|
| 238 |
+
return
|
| 239 |
+
|
| 240 |
+
if not self._is_atty:
|
| 241 |
+
# Only output the label once if the output is not a TTY.
|
| 242 |
+
if self._last_line != self.label:
|
| 243 |
+
self._last_line = self.label
|
| 244 |
+
echo(self.label, file=self.file, color=self.color)
|
| 245 |
+
return
|
| 246 |
+
|
| 247 |
+
buf = []
|
| 248 |
+
# Update width in case the terminal has been resized
|
| 249 |
+
if self.autowidth:
|
| 250 |
+
import shutil
|
| 251 |
+
|
| 252 |
+
old_width = self.width
|
| 253 |
+
self.width = 0
|
| 254 |
+
clutter_length = term_len(self.format_progress_line())
|
| 255 |
+
new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
|
| 256 |
+
if new_width < old_width and self.max_width is not None:
|
| 257 |
+
buf.append(BEFORE_BAR)
|
| 258 |
+
buf.append(" " * self.max_width)
|
| 259 |
+
self.max_width = new_width
|
| 260 |
+
self.width = new_width
|
| 261 |
+
|
| 262 |
+
clear_width = self.width
|
| 263 |
+
if self.max_width is not None:
|
| 264 |
+
clear_width = self.max_width
|
| 265 |
+
|
| 266 |
+
buf.append(BEFORE_BAR)
|
| 267 |
+
line = self.format_progress_line()
|
| 268 |
+
line_len = term_len(line)
|
| 269 |
+
if self.max_width is None or self.max_width < line_len:
|
| 270 |
+
self.max_width = line_len
|
| 271 |
+
|
| 272 |
+
buf.append(line)
|
| 273 |
+
buf.append(" " * (clear_width - line_len))
|
| 274 |
+
line = "".join(buf)
|
| 275 |
+
# Render the line only if it changed.
|
| 276 |
+
|
| 277 |
+
if line != self._last_line:
|
| 278 |
+
self._last_line = line
|
| 279 |
+
echo(line, file=self.file, color=self.color, nl=False)
|
| 280 |
+
self.file.flush()
|
| 281 |
+
|
| 282 |
+
def make_step(self, n_steps: int) -> None:
|
| 283 |
+
self.pos += n_steps
|
| 284 |
+
if self.length is not None and self.pos >= self.length:
|
| 285 |
+
self.finished = True
|
| 286 |
+
|
| 287 |
+
if (time.time() - self.last_eta) < 1.0:
|
| 288 |
+
return
|
| 289 |
+
|
| 290 |
+
self.last_eta = time.time()
|
| 291 |
+
|
| 292 |
+
# self.avg is a rolling list of length <= 7 of steps where steps are
|
| 293 |
+
# defined as time elapsed divided by the total progress through
|
| 294 |
+
# self.length.
|
| 295 |
+
if self.pos:
|
| 296 |
+
step = (time.time() - self.start) / self.pos
|
| 297 |
+
else:
|
| 298 |
+
step = time.time() - self.start
|
| 299 |
+
|
| 300 |
+
self.avg = self.avg[-6:] + [step]
|
| 301 |
+
|
| 302 |
+
self.eta_known = self.length is not None
|
| 303 |
+
|
| 304 |
+
def update(self, n_steps: int, current_item: V | None = None) -> None:
|
| 305 |
+
"""Update the progress bar by advancing a specified number of
|
| 306 |
+
steps, and optionally set the ``current_item`` for this new
|
| 307 |
+
position.
|
| 308 |
+
|
| 309 |
+
:param n_steps: Number of steps to advance.
|
| 310 |
+
:param current_item: Optional item to set as ``current_item``
|
| 311 |
+
for the updated position.
|
| 312 |
+
|
| 313 |
+
.. versionchanged:: 8.0
|
| 314 |
+
Added the ``current_item`` optional parameter.
|
| 315 |
+
|
| 316 |
+
.. versionchanged:: 8.0
|
| 317 |
+
Only render when the number of steps meets the
|
| 318 |
+
``update_min_steps`` threshold.
|
| 319 |
+
"""
|
| 320 |
+
if current_item is not None:
|
| 321 |
+
self.current_item = current_item
|
| 322 |
+
|
| 323 |
+
self._completed_intervals += n_steps
|
| 324 |
+
|
| 325 |
+
if self._completed_intervals >= self.update_min_steps:
|
| 326 |
+
self.make_step(self._completed_intervals)
|
| 327 |
+
self.render_progress()
|
| 328 |
+
self._completed_intervals = 0
|
| 329 |
+
|
| 330 |
+
def finish(self) -> None:
|
| 331 |
+
self.eta_known = False
|
| 332 |
+
self.current_item = None
|
| 333 |
+
self.finished = True
|
| 334 |
+
|
| 335 |
+
def generator(self) -> cabc.Iterator[V]:
|
| 336 |
+
"""Return a generator which yields the items added to the bar
|
| 337 |
+
during construction, and updates the progress bar *after* the
|
| 338 |
+
yielded block returns.
|
| 339 |
+
"""
|
| 340 |
+
# WARNING: the iterator interface for `ProgressBar` relies on
|
| 341 |
+
# this and only works because this is a simple generator which
|
| 342 |
+
# doesn't create or manage additional state. If this function
|
| 343 |
+
# changes, the impact should be evaluated both against
|
| 344 |
+
# `iter(bar)` and `next(bar)`. `next()` in particular may call
|
| 345 |
+
# `self.generator()` repeatedly, and this must remain safe in
|
| 346 |
+
# order for that interface to work.
|
| 347 |
+
if not self.entered:
|
| 348 |
+
raise RuntimeError("You need to use progress bars in a with block.")
|
| 349 |
+
|
| 350 |
+
if not self._is_atty:
|
| 351 |
+
yield from self.iter
|
| 352 |
+
else:
|
| 353 |
+
for rv in self.iter:
|
| 354 |
+
self.current_item = rv
|
| 355 |
+
|
| 356 |
+
# This allows show_item_func to be updated before the
|
| 357 |
+
# item is processed. Only trigger at the beginning of
|
| 358 |
+
# the update interval.
|
| 359 |
+
if self._completed_intervals == 0:
|
| 360 |
+
self.render_progress()
|
| 361 |
+
|
| 362 |
+
yield rv
|
| 363 |
+
self.update(1)
|
| 364 |
+
|
| 365 |
+
self.finish()
|
| 366 |
+
self.render_progress()
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def pager(generator: cabc.Iterable[str], color: bool | None = None) -> None:
|
| 370 |
+
"""Decide what method to use for paging through text."""
|
| 371 |
+
stdout = _default_text_stdout()
|
| 372 |
+
|
| 373 |
+
# There are no standard streams attached to write to. For example,
|
| 374 |
+
# pythonw on Windows.
|
| 375 |
+
if stdout is None:
|
| 376 |
+
stdout = StringIO()
|
| 377 |
+
|
| 378 |
+
if not isatty(sys.stdin) or not isatty(stdout):
|
| 379 |
+
return _nullpager(stdout, generator, color)
|
| 380 |
+
|
| 381 |
+
# Split and normalize the pager command into parts.
|
| 382 |
+
pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""), posix=False)
|
| 383 |
+
if pager_cmd_parts:
|
| 384 |
+
if WIN:
|
| 385 |
+
if _tempfilepager(generator, pager_cmd_parts, color):
|
| 386 |
+
return
|
| 387 |
+
elif _pipepager(generator, pager_cmd_parts, color):
|
| 388 |
+
return
|
| 389 |
+
|
| 390 |
+
if os.environ.get("TERM") in ("dumb", "emacs"):
|
| 391 |
+
return _nullpager(stdout, generator, color)
|
| 392 |
+
if (WIN or sys.platform.startswith("os2")) and _tempfilepager(
|
| 393 |
+
generator, ["more"], color
|
| 394 |
+
):
|
| 395 |
+
return
|
| 396 |
+
if _pipepager(generator, ["less"], color):
|
| 397 |
+
return
|
| 398 |
+
|
| 399 |
+
import tempfile
|
| 400 |
+
|
| 401 |
+
fd, filename = tempfile.mkstemp()
|
| 402 |
+
os.close(fd)
|
| 403 |
+
try:
|
| 404 |
+
if _pipepager(generator, ["more"], color):
|
| 405 |
+
return
|
| 406 |
+
return _nullpager(stdout, generator, color)
|
| 407 |
+
finally:
|
| 408 |
+
os.unlink(filename)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _pipepager(
|
| 412 |
+
generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None
|
| 413 |
+
) -> bool:
|
| 414 |
+
"""Page through text by feeding it to another program. Invoking a
|
| 415 |
+
pager through this might support colors.
|
| 416 |
+
|
| 417 |
+
Returns `True` if the command was found, `False` otherwise and thus another
|
| 418 |
+
pager should be attempted.
|
| 419 |
+
"""
|
| 420 |
+
# Split the command into the invoked CLI and its parameters.
|
| 421 |
+
if not cmd_parts:
|
| 422 |
+
return False
|
| 423 |
+
|
| 424 |
+
import shutil
|
| 425 |
+
|
| 426 |
+
cmd = cmd_parts[0]
|
| 427 |
+
cmd_params = cmd_parts[1:]
|
| 428 |
+
|
| 429 |
+
cmd_filepath = shutil.which(cmd)
|
| 430 |
+
if not cmd_filepath:
|
| 431 |
+
return False
|
| 432 |
+
|
| 433 |
+
# Produces a normalized absolute path string.
|
| 434 |
+
# multi-call binaries such as busybox derive their identity from the symlink
|
| 435 |
+
# less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
|
| 436 |
+
cmd_path = Path(cmd_filepath).absolute()
|
| 437 |
+
cmd_name = cmd_path.name
|
| 438 |
+
|
| 439 |
+
import subprocess
|
| 440 |
+
|
| 441 |
+
# Make a local copy of the environment to not affect the global one.
|
| 442 |
+
env = dict(os.environ)
|
| 443 |
+
|
| 444 |
+
# If we're piping to less and the user hasn't decided on colors, we enable
|
| 445 |
+
# them by default we find the -R flag in the command line arguments.
|
| 446 |
+
if color is None and cmd_name == "less":
|
| 447 |
+
less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"
|
| 448 |
+
if not less_flags:
|
| 449 |
+
env["LESS"] = "-R"
|
| 450 |
+
color = True
|
| 451 |
+
elif "r" in less_flags or "R" in less_flags:
|
| 452 |
+
color = True
|
| 453 |
+
|
| 454 |
+
c = subprocess.Popen(
|
| 455 |
+
[str(cmd_path)] + cmd_params,
|
| 456 |
+
shell=False,
|
| 457 |
+
stdin=subprocess.PIPE,
|
| 458 |
+
env=env,
|
| 459 |
+
errors="replace",
|
| 460 |
+
text=True,
|
| 461 |
+
)
|
| 462 |
+
assert c.stdin is not None
|
| 463 |
+
try:
|
| 464 |
+
for text in generator:
|
| 465 |
+
if not color:
|
| 466 |
+
text = strip_ansi(text)
|
| 467 |
+
|
| 468 |
+
c.stdin.write(text)
|
| 469 |
+
except BrokenPipeError:
|
| 470 |
+
# In case the pager exited unexpectedly, ignore the broken pipe error.
|
| 471 |
+
pass
|
| 472 |
+
except Exception as e:
|
| 473 |
+
# In case there is an exception we want to close the pager immediately
|
| 474 |
+
# and let the caller handle it.
|
| 475 |
+
# Otherwise the pager will keep running, and the user may not notice
|
| 476 |
+
# the error message, or worse yet it may leave the terminal in a broken state.
|
| 477 |
+
c.terminate()
|
| 478 |
+
raise e
|
| 479 |
+
finally:
|
| 480 |
+
# We must close stdin and wait for the pager to exit before we continue
|
| 481 |
+
try:
|
| 482 |
+
c.stdin.close()
|
| 483 |
+
# Close implies flush, so it might throw a BrokenPipeError if the pager
|
| 484 |
+
# process exited already.
|
| 485 |
+
except BrokenPipeError:
|
| 486 |
+
pass
|
| 487 |
+
|
| 488 |
+
# Less doesn't respect ^C, but catches it for its own UI purposes (aborting
|
| 489 |
+
# search or other commands inside less).
|
| 490 |
+
#
|
| 491 |
+
# That means when the user hits ^C, the parent process (click) terminates,
|
| 492 |
+
# but less is still alive, paging the output and messing up the terminal.
|
| 493 |
+
#
|
| 494 |
+
# If the user wants to make the pager exit on ^C, they should set
|
| 495 |
+
# `LESS='-K'`. It's not our decision to make.
|
| 496 |
+
while True:
|
| 497 |
+
try:
|
| 498 |
+
c.wait()
|
| 499 |
+
except KeyboardInterrupt:
|
| 500 |
+
pass
|
| 501 |
+
else:
|
| 502 |
+
break
|
| 503 |
+
|
| 504 |
+
return True
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def _tempfilepager(
|
| 508 |
+
generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None
|
| 509 |
+
) -> bool:
|
| 510 |
+
"""Page through text by invoking a program on a temporary file.
|
| 511 |
+
|
| 512 |
+
Returns `True` if the command was found, `False` otherwise and thus another
|
| 513 |
+
pager should be attempted.
|
| 514 |
+
"""
|
| 515 |
+
# Split the command into the invoked CLI and its parameters.
|
| 516 |
+
if not cmd_parts:
|
| 517 |
+
return False
|
| 518 |
+
|
| 519 |
+
import shutil
|
| 520 |
+
|
| 521 |
+
cmd = cmd_parts[0]
|
| 522 |
+
|
| 523 |
+
cmd_filepath = shutil.which(cmd)
|
| 524 |
+
if not cmd_filepath:
|
| 525 |
+
return False
|
| 526 |
+
# Produces a normalized absolute path string.
|
| 527 |
+
# multi-call binaries such as busybox derive their identity from the symlink
|
| 528 |
+
# less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
|
| 529 |
+
cmd_path = Path(cmd_filepath).absolute()
|
| 530 |
+
|
| 531 |
+
import subprocess
|
| 532 |
+
import tempfile
|
| 533 |
+
|
| 534 |
+
fd, filename = tempfile.mkstemp()
|
| 535 |
+
# TODO: This never terminates if the passed generator never terminates.
|
| 536 |
+
text = "".join(generator)
|
| 537 |
+
if not color:
|
| 538 |
+
text = strip_ansi(text)
|
| 539 |
+
encoding = get_best_encoding(sys.stdout)
|
| 540 |
+
with open_stream(filename, "wb")[0] as f:
|
| 541 |
+
f.write(text.encode(encoding))
|
| 542 |
+
try:
|
| 543 |
+
subprocess.call([str(cmd_path), filename])
|
| 544 |
+
except OSError:
|
| 545 |
+
# Command not found
|
| 546 |
+
pass
|
| 547 |
+
finally:
|
| 548 |
+
os.close(fd)
|
| 549 |
+
os.unlink(filename)
|
| 550 |
+
|
| 551 |
+
return True
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def _nullpager(
|
| 555 |
+
stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None
|
| 556 |
+
) -> None:
|
| 557 |
+
"""Simply print unformatted text. This is the ultimate fallback."""
|
| 558 |
+
for text in generator:
|
| 559 |
+
if not color:
|
| 560 |
+
text = strip_ansi(text)
|
| 561 |
+
stream.write(text)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
class Editor:
|
| 565 |
+
def __init__(
|
| 566 |
+
self,
|
| 567 |
+
editor: str | None = None,
|
| 568 |
+
env: cabc.Mapping[str, str] | None = None,
|
| 569 |
+
require_save: bool = True,
|
| 570 |
+
extension: str = ".txt",
|
| 571 |
+
) -> None:
|
| 572 |
+
self.editor = editor
|
| 573 |
+
self.env = env
|
| 574 |
+
self.require_save = require_save
|
| 575 |
+
self.extension = extension
|
| 576 |
+
|
| 577 |
+
def get_editor(self) -> str:
|
| 578 |
+
if self.editor is not None:
|
| 579 |
+
return self.editor
|
| 580 |
+
for key in "VISUAL", "EDITOR":
|
| 581 |
+
rv = os.environ.get(key)
|
| 582 |
+
if rv:
|
| 583 |
+
return rv
|
| 584 |
+
if WIN:
|
| 585 |
+
return "notepad"
|
| 586 |
+
|
| 587 |
+
from shutil import which
|
| 588 |
+
|
| 589 |
+
for editor in "sensible-editor", "vim", "nano":
|
| 590 |
+
if which(editor) is not None:
|
| 591 |
+
return editor
|
| 592 |
+
return "vi"
|
| 593 |
+
|
| 594 |
+
def edit_files(self, filenames: cabc.Iterable[str]) -> None:
|
| 595 |
+
import subprocess
|
| 596 |
+
|
| 597 |
+
editor = self.get_editor()
|
| 598 |
+
environ: dict[str, str] | None = None
|
| 599 |
+
|
| 600 |
+
if self.env:
|
| 601 |
+
environ = os.environ.copy()
|
| 602 |
+
environ.update(self.env)
|
| 603 |
+
|
| 604 |
+
exc_filename = " ".join(f'"{filename}"' for filename in filenames)
|
| 605 |
+
|
| 606 |
+
try:
|
| 607 |
+
c = subprocess.Popen(
|
| 608 |
+
args=f"{editor} {exc_filename}", env=environ, shell=True
|
| 609 |
+
)
|
| 610 |
+
exit_code = c.wait()
|
| 611 |
+
if exit_code != 0:
|
| 612 |
+
raise ClickException(
|
| 613 |
+
_("{editor}: Editing failed").format(editor=editor)
|
| 614 |
+
)
|
| 615 |
+
except OSError as e:
|
| 616 |
+
raise ClickException(
|
| 617 |
+
_("{editor}: Editing failed: {e}").format(editor=editor, e=e)
|
| 618 |
+
) from e
|
| 619 |
+
|
| 620 |
+
@t.overload
|
| 621 |
+
def edit(self, text: bytes | bytearray) -> bytes | None: ...
|
| 622 |
+
|
| 623 |
+
# We cannot know whether or not the type expected is str or bytes when None
|
| 624 |
+
# is passed, so str is returned as that was what was done before.
|
| 625 |
+
@t.overload
|
| 626 |
+
def edit(self, text: str | None) -> str | None: ...
|
| 627 |
+
|
| 628 |
+
def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:
|
| 629 |
+
import tempfile
|
| 630 |
+
|
| 631 |
+
if text is None:
|
| 632 |
+
data: bytes | bytearray = b""
|
| 633 |
+
elif isinstance(text, (bytes, bytearray)):
|
| 634 |
+
data = text
|
| 635 |
+
else:
|
| 636 |
+
if text and not text.endswith("\n"):
|
| 637 |
+
text += "\n"
|
| 638 |
+
|
| 639 |
+
if WIN:
|
| 640 |
+
data = text.replace("\n", "\r\n").encode("utf-8-sig")
|
| 641 |
+
else:
|
| 642 |
+
data = text.encode("utf-8")
|
| 643 |
+
|
| 644 |
+
fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
|
| 645 |
+
f: t.BinaryIO
|
| 646 |
+
|
| 647 |
+
try:
|
| 648 |
+
with os.fdopen(fd, "wb") as f:
|
| 649 |
+
f.write(data)
|
| 650 |
+
|
| 651 |
+
# If the filesystem resolution is 1 second, like Mac OS
|
| 652 |
+
# 10.12 Extended, or 2 seconds, like FAT32, and the editor
|
| 653 |
+
# closes very fast, require_save can fail. Set the modified
|
| 654 |
+
# time to be 2 seconds in the past to work around this.
|
| 655 |
+
os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
|
| 656 |
+
# Depending on the resolution, the exact value might not be
|
| 657 |
+
# recorded, so get the new recorded value.
|
| 658 |
+
timestamp = os.path.getmtime(name)
|
| 659 |
+
|
| 660 |
+
self.edit_files((name,))
|
| 661 |
+
|
| 662 |
+
if self.require_save and os.path.getmtime(name) == timestamp:
|
| 663 |
+
return None
|
| 664 |
+
|
| 665 |
+
with open(name, "rb") as f:
|
| 666 |
+
rv = f.read()
|
| 667 |
+
|
| 668 |
+
if isinstance(text, (bytes, bytearray)):
|
| 669 |
+
return rv
|
| 670 |
+
|
| 671 |
+
return rv.decode("utf-8-sig").replace("\r\n", "\n")
|
| 672 |
+
finally:
|
| 673 |
+
os.unlink(name)
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
|
| 677 |
+
import subprocess
|
| 678 |
+
|
| 679 |
+
def _unquote_file(url: str) -> str:
|
| 680 |
+
from urllib.parse import unquote
|
| 681 |
+
|
| 682 |
+
if url.startswith("file://"):
|
| 683 |
+
url = unquote(url[7:])
|
| 684 |
+
|
| 685 |
+
return url
|
| 686 |
+
|
| 687 |
+
if sys.platform == "darwin":
|
| 688 |
+
args = ["open"]
|
| 689 |
+
if wait:
|
| 690 |
+
args.append("-W")
|
| 691 |
+
if locate:
|
| 692 |
+
args.append("-R")
|
| 693 |
+
args.append(_unquote_file(url))
|
| 694 |
+
null = open("/dev/null", "w")
|
| 695 |
+
try:
|
| 696 |
+
return subprocess.Popen(args, stderr=null).wait()
|
| 697 |
+
finally:
|
| 698 |
+
null.close()
|
| 699 |
+
elif WIN:
|
| 700 |
+
if locate:
|
| 701 |
+
url = _unquote_file(url)
|
| 702 |
+
args = ["explorer", f"/select,{url}"]
|
| 703 |
+
else:
|
| 704 |
+
args = ["start"]
|
| 705 |
+
if wait:
|
| 706 |
+
args.append("/WAIT")
|
| 707 |
+
args.append("")
|
| 708 |
+
args.append(url)
|
| 709 |
+
try:
|
| 710 |
+
return subprocess.call(args)
|
| 711 |
+
except OSError:
|
| 712 |
+
# Command not found
|
| 713 |
+
return 127
|
| 714 |
+
elif CYGWIN:
|
| 715 |
+
if locate:
|
| 716 |
+
url = _unquote_file(url)
|
| 717 |
+
args = ["cygstart", os.path.dirname(url)]
|
| 718 |
+
else:
|
| 719 |
+
args = ["cygstart"]
|
| 720 |
+
if wait:
|
| 721 |
+
args.append("-w")
|
| 722 |
+
args.append(url)
|
| 723 |
+
try:
|
| 724 |
+
return subprocess.call(args)
|
| 725 |
+
except OSError:
|
| 726 |
+
# Command not found
|
| 727 |
+
return 127
|
| 728 |
+
|
| 729 |
+
try:
|
| 730 |
+
if locate:
|
| 731 |
+
url = os.path.dirname(_unquote_file(url)) or "."
|
| 732 |
+
else:
|
| 733 |
+
url = _unquote_file(url)
|
| 734 |
+
c = subprocess.Popen(["xdg-open", url])
|
| 735 |
+
if wait:
|
| 736 |
+
return c.wait()
|
| 737 |
+
return 0
|
| 738 |
+
except OSError:
|
| 739 |
+
if url.startswith(("http://", "https://")) and not locate and not wait:
|
| 740 |
+
import webbrowser
|
| 741 |
+
|
| 742 |
+
webbrowser.open(url)
|
| 743 |
+
return 0
|
| 744 |
+
return 1
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def _translate_ch_to_exc(ch: str) -> None:
|
| 748 |
+
if ch == "\x03":
|
| 749 |
+
raise KeyboardInterrupt()
|
| 750 |
+
|
| 751 |
+
if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
|
| 752 |
+
raise EOFError()
|
| 753 |
+
|
| 754 |
+
if ch == "\x1a" and WIN: # Windows, Ctrl+Z
|
| 755 |
+
raise EOFError()
|
| 756 |
+
|
| 757 |
+
return None
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
if sys.platform == "win32":
|
| 761 |
+
import msvcrt
|
| 762 |
+
|
| 763 |
+
@contextlib.contextmanager
|
| 764 |
+
def raw_terminal() -> cabc.Iterator[int]:
|
| 765 |
+
yield -1
|
| 766 |
+
|
| 767 |
+
def getchar(echo: bool) -> str:
|
| 768 |
+
# The function `getch` will return a bytes object corresponding to
|
| 769 |
+
# the pressed character. Since Windows 10 build 1803, it will also
|
| 770 |
+
# return \x00 when called a second time after pressing a regular key.
|
| 771 |
+
#
|
| 772 |
+
# `getwch` does not share this probably-bugged behavior. Moreover, it
|
| 773 |
+
# returns a Unicode object by default, which is what we want.
|
| 774 |
+
#
|
| 775 |
+
# Either of these functions will return \x00 or \xe0 to indicate
|
| 776 |
+
# a special key, and you need to call the same function again to get
|
| 777 |
+
# the "rest" of the code. The fun part is that \u00e0 is
|
| 778 |
+
# "latin small letter a with grave", so if you type that on a French
|
| 779 |
+
# keyboard, you _also_ get a \xe0.
|
| 780 |
+
# E.g., consider the Up arrow. This returns \xe0 and then \x48. The
|
| 781 |
+
# resulting Unicode string reads as "a with grave" + "capital H".
|
| 782 |
+
# This is indistinguishable from when the user actually types
|
| 783 |
+
# "a with grave" and then "capital H".
|
| 784 |
+
#
|
| 785 |
+
# When \xe0 is returned, we assume it's part of a special-key sequence
|
| 786 |
+
# and call `getwch` again, but that means that when the user types
|
| 787 |
+
# the \u00e0 character, `getchar` doesn't return until a second
|
| 788 |
+
# character is typed.
|
| 789 |
+
# The alternative is returning immediately, but that would mess up
|
| 790 |
+
# cross-platform handling of arrow keys and others that start with
|
| 791 |
+
# \xe0. Another option is using `getch`, but then we can't reliably
|
| 792 |
+
# read non-ASCII characters, because return values of `getch` are
|
| 793 |
+
# limited to the current 8-bit codepage.
|
| 794 |
+
#
|
| 795 |
+
# Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
|
| 796 |
+
# is doing the right thing in more situations than with `getch`.
|
| 797 |
+
|
| 798 |
+
if echo:
|
| 799 |
+
func = t.cast(t.Callable[[], str], msvcrt.getwche)
|
| 800 |
+
else:
|
| 801 |
+
func = t.cast(t.Callable[[], str], msvcrt.getwch)
|
| 802 |
+
|
| 803 |
+
rv = func()
|
| 804 |
+
|
| 805 |
+
if rv in ("\x00", "\xe0"):
|
| 806 |
+
# \x00 and \xe0 are control characters that indicate special key,
|
| 807 |
+
# see above.
|
| 808 |
+
rv += func()
|
| 809 |
+
|
| 810 |
+
_translate_ch_to_exc(rv)
|
| 811 |
+
return rv
|
| 812 |
+
|
| 813 |
+
else:
|
| 814 |
+
import termios
|
| 815 |
+
import tty
|
| 816 |
+
|
| 817 |
+
@contextlib.contextmanager
|
| 818 |
+
def raw_terminal() -> cabc.Iterator[int]:
|
| 819 |
+
f: t.TextIO | None
|
| 820 |
+
fd: int
|
| 821 |
+
|
| 822 |
+
if not isatty(sys.stdin):
|
| 823 |
+
f = open("/dev/tty")
|
| 824 |
+
fd = f.fileno()
|
| 825 |
+
else:
|
| 826 |
+
fd = sys.stdin.fileno()
|
| 827 |
+
f = None
|
| 828 |
+
|
| 829 |
+
try:
|
| 830 |
+
old_settings = termios.tcgetattr(fd)
|
| 831 |
+
|
| 832 |
+
try:
|
| 833 |
+
tty.setraw(fd)
|
| 834 |
+
yield fd
|
| 835 |
+
finally:
|
| 836 |
+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
|
| 837 |
+
sys.stdout.flush()
|
| 838 |
+
|
| 839 |
+
if f is not None:
|
| 840 |
+
f.close()
|
| 841 |
+
except termios.error:
|
| 842 |
+
pass
|
| 843 |
+
|
| 844 |
+
def getchar(echo: bool) -> str:
|
| 845 |
+
with raw_terminal() as fd:
|
| 846 |
+
ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
|
| 847 |
+
|
| 848 |
+
if echo and isatty(sys.stdout):
|
| 849 |
+
sys.stdout.write(ch)
|
| 850 |
+
|
| 851 |
+
_translate_ch_to_exc(ch)
|
| 852 |
+
return ch
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_textwrap.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections.abc as cabc
|
| 4 |
+
import textwrap
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class TextWrapper(textwrap.TextWrapper):
|
| 9 |
+
def _handle_long_word(
|
| 10 |
+
self,
|
| 11 |
+
reversed_chunks: list[str],
|
| 12 |
+
cur_line: list[str],
|
| 13 |
+
cur_len: int,
|
| 14 |
+
width: int,
|
| 15 |
+
) -> None:
|
| 16 |
+
space_left = max(width - cur_len, 1)
|
| 17 |
+
|
| 18 |
+
if self.break_long_words:
|
| 19 |
+
last = reversed_chunks[-1]
|
| 20 |
+
cut = last[:space_left]
|
| 21 |
+
res = last[space_left:]
|
| 22 |
+
cur_line.append(cut)
|
| 23 |
+
reversed_chunks[-1] = res
|
| 24 |
+
elif not cur_line:
|
| 25 |
+
cur_line.append(reversed_chunks.pop())
|
| 26 |
+
|
| 27 |
+
@contextmanager
|
| 28 |
+
def extra_indent(self, indent: str) -> cabc.Iterator[None]:
|
| 29 |
+
old_initial_indent = self.initial_indent
|
| 30 |
+
old_subsequent_indent = self.subsequent_indent
|
| 31 |
+
self.initial_indent += indent
|
| 32 |
+
self.subsequent_indent += indent
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
yield
|
| 36 |
+
finally:
|
| 37 |
+
self.initial_indent = old_initial_indent
|
| 38 |
+
self.subsequent_indent = old_subsequent_indent
|
| 39 |
+
|
| 40 |
+
def indent_only(self, text: str) -> str:
|
| 41 |
+
rv = []
|
| 42 |
+
|
| 43 |
+
for idx, line in enumerate(text.splitlines()):
|
| 44 |
+
indent = self.initial_indent
|
| 45 |
+
|
| 46 |
+
if idx > 0:
|
| 47 |
+
indent = self.subsequent_indent
|
| 48 |
+
|
| 49 |
+
rv.append(f"{indent}{line}")
|
| 50 |
+
|
| 51 |
+
return "\n".join(rv)
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_utils.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import enum
|
| 4 |
+
import typing as t
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Sentinel(enum.Enum):
|
| 8 |
+
"""Enum used to define sentinel values.
|
| 9 |
+
|
| 10 |
+
.. seealso::
|
| 11 |
+
|
| 12 |
+
`PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
UNSET = object()
|
| 16 |
+
FLAG_NEEDS_VALUE = object()
|
| 17 |
+
|
| 18 |
+
def __repr__(self) -> str:
|
| 19 |
+
return f"{self.__class__.__name__}.{self.name}"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
UNSET = Sentinel.UNSET
|
| 23 |
+
"""Sentinel used to indicate that a value is not set."""
|
| 24 |
+
|
| 25 |
+
FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE
|
| 26 |
+
"""Sentinel used to indicate an option was passed as a flag without a
|
| 27 |
+
value but is not a flag option.
|
| 28 |
+
|
| 29 |
+
``Option.consume_value`` uses this to prompt or use the ``flag_value``.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]
|
| 33 |
+
"""Type hint for the :data:`UNSET` sentinel value."""
|
| 34 |
+
|
| 35 |
+
T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type]
|
| 36 |
+
"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/_winconsole.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ellent work by Adam Bartoš who
|
| 2 |
+
# provided a lot of what went into the implementation here in
|
| 3 |
+
# the discussion to issue1602 in the Python bug tracker.
|
| 4 |
+
#
|
| 5 |
+
# There are some general differences in regards to how this works
|
| 6 |
+
# compared to the original patches as we do not need to patch
|
| 7 |
+
# the entire interpreter but just work in our little world of
|
| 8 |
+
# echo and prompt.
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import collections.abc as cabc
|
| 12 |
+
import io
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
import typing as t
|
| 16 |
+
from ctypes import Array
|
| 17 |
+
from ctypes import byref
|
| 18 |
+
from ctypes import c_char
|
| 19 |
+
from ctypes import c_char_p
|
| 20 |
+
from ctypes import c_int
|
| 21 |
+
from ctypes import c_ssize_t
|
| 22 |
+
from ctypes import c_ulong
|
| 23 |
+
from ctypes import c_void_p
|
| 24 |
+
from ctypes import POINTER
|
| 25 |
+
from ctypes import py_object
|
| 26 |
+
from ctypes import Structure
|
| 27 |
+
from ctypes.wintypes import DWORD
|
| 28 |
+
from ctypes.wintypes import HANDLE
|
| 29 |
+
from ctypes.wintypes import LPCWSTR
|
| 30 |
+
from ctypes.wintypes import LPWSTR
|
| 31 |
+
|
| 32 |
+
from ._compat import _NonClosingTextIOWrapper
|
| 33 |
+
|
| 34 |
+
assert sys.platform == "win32"
|
| 35 |
+
import msvcrt # noqa: E402
|
| 36 |
+
from ctypes import windll # noqa: E402
|
| 37 |
+
from ctypes import WINFUNCTYPE # noqa: E402
|
| 38 |
+
|
| 39 |
+
c_ssize_p = POINTER(c_ssize_t)
|
| 40 |
+
|
| 41 |
+
kernel32 = windll.kernel32
|
| 42 |
+
GetStdHandle = kernel32.GetStdHandle
|
| 43 |
+
ReadConsoleW = kernel32.ReadConsoleW
|
| 44 |
+
WriteConsoleW = kernel32.WriteConsoleW
|
| 45 |
+
GetConsoleMode = kernel32.GetConsoleMode
|
| 46 |
+
GetLastError = kernel32.GetLastError
|
| 47 |
+
GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
|
| 48 |
+
CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
|
| 49 |
+
("CommandLineToArgvW", windll.shell32)
|
| 50 |
+
)
|
| 51 |
+
LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))
|
| 52 |
+
|
| 53 |
+
STDIN_HANDLE = GetStdHandle(-10)
|
| 54 |
+
STDOUT_HANDLE = GetStdHandle(-11)
|
| 55 |
+
STDERR_HANDLE = GetStdHandle(-12)
|
| 56 |
+
|
| 57 |
+
PyBUF_SIMPLE = 0
|
| 58 |
+
PyBUF_WRITABLE = 1
|
| 59 |
+
|
| 60 |
+
ERROR_SUCCESS = 0
|
| 61 |
+
ERROR_NOT_ENOUGH_MEMORY = 8
|
| 62 |
+
ERROR_OPERATION_ABORTED = 995
|
| 63 |
+
|
| 64 |
+
STDIN_FILENO = 0
|
| 65 |
+
STDOUT_FILENO = 1
|
| 66 |
+
STDERR_FILENO = 2
|
| 67 |
+
|
| 68 |
+
EOF = b"\x1a"
|
| 69 |
+
MAX_BYTES_WRITTEN = 32767
|
| 70 |
+
|
| 71 |
+
if t.TYPE_CHECKING:
|
| 72 |
+
try:
|
| 73 |
+
# Using `typing_extensions.Buffer` instead of `collections.abc`
|
| 74 |
+
# on Windows for some reason does not have `Sized` implemented.
|
| 75 |
+
from collections.abc import Buffer # type: ignore
|
| 76 |
+
except ImportError:
|
| 77 |
+
from typing_extensions import Buffer
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
from ctypes import pythonapi
|
| 81 |
+
except ImportError:
|
| 82 |
+
# On PyPy we cannot get buffers so our ability to operate here is
|
| 83 |
+
# severely limited.
|
| 84 |
+
get_buffer = None
|
| 85 |
+
else:
|
| 86 |
+
|
| 87 |
+
class Py_buffer(Structure):
|
| 88 |
+
_fields_ = [ # noqa: RUF012
|
| 89 |
+
("buf", c_void_p),
|
| 90 |
+
("obj", py_object),
|
| 91 |
+
("len", c_ssize_t),
|
| 92 |
+
("itemsize", c_ssize_t),
|
| 93 |
+
("readonly", c_int),
|
| 94 |
+
("ndim", c_int),
|
| 95 |
+
("format", c_char_p),
|
| 96 |
+
("shape", c_ssize_p),
|
| 97 |
+
("strides", c_ssize_p),
|
| 98 |
+
("suboffsets", c_ssize_p),
|
| 99 |
+
("internal", c_void_p),
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
|
| 103 |
+
PyBuffer_Release = pythonapi.PyBuffer_Release
|
| 104 |
+
|
| 105 |
+
def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]:
|
| 106 |
+
buf = Py_buffer()
|
| 107 |
+
flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE
|
| 108 |
+
PyObject_GetBuffer(py_object(obj), byref(buf), flags)
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
buffer_type = c_char * buf.len
|
| 112 |
+
out: Array[c_char] = buffer_type.from_address(buf.buf)
|
| 113 |
+
return out
|
| 114 |
+
finally:
|
| 115 |
+
PyBuffer_Release(byref(buf))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class _WindowsConsoleRawIOBase(io.RawIOBase):
|
| 119 |
+
def __init__(self, handle: int | None) -> None:
|
| 120 |
+
self.handle = handle
|
| 121 |
+
|
| 122 |
+
def isatty(self) -> t.Literal[True]:
|
| 123 |
+
super().isatty()
|
| 124 |
+
return True
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
|
| 128 |
+
def readable(self) -> t.Literal[True]:
|
| 129 |
+
return True
|
| 130 |
+
|
| 131 |
+
def readinto(self, b: Buffer) -> int:
|
| 132 |
+
bytes_to_be_read = len(b)
|
| 133 |
+
if not bytes_to_be_read:
|
| 134 |
+
return 0
|
| 135 |
+
elif bytes_to_be_read % 2:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
"cannot read odd number of bytes from UTF-16-LE encoded console"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
buffer = get_buffer(b, writable=True)
|
| 141 |
+
code_units_to_be_read = bytes_to_be_read // 2
|
| 142 |
+
code_units_read = c_ulong()
|
| 143 |
+
|
| 144 |
+
rv = ReadConsoleW(
|
| 145 |
+
HANDLE(self.handle),
|
| 146 |
+
buffer,
|
| 147 |
+
code_units_to_be_read,
|
| 148 |
+
byref(code_units_read),
|
| 149 |
+
None,
|
| 150 |
+
)
|
| 151 |
+
if GetLastError() == ERROR_OPERATION_ABORTED:
|
| 152 |
+
# wait for KeyboardInterrupt
|
| 153 |
+
time.sleep(0.1)
|
| 154 |
+
if not rv:
|
| 155 |
+
raise OSError(f"Windows error: {GetLastError()}")
|
| 156 |
+
|
| 157 |
+
if buffer[0] == EOF:
|
| 158 |
+
return 0
|
| 159 |
+
return 2 * code_units_read.value
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
|
| 163 |
+
def writable(self) -> t.Literal[True]:
|
| 164 |
+
return True
|
| 165 |
+
|
| 166 |
+
@staticmethod
|
| 167 |
+
def _get_error_message(errno: int) -> str:
|
| 168 |
+
if errno == ERROR_SUCCESS:
|
| 169 |
+
return "ERROR_SUCCESS"
|
| 170 |
+
elif errno == ERROR_NOT_ENOUGH_MEMORY:
|
| 171 |
+
return "ERROR_NOT_ENOUGH_MEMORY"
|
| 172 |
+
return f"Windows error {errno}"
|
| 173 |
+
|
| 174 |
+
def write(self, b: Buffer) -> int:
|
| 175 |
+
bytes_to_be_written = len(b)
|
| 176 |
+
buf = get_buffer(b)
|
| 177 |
+
code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2
|
| 178 |
+
code_units_written = c_ulong()
|
| 179 |
+
|
| 180 |
+
WriteConsoleW(
|
| 181 |
+
HANDLE(self.handle),
|
| 182 |
+
buf,
|
| 183 |
+
code_units_to_be_written,
|
| 184 |
+
byref(code_units_written),
|
| 185 |
+
None,
|
| 186 |
+
)
|
| 187 |
+
bytes_written = 2 * code_units_written.value
|
| 188 |
+
|
| 189 |
+
if bytes_written == 0 and bytes_to_be_written > 0:
|
| 190 |
+
raise OSError(self._get_error_message(GetLastError()))
|
| 191 |
+
return bytes_written
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class ConsoleStream:
|
| 195 |
+
def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:
|
| 196 |
+
self._text_stream = text_stream
|
| 197 |
+
self.buffer = byte_stream
|
| 198 |
+
|
| 199 |
+
@property
|
| 200 |
+
def name(self) -> str:
|
| 201 |
+
return self.buffer.name
|
| 202 |
+
|
| 203 |
+
def write(self, x: t.AnyStr) -> int:
|
| 204 |
+
if isinstance(x, str):
|
| 205 |
+
return self._text_stream.write(x)
|
| 206 |
+
try:
|
| 207 |
+
self.flush()
|
| 208 |
+
except Exception:
|
| 209 |
+
pass
|
| 210 |
+
return self.buffer.write(x)
|
| 211 |
+
|
| 212 |
+
def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None:
|
| 213 |
+
for line in lines:
|
| 214 |
+
self.write(line)
|
| 215 |
+
|
| 216 |
+
def __getattr__(self, name: str) -> t.Any:
|
| 217 |
+
return getattr(self._text_stream, name)
|
| 218 |
+
|
| 219 |
+
def isatty(self) -> bool:
|
| 220 |
+
return self.buffer.isatty()
|
| 221 |
+
|
| 222 |
+
def __repr__(self) -> str:
|
| 223 |
+
return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:
|
| 227 |
+
text_stream = _NonClosingTextIOWrapper(
|
| 228 |
+
io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
|
| 229 |
+
"utf-16-le",
|
| 230 |
+
"strict",
|
| 231 |
+
line_buffering=True,
|
| 232 |
+
)
|
| 233 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:
|
| 237 |
+
text_stream = _NonClosingTextIOWrapper(
|
| 238 |
+
io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
|
| 239 |
+
"utf-16-le",
|
| 240 |
+
"strict",
|
| 241 |
+
line_buffering=True,
|
| 242 |
+
)
|
| 243 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:
|
| 247 |
+
text_stream = _NonClosingTextIOWrapper(
|
| 248 |
+
io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
|
| 249 |
+
"utf-16-le",
|
| 250 |
+
"strict",
|
| 251 |
+
line_buffering=True,
|
| 252 |
+
)
|
| 253 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
_stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {
|
| 257 |
+
0: _get_text_stdin,
|
| 258 |
+
1: _get_text_stdout,
|
| 259 |
+
2: _get_text_stderr,
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _is_console(f: t.TextIO) -> bool:
|
| 264 |
+
if not hasattr(f, "fileno"):
|
| 265 |
+
return False
|
| 266 |
+
|
| 267 |
+
try:
|
| 268 |
+
fileno = f.fileno()
|
| 269 |
+
except (OSError, io.UnsupportedOperation):
|
| 270 |
+
return False
|
| 271 |
+
|
| 272 |
+
handle = msvcrt.get_osfhandle(fileno)
|
| 273 |
+
return bool(GetConsoleMode(handle, byref(DWORD())))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _get_windows_console_stream(
|
| 277 |
+
f: t.TextIO, encoding: str | None, errors: str | None
|
| 278 |
+
) -> t.TextIO | None:
|
| 279 |
+
if (
|
| 280 |
+
get_buffer is None
|
| 281 |
+
or encoding not in {"utf-16-le", None}
|
| 282 |
+
or errors not in {"strict", None}
|
| 283 |
+
or not _is_console(f)
|
| 284 |
+
):
|
| 285 |
+
return None
|
| 286 |
+
|
| 287 |
+
func = _stream_factories.get(f.fileno())
|
| 288 |
+
if func is None:
|
| 289 |
+
return None
|
| 290 |
+
|
| 291 |
+
b = getattr(f, "buffer", None)
|
| 292 |
+
|
| 293 |
+
if b is None:
|
| 294 |
+
return None
|
| 295 |
+
|
| 296 |
+
return func(b)
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/core.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/decorators.py
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
import typing as t
|
| 5 |
+
from functools import update_wrapper
|
| 6 |
+
from gettext import gettext as _
|
| 7 |
+
|
| 8 |
+
from .core import Argument
|
| 9 |
+
from .core import Command
|
| 10 |
+
from .core import Context
|
| 11 |
+
from .core import Group
|
| 12 |
+
from .core import Option
|
| 13 |
+
from .core import Parameter
|
| 14 |
+
from .globals import get_current_context
|
| 15 |
+
from .utils import echo
|
| 16 |
+
|
| 17 |
+
if t.TYPE_CHECKING:
|
| 18 |
+
import typing_extensions as te
|
| 19 |
+
|
| 20 |
+
P = te.ParamSpec("P")
|
| 21 |
+
|
| 22 |
+
R = t.TypeVar("R")
|
| 23 |
+
T = t.TypeVar("T")
|
| 24 |
+
_AnyCallable = t.Callable[..., t.Any]
|
| 25 |
+
FC = t.TypeVar("FC", bound="_AnyCallable | Command")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]:
|
| 29 |
+
"""Marks a callback as wanting to receive the current context
|
| 30 |
+
object as first argument.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 34 |
+
return f(get_current_context(), *args, **kwargs)
|
| 35 |
+
|
| 36 |
+
return update_wrapper(new_func, f)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:
|
| 40 |
+
"""Similar to :func:`pass_context`, but only pass the object on the
|
| 41 |
+
context onwards (:attr:`Context.obj`). This is useful if that object
|
| 42 |
+
represents the state of a nested system.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 46 |
+
return f(get_current_context().obj, *args, **kwargs)
|
| 47 |
+
|
| 48 |
+
return update_wrapper(new_func, f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def make_pass_decorator(
|
| 52 |
+
object_type: type[T], ensure: bool = False
|
| 53 |
+
) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:
|
| 54 |
+
"""Given an object type this creates a decorator that will work
|
| 55 |
+
similar to :func:`pass_obj` but instead of passing the object of the
|
| 56 |
+
current context, it will find the innermost context of type
|
| 57 |
+
:func:`object_type`.
|
| 58 |
+
|
| 59 |
+
This generates a decorator that works roughly like this::
|
| 60 |
+
|
| 61 |
+
from functools import update_wrapper
|
| 62 |
+
|
| 63 |
+
def decorator(f):
|
| 64 |
+
@pass_context
|
| 65 |
+
def new_func(ctx, *args, **kwargs):
|
| 66 |
+
obj = ctx.find_object(object_type)
|
| 67 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
| 68 |
+
return update_wrapper(new_func, f)
|
| 69 |
+
return decorator
|
| 70 |
+
|
| 71 |
+
:param object_type: the type of the object to pass.
|
| 72 |
+
:param ensure: if set to `True`, a new object will be created and
|
| 73 |
+
remembered on the context if it's not there yet.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:
|
| 77 |
+
def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 78 |
+
ctx = get_current_context()
|
| 79 |
+
|
| 80 |
+
obj: T | None
|
| 81 |
+
if ensure:
|
| 82 |
+
obj = ctx.ensure_object(object_type)
|
| 83 |
+
else:
|
| 84 |
+
obj = ctx.find_object(object_type)
|
| 85 |
+
|
| 86 |
+
if obj is None:
|
| 87 |
+
raise RuntimeError(
|
| 88 |
+
"Managed to invoke callback without a context"
|
| 89 |
+
f" object of type {object_type.__name__!r}"
|
| 90 |
+
" existing."
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
| 94 |
+
|
| 95 |
+
return update_wrapper(new_func, f)
|
| 96 |
+
|
| 97 |
+
return decorator
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def pass_meta_key(
|
| 101 |
+
key: str, *, doc_description: str | None = None
|
| 102 |
+
) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:
|
| 103 |
+
"""Create a decorator that passes a key from
|
| 104 |
+
:attr:`click.Context.meta` as the first argument to the decorated
|
| 105 |
+
function.
|
| 106 |
+
|
| 107 |
+
:param key: Key in ``Context.meta`` to pass.
|
| 108 |
+
:param doc_description: Description of the object being passed,
|
| 109 |
+
inserted into the decorator's docstring. Defaults to "the 'key'
|
| 110 |
+
key from Context.meta".
|
| 111 |
+
|
| 112 |
+
.. versionadded:: 8.0
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:
|
| 116 |
+
def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 117 |
+
ctx = get_current_context()
|
| 118 |
+
obj = ctx.meta[key]
|
| 119 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
| 120 |
+
|
| 121 |
+
return update_wrapper(new_func, f)
|
| 122 |
+
|
| 123 |
+
if doc_description is None:
|
| 124 |
+
doc_description = f"the {key!r} key from :attr:`click.Context.meta`"
|
| 125 |
+
|
| 126 |
+
decorator.__doc__ = (
|
| 127 |
+
f"Decorator that passes {doc_description} as the first argument"
|
| 128 |
+
" to the decorated function."
|
| 129 |
+
)
|
| 130 |
+
return decorator
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
CmdType = t.TypeVar("CmdType", bound=Command)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# variant: no call, directly as decorator for a function.
|
| 137 |
+
@t.overload
|
| 138 |
+
def command(name: _AnyCallable) -> Command: ...
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# variant: with positional name and with positional or keyword cls argument:
|
| 142 |
+
# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)
|
| 143 |
+
@t.overload
|
| 144 |
+
def command(
|
| 145 |
+
name: str | None,
|
| 146 |
+
cls: type[CmdType],
|
| 147 |
+
**attrs: t.Any,
|
| 148 |
+
) -> t.Callable[[_AnyCallable], CmdType]: ...
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)
|
| 152 |
+
@t.overload
|
| 153 |
+
def command(
|
| 154 |
+
name: None = None,
|
| 155 |
+
*,
|
| 156 |
+
cls: type[CmdType],
|
| 157 |
+
**attrs: t.Any,
|
| 158 |
+
) -> t.Callable[[_AnyCallable], CmdType]: ...
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# variant: with optional string name, no cls argument provided.
|
| 162 |
+
@t.overload
|
| 163 |
+
def command(
|
| 164 |
+
name: str | None = ..., cls: None = None, **attrs: t.Any
|
| 165 |
+
) -> t.Callable[[_AnyCallable], Command]: ...
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def command(
|
| 169 |
+
name: str | _AnyCallable | None = None,
|
| 170 |
+
cls: type[CmdType] | None = None,
|
| 171 |
+
**attrs: t.Any,
|
| 172 |
+
) -> Command | t.Callable[[_AnyCallable], Command | CmdType]:
|
| 173 |
+
r"""Creates a new :class:`Command` and uses the decorated function as
|
| 174 |
+
callback. This will also automatically attach all decorated
|
| 175 |
+
:func:`option`\s and :func:`argument`\s as parameters to the command.
|
| 176 |
+
|
| 177 |
+
The name of the command defaults to the name of the function, converted to
|
| 178 |
+
lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes
|
| 179 |
+
``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example,
|
| 180 |
+
``init_data_command`` becomes ``init-data``.
|
| 181 |
+
|
| 182 |
+
All keyword arguments are forwarded to the underlying command class.
|
| 183 |
+
For the ``params`` argument, any decorated params are appended to
|
| 184 |
+
the end of the list.
|
| 185 |
+
|
| 186 |
+
Once decorated the function turns into a :class:`Command` instance
|
| 187 |
+
that can be invoked as a command line utility or be attached to a
|
| 188 |
+
command :class:`Group`.
|
| 189 |
+
|
| 190 |
+
:param name: The name of the command. Defaults to modifying the function's
|
| 191 |
+
name as described above.
|
| 192 |
+
:param cls: The command class to create. Defaults to :class:`Command`.
|
| 193 |
+
|
| 194 |
+
.. versionchanged:: 8.2
|
| 195 |
+
The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are
|
| 196 |
+
removed when generating the name.
|
| 197 |
+
|
| 198 |
+
.. versionchanged:: 8.1
|
| 199 |
+
This decorator can be applied without parentheses.
|
| 200 |
+
|
| 201 |
+
.. versionchanged:: 8.1
|
| 202 |
+
The ``params`` argument can be used. Decorated params are
|
| 203 |
+
appended to the end of the list.
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
func: t.Callable[[_AnyCallable], t.Any] | None = None
|
| 207 |
+
|
| 208 |
+
if callable(name):
|
| 209 |
+
func = name
|
| 210 |
+
name = None
|
| 211 |
+
assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
|
| 212 |
+
assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
|
| 213 |
+
|
| 214 |
+
if cls is None:
|
| 215 |
+
cls = t.cast("type[CmdType]", Command)
|
| 216 |
+
|
| 217 |
+
def decorator(f: _AnyCallable) -> CmdType:
|
| 218 |
+
if isinstance(f, Command):
|
| 219 |
+
raise TypeError("Attempted to convert a callback into a command twice.")
|
| 220 |
+
|
| 221 |
+
attr_params = attrs.pop("params", None)
|
| 222 |
+
params = attr_params if attr_params is not None else []
|
| 223 |
+
|
| 224 |
+
try:
|
| 225 |
+
decorator_params = f.__click_params__ # type: ignore
|
| 226 |
+
except AttributeError:
|
| 227 |
+
pass
|
| 228 |
+
else:
|
| 229 |
+
del f.__click_params__ # type: ignore
|
| 230 |
+
params.extend(reversed(decorator_params))
|
| 231 |
+
|
| 232 |
+
if attrs.get("help") is None:
|
| 233 |
+
attrs["help"] = f.__doc__
|
| 234 |
+
|
| 235 |
+
if t.TYPE_CHECKING:
|
| 236 |
+
assert cls is not None
|
| 237 |
+
assert not callable(name)
|
| 238 |
+
|
| 239 |
+
if name is not None:
|
| 240 |
+
cmd_name = name
|
| 241 |
+
else:
|
| 242 |
+
cmd_name = f.__name__.lower().replace("_", "-")
|
| 243 |
+
cmd_left, sep, suffix = cmd_name.rpartition("-")
|
| 244 |
+
|
| 245 |
+
if sep and suffix in {"command", "cmd", "group", "grp"}:
|
| 246 |
+
cmd_name = cmd_left
|
| 247 |
+
|
| 248 |
+
cmd = cls(name=cmd_name, callback=f, params=params, **attrs)
|
| 249 |
+
cmd.__doc__ = f.__doc__
|
| 250 |
+
return cmd
|
| 251 |
+
|
| 252 |
+
if func is not None:
|
| 253 |
+
return decorator(func)
|
| 254 |
+
|
| 255 |
+
return decorator
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
GrpType = t.TypeVar("GrpType", bound=Group)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# variant: no call, directly as decorator for a function.
|
| 262 |
+
@t.overload
|
| 263 |
+
def group(name: _AnyCallable) -> Group: ...
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
# variant: with positional name and with positional or keyword cls argument:
|
| 267 |
+
# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)
|
| 268 |
+
@t.overload
|
| 269 |
+
def group(
|
| 270 |
+
name: str | None,
|
| 271 |
+
cls: type[GrpType],
|
| 272 |
+
**attrs: t.Any,
|
| 273 |
+
) -> t.Callable[[_AnyCallable], GrpType]: ...
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)
|
| 277 |
+
@t.overload
|
| 278 |
+
def group(
|
| 279 |
+
name: None = None,
|
| 280 |
+
*,
|
| 281 |
+
cls: type[GrpType],
|
| 282 |
+
**attrs: t.Any,
|
| 283 |
+
) -> t.Callable[[_AnyCallable], GrpType]: ...
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
# variant: with optional string name, no cls argument provided.
|
| 287 |
+
@t.overload
|
| 288 |
+
def group(
|
| 289 |
+
name: str | None = ..., cls: None = None, **attrs: t.Any
|
| 290 |
+
) -> t.Callable[[_AnyCallable], Group]: ...
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def group(
|
| 294 |
+
name: str | _AnyCallable | None = None,
|
| 295 |
+
cls: type[GrpType] | None = None,
|
| 296 |
+
**attrs: t.Any,
|
| 297 |
+
) -> Group | t.Callable[[_AnyCallable], Group | GrpType]:
|
| 298 |
+
"""Creates a new :class:`Group` with a function as callback. This
|
| 299 |
+
works otherwise the same as :func:`command` just that the `cls`
|
| 300 |
+
parameter is set to :class:`Group`.
|
| 301 |
+
|
| 302 |
+
.. versionchanged:: 8.1
|
| 303 |
+
This decorator can be applied without parentheses.
|
| 304 |
+
"""
|
| 305 |
+
if cls is None:
|
| 306 |
+
cls = t.cast("type[GrpType]", Group)
|
| 307 |
+
|
| 308 |
+
if callable(name):
|
| 309 |
+
return command(cls=cls, **attrs)(name)
|
| 310 |
+
|
| 311 |
+
return command(name, cls, **attrs)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None:
|
| 315 |
+
if isinstance(f, Command):
|
| 316 |
+
f.params.append(param)
|
| 317 |
+
else:
|
| 318 |
+
if not hasattr(f, "__click_params__"):
|
| 319 |
+
f.__click_params__ = [] # type: ignore
|
| 320 |
+
|
| 321 |
+
f.__click_params__.append(param) # type: ignore
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def argument(
|
| 325 |
+
*param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any
|
| 326 |
+
) -> t.Callable[[FC], FC]:
|
| 327 |
+
"""Attaches an argument to the command. All positional arguments are
|
| 328 |
+
passed as parameter declarations to :class:`Argument`; all keyword
|
| 329 |
+
arguments are forwarded unchanged (except ``cls``).
|
| 330 |
+
This is equivalent to creating an :class:`Argument` instance manually
|
| 331 |
+
and attaching it to the :attr:`Command.params` list.
|
| 332 |
+
|
| 333 |
+
For the default argument class, refer to :class:`Argument` and
|
| 334 |
+
:class:`Parameter` for descriptions of parameters.
|
| 335 |
+
|
| 336 |
+
:param cls: the argument class to instantiate. This defaults to
|
| 337 |
+
:class:`Argument`.
|
| 338 |
+
:param param_decls: Passed as positional arguments to the constructor of
|
| 339 |
+
``cls``.
|
| 340 |
+
:param attrs: Passed as keyword arguments to the constructor of ``cls``.
|
| 341 |
+
"""
|
| 342 |
+
if cls is None:
|
| 343 |
+
cls = Argument
|
| 344 |
+
|
| 345 |
+
def decorator(f: FC) -> FC:
|
| 346 |
+
_param_memo(f, cls(param_decls, **attrs))
|
| 347 |
+
return f
|
| 348 |
+
|
| 349 |
+
return decorator
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def option(
|
| 353 |
+
*param_decls: str, cls: type[Option] | None = None, **attrs: t.Any
|
| 354 |
+
) -> t.Callable[[FC], FC]:
|
| 355 |
+
"""Attaches an option to the command. All positional arguments are
|
| 356 |
+
passed as parameter declarations to :class:`Option`; all keyword
|
| 357 |
+
arguments are forwarded unchanged (except ``cls``).
|
| 358 |
+
This is equivalent to creating an :class:`Option` instance manually
|
| 359 |
+
and attaching it to the :attr:`Command.params` list.
|
| 360 |
+
|
| 361 |
+
For the default option class, refer to :class:`Option` and
|
| 362 |
+
:class:`Parameter` for descriptions of parameters.
|
| 363 |
+
|
| 364 |
+
:param cls: the option class to instantiate. This defaults to
|
| 365 |
+
:class:`Option`.
|
| 366 |
+
:param param_decls: Passed as positional arguments to the constructor of
|
| 367 |
+
``cls``.
|
| 368 |
+
:param attrs: Passed as keyword arguments to the constructor of ``cls``.
|
| 369 |
+
"""
|
| 370 |
+
if cls is None:
|
| 371 |
+
cls = Option
|
| 372 |
+
|
| 373 |
+
def decorator(f: FC) -> FC:
|
| 374 |
+
_param_memo(f, cls(param_decls, **attrs))
|
| 375 |
+
return f
|
| 376 |
+
|
| 377 |
+
return decorator
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
| 381 |
+
"""Add a ``--yes`` option which shows a prompt before continuing if
|
| 382 |
+
not passed. If the prompt is declined, the program will exit.
|
| 383 |
+
|
| 384 |
+
:param param_decls: One or more option names. Defaults to the single
|
| 385 |
+
value ``"--yes"``.
|
| 386 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
| 387 |
+
"""
|
| 388 |
+
|
| 389 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
| 390 |
+
if not value:
|
| 391 |
+
ctx.abort()
|
| 392 |
+
|
| 393 |
+
if not param_decls:
|
| 394 |
+
param_decls = ("--yes",)
|
| 395 |
+
|
| 396 |
+
kwargs.setdefault("is_flag", True)
|
| 397 |
+
kwargs.setdefault("callback", callback)
|
| 398 |
+
kwargs.setdefault("expose_value", False)
|
| 399 |
+
kwargs.setdefault("prompt", "Do you want to continue?")
|
| 400 |
+
kwargs.setdefault("help", "Confirm the action without prompting.")
|
| 401 |
+
return option(*param_decls, **kwargs)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
| 405 |
+
"""Add a ``--password`` option which prompts for a password, hiding
|
| 406 |
+
input and asking to enter the value again for confirmation.
|
| 407 |
+
|
| 408 |
+
:param param_decls: One or more option names. Defaults to the single
|
| 409 |
+
value ``"--password"``.
|
| 410 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
| 411 |
+
"""
|
| 412 |
+
if not param_decls:
|
| 413 |
+
param_decls = ("--password",)
|
| 414 |
+
|
| 415 |
+
kwargs.setdefault("prompt", True)
|
| 416 |
+
kwargs.setdefault("confirmation_prompt", True)
|
| 417 |
+
kwargs.setdefault("hide_input", True)
|
| 418 |
+
return option(*param_decls, **kwargs)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def version_option(
|
| 422 |
+
version: str | None = None,
|
| 423 |
+
*param_decls: str,
|
| 424 |
+
package_name: str | None = None,
|
| 425 |
+
prog_name: str | None = None,
|
| 426 |
+
message: str | None = None,
|
| 427 |
+
**kwargs: t.Any,
|
| 428 |
+
) -> t.Callable[[FC], FC]:
|
| 429 |
+
"""Add a ``--version`` option which immediately prints the version
|
| 430 |
+
number and exits the program.
|
| 431 |
+
|
| 432 |
+
If ``version`` is not provided, Click will try to detect it using
|
| 433 |
+
:func:`importlib.metadata.version` to get the version for the
|
| 434 |
+
``package_name``.
|
| 435 |
+
|
| 436 |
+
If ``package_name`` is not provided, Click will try to detect it by
|
| 437 |
+
inspecting the stack frames. This will be used to detect the
|
| 438 |
+
version, so it must match the name of the installed package.
|
| 439 |
+
|
| 440 |
+
:param version: The version number to show. If not provided, Click
|
| 441 |
+
will try to detect it.
|
| 442 |
+
:param param_decls: One or more option names. Defaults to the single
|
| 443 |
+
value ``"--version"``.
|
| 444 |
+
:param package_name: The package name to detect the version from. If
|
| 445 |
+
not provided, Click will try to detect it.
|
| 446 |
+
:param prog_name: The name of the CLI to show in the message. If not
|
| 447 |
+
provided, it will be detected from the command.
|
| 448 |
+
:param message: The message to show. The values ``%(prog)s``,
|
| 449 |
+
``%(package)s``, and ``%(version)s`` are available. Defaults to
|
| 450 |
+
``"%(prog)s, version %(version)s"``.
|
| 451 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
| 452 |
+
:raise RuntimeError: ``version`` could not be detected.
|
| 453 |
+
|
| 454 |
+
.. versionchanged:: 8.0
|
| 455 |
+
Add the ``package_name`` parameter, and the ``%(package)s``
|
| 456 |
+
value for messages.
|
| 457 |
+
|
| 458 |
+
.. versionchanged:: 8.0
|
| 459 |
+
Use :mod:`importlib.metadata` instead of ``pkg_resources``. The
|
| 460 |
+
version is detected based on the package name, not the entry
|
| 461 |
+
point name. The Python package name must match the installed
|
| 462 |
+
package name, or be passed with ``package_name=``.
|
| 463 |
+
"""
|
| 464 |
+
if message is None:
|
| 465 |
+
message = _("%(prog)s, version %(version)s")
|
| 466 |
+
|
| 467 |
+
if version is None and package_name is None:
|
| 468 |
+
frame = inspect.currentframe()
|
| 469 |
+
f_back = frame.f_back if frame is not None else None
|
| 470 |
+
f_globals = f_back.f_globals if f_back is not None else None
|
| 471 |
+
# break reference cycle
|
| 472 |
+
# https://docs.python.org/3/library/inspect.html#the-interpreter-stack
|
| 473 |
+
del frame
|
| 474 |
+
|
| 475 |
+
if f_globals is not None:
|
| 476 |
+
package_name = f_globals.get("__name__")
|
| 477 |
+
|
| 478 |
+
if package_name == "__main__":
|
| 479 |
+
package_name = f_globals.get("__package__")
|
| 480 |
+
|
| 481 |
+
if package_name:
|
| 482 |
+
package_name = package_name.partition(".")[0]
|
| 483 |
+
|
| 484 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
| 485 |
+
if not value or ctx.resilient_parsing:
|
| 486 |
+
return
|
| 487 |
+
|
| 488 |
+
nonlocal prog_name
|
| 489 |
+
nonlocal version
|
| 490 |
+
|
| 491 |
+
if prog_name is None:
|
| 492 |
+
prog_name = ctx.find_root().info_name
|
| 493 |
+
|
| 494 |
+
if version is None and package_name is not None:
|
| 495 |
+
import importlib.metadata
|
| 496 |
+
|
| 497 |
+
try:
|
| 498 |
+
version = importlib.metadata.version(package_name)
|
| 499 |
+
except importlib.metadata.PackageNotFoundError:
|
| 500 |
+
raise RuntimeError(
|
| 501 |
+
f"{package_name!r} is not installed. Try passing"
|
| 502 |
+
" 'package_name' instead."
|
| 503 |
+
) from None
|
| 504 |
+
|
| 505 |
+
if version is None:
|
| 506 |
+
raise RuntimeError(
|
| 507 |
+
f"Could not determine the version for {package_name!r} automatically."
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
echo(
|
| 511 |
+
message % {"prog": prog_name, "package": package_name, "version": version},
|
| 512 |
+
color=ctx.color,
|
| 513 |
+
)
|
| 514 |
+
ctx.exit()
|
| 515 |
+
|
| 516 |
+
if not param_decls:
|
| 517 |
+
param_decls = ("--version",)
|
| 518 |
+
|
| 519 |
+
kwargs.setdefault("is_flag", True)
|
| 520 |
+
kwargs.setdefault("expose_value", False)
|
| 521 |
+
kwargs.setdefault("is_eager", True)
|
| 522 |
+
kwargs.setdefault("help", _("Show the version and exit."))
|
| 523 |
+
kwargs["callback"] = callback
|
| 524 |
+
return option(*param_decls, **kwargs)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
| 528 |
+
"""Pre-configured ``--help`` option which immediately prints the help page
|
| 529 |
+
and exits the program.
|
| 530 |
+
|
| 531 |
+
:param param_decls: One or more option names. Defaults to the single
|
| 532 |
+
value ``"--help"``.
|
| 533 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
| 534 |
+
"""
|
| 535 |
+
|
| 536 |
+
def show_help(ctx: Context, param: Parameter, value: bool) -> None:
|
| 537 |
+
"""Callback that print the help page on ``<stdout>`` and exits."""
|
| 538 |
+
if value and not ctx.resilient_parsing:
|
| 539 |
+
echo(ctx.get_help(), color=ctx.color)
|
| 540 |
+
ctx.exit()
|
| 541 |
+
|
| 542 |
+
if not param_decls:
|
| 543 |
+
param_decls = ("--help",)
|
| 544 |
+
|
| 545 |
+
kwargs.setdefault("is_flag", True)
|
| 546 |
+
kwargs.setdefault("expose_value", False)
|
| 547 |
+
kwargs.setdefault("is_eager", True)
|
| 548 |
+
kwargs.setdefault("help", _("Show this message and exit."))
|
| 549 |
+
kwargs.setdefault("callback", show_help)
|
| 550 |
+
|
| 551 |
+
return option(*param_decls, **kwargs)
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/exceptions.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections.abc as cabc
|
| 4 |
+
import typing as t
|
| 5 |
+
from gettext import gettext as _
|
| 6 |
+
from gettext import ngettext
|
| 7 |
+
|
| 8 |
+
from ._compat import get_text_stderr
|
| 9 |
+
from .globals import resolve_color_default
|
| 10 |
+
from .utils import echo
|
| 11 |
+
from .utils import format_filename
|
| 12 |
+
|
| 13 |
+
if t.TYPE_CHECKING:
|
| 14 |
+
from .core import Command
|
| 15 |
+
from .core import Context
|
| 16 |
+
from .core import Parameter
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None:
|
| 20 |
+
if param_hint is not None and not isinstance(param_hint, str):
|
| 21 |
+
return " / ".join(repr(x) for x in param_hint)
|
| 22 |
+
|
| 23 |
+
return param_hint
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ClickException(Exception):
|
| 27 |
+
"""An exception that Click can handle and show to the user."""
|
| 28 |
+
|
| 29 |
+
#: The exit code for this exception.
|
| 30 |
+
exit_code = 1
|
| 31 |
+
|
| 32 |
+
def __init__(self, message: str) -> None:
|
| 33 |
+
super().__init__(message)
|
| 34 |
+
# The context will be removed by the time we print the message, so cache
|
| 35 |
+
# the color settings here to be used later on (in `show`)
|
| 36 |
+
self.show_color: bool | None = resolve_color_default()
|
| 37 |
+
self.message = message
|
| 38 |
+
|
| 39 |
+
def format_message(self) -> str:
|
| 40 |
+
return self.message
|
| 41 |
+
|
| 42 |
+
def __str__(self) -> str:
|
| 43 |
+
return self.message
|
| 44 |
+
|
| 45 |
+
def show(self, file: t.IO[t.Any] | None = None) -> None:
|
| 46 |
+
if file is None:
|
| 47 |
+
file = get_text_stderr()
|
| 48 |
+
|
| 49 |
+
echo(
|
| 50 |
+
_("Error: {message}").format(message=self.format_message()),
|
| 51 |
+
file=file,
|
| 52 |
+
color=self.show_color,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class UsageError(ClickException):
|
| 57 |
+
"""An internal exception that signals a usage error. This typically
|
| 58 |
+
aborts any further handling.
|
| 59 |
+
|
| 60 |
+
:param message: the error message to display.
|
| 61 |
+
:param ctx: optionally the context that caused this error. Click will
|
| 62 |
+
fill in the context automatically in some situations.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
exit_code = 2
|
| 66 |
+
|
| 67 |
+
def __init__(self, message: str, ctx: Context | None = None) -> None:
|
| 68 |
+
super().__init__(message)
|
| 69 |
+
self.ctx = ctx
|
| 70 |
+
self.cmd: Command | None = self.ctx.command if self.ctx else None
|
| 71 |
+
|
| 72 |
+
def show(self, file: t.IO[t.Any] | None = None) -> None:
|
| 73 |
+
if file is None:
|
| 74 |
+
file = get_text_stderr()
|
| 75 |
+
color = None
|
| 76 |
+
hint = ""
|
| 77 |
+
if (
|
| 78 |
+
self.ctx is not None
|
| 79 |
+
and self.ctx.command.get_help_option(self.ctx) is not None
|
| 80 |
+
):
|
| 81 |
+
hint = _("Try '{command} {option}' for help.").format(
|
| 82 |
+
command=self.ctx.command_path, option=self.ctx.help_option_names[0]
|
| 83 |
+
)
|
| 84 |
+
hint = f"{hint}\n"
|
| 85 |
+
if self.ctx is not None:
|
| 86 |
+
color = self.ctx.color
|
| 87 |
+
echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)
|
| 88 |
+
echo(
|
| 89 |
+
_("Error: {message}").format(message=self.format_message()),
|
| 90 |
+
file=file,
|
| 91 |
+
color=color,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class BadParameter(UsageError):
|
| 96 |
+
"""An exception that formats out a standardized error message for a
|
| 97 |
+
bad parameter. This is useful when thrown from a callback or type as
|
| 98 |
+
Click will attach contextual information to it (for instance, which
|
| 99 |
+
parameter it is).
|
| 100 |
+
|
| 101 |
+
.. versionadded:: 2.0
|
| 102 |
+
|
| 103 |
+
:param param: the parameter object that caused this error. This can
|
| 104 |
+
be left out, and Click will attach this info itself
|
| 105 |
+
if possible.
|
| 106 |
+
:param param_hint: a string that shows up as parameter name. This
|
| 107 |
+
can be used as alternative to `param` in cases
|
| 108 |
+
where custom validation should happen. If it is
|
| 109 |
+
a string it's used as such, if it's a list then
|
| 110 |
+
each item is quoted and separated.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
message: str,
|
| 116 |
+
ctx: Context | None = None,
|
| 117 |
+
param: Parameter | None = None,
|
| 118 |
+
param_hint: cabc.Sequence[str] | str | None = None,
|
| 119 |
+
) -> None:
|
| 120 |
+
super().__init__(message, ctx)
|
| 121 |
+
self.param = param
|
| 122 |
+
self.param_hint = param_hint
|
| 123 |
+
|
| 124 |
+
def format_message(self) -> str:
|
| 125 |
+
if self.param_hint is not None:
|
| 126 |
+
param_hint = self.param_hint
|
| 127 |
+
elif self.param is not None:
|
| 128 |
+
param_hint = self.param.get_error_hint(self.ctx) # type: ignore
|
| 129 |
+
else:
|
| 130 |
+
return _("Invalid value: {message}").format(message=self.message)
|
| 131 |
+
|
| 132 |
+
return _("Invalid value for {param_hint}: {message}").format(
|
| 133 |
+
param_hint=_join_param_hints(param_hint), message=self.message
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class MissingParameter(BadParameter):
|
| 138 |
+
"""Raised if click required an option or argument but it was not
|
| 139 |
+
provided when invoking the script.
|
| 140 |
+
|
| 141 |
+
.. versionadded:: 4.0
|
| 142 |
+
|
| 143 |
+
:param param_type: a string that indicates the type of the parameter.
|
| 144 |
+
The default is to inherit the parameter type from
|
| 145 |
+
the given `param`. Valid values are ``'parameter'``,
|
| 146 |
+
``'option'`` or ``'argument'``.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
def __init__(
|
| 150 |
+
self,
|
| 151 |
+
message: str | None = None,
|
| 152 |
+
ctx: Context | None = None,
|
| 153 |
+
param: Parameter | None = None,
|
| 154 |
+
param_hint: cabc.Sequence[str] | str | None = None,
|
| 155 |
+
param_type: str | None = None,
|
| 156 |
+
) -> None:
|
| 157 |
+
super().__init__(message or "", ctx, param, param_hint)
|
| 158 |
+
self.param_type = param_type
|
| 159 |
+
|
| 160 |
+
def format_message(self) -> str:
|
| 161 |
+
if self.param_hint is not None:
|
| 162 |
+
param_hint: cabc.Sequence[str] | str | None = self.param_hint
|
| 163 |
+
elif self.param is not None:
|
| 164 |
+
param_hint = self.param.get_error_hint(self.ctx) # type: ignore
|
| 165 |
+
else:
|
| 166 |
+
param_hint = None
|
| 167 |
+
|
| 168 |
+
param_hint = _join_param_hints(param_hint)
|
| 169 |
+
param_hint = f" {param_hint}" if param_hint else ""
|
| 170 |
+
|
| 171 |
+
param_type = self.param_type
|
| 172 |
+
if param_type is None and self.param is not None:
|
| 173 |
+
param_type = self.param.param_type_name
|
| 174 |
+
|
| 175 |
+
msg = self.message
|
| 176 |
+
if self.param is not None:
|
| 177 |
+
msg_extra = self.param.type.get_missing_message(
|
| 178 |
+
param=self.param, ctx=self.ctx
|
| 179 |
+
)
|
| 180 |
+
if msg_extra:
|
| 181 |
+
if msg:
|
| 182 |
+
msg += f". {msg_extra}"
|
| 183 |
+
else:
|
| 184 |
+
msg = msg_extra
|
| 185 |
+
|
| 186 |
+
msg = f" {msg}" if msg else ""
|
| 187 |
+
|
| 188 |
+
# Translate param_type for known types.
|
| 189 |
+
if param_type == "argument":
|
| 190 |
+
missing = _("Missing argument")
|
| 191 |
+
elif param_type == "option":
|
| 192 |
+
missing = _("Missing option")
|
| 193 |
+
elif param_type == "parameter":
|
| 194 |
+
missing = _("Missing parameter")
|
| 195 |
+
else:
|
| 196 |
+
missing = _("Missing {param_type}").format(param_type=param_type)
|
| 197 |
+
|
| 198 |
+
return f"{missing}{param_hint}.{msg}"
|
| 199 |
+
|
| 200 |
+
def __str__(self) -> str:
|
| 201 |
+
if not self.message:
|
| 202 |
+
param_name = self.param.name if self.param else None
|
| 203 |
+
return _("Missing parameter: {param_name}").format(param_name=param_name)
|
| 204 |
+
else:
|
| 205 |
+
return self.message
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class NoSuchOption(UsageError):
|
| 209 |
+
"""Raised if click attempted to handle an option that does not
|
| 210 |
+
exist.
|
| 211 |
+
|
| 212 |
+
.. versionadded:: 4.0
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
def __init__(
|
| 216 |
+
self,
|
| 217 |
+
option_name: str,
|
| 218 |
+
message: str | None = None,
|
| 219 |
+
possibilities: cabc.Sequence[str] | None = None,
|
| 220 |
+
ctx: Context | None = None,
|
| 221 |
+
) -> None:
|
| 222 |
+
if message is None:
|
| 223 |
+
message = _("No such option: {name}").format(name=option_name)
|
| 224 |
+
|
| 225 |
+
super().__init__(message, ctx)
|
| 226 |
+
self.option_name = option_name
|
| 227 |
+
self.possibilities = possibilities
|
| 228 |
+
|
| 229 |
+
def format_message(self) -> str:
|
| 230 |
+
if not self.possibilities:
|
| 231 |
+
return self.message
|
| 232 |
+
|
| 233 |
+
possibility_str = ", ".join(sorted(self.possibilities))
|
| 234 |
+
suggest = ngettext(
|
| 235 |
+
"Did you mean {possibility}?",
|
| 236 |
+
"(Possible options: {possibilities})",
|
| 237 |
+
len(self.possibilities),
|
| 238 |
+
).format(possibility=possibility_str, possibilities=possibility_str)
|
| 239 |
+
return f"{self.message} {suggest}"
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class BadOptionUsage(UsageError):
|
| 243 |
+
"""Raised if an option is generally supplied but the use of the option
|
| 244 |
+
was incorrect. This is for instance raised if the number of arguments
|
| 245 |
+
for an option is not correct.
|
| 246 |
+
|
| 247 |
+
.. versionadded:: 4.0
|
| 248 |
+
|
| 249 |
+
:param option_name: the name of the option being used incorrectly.
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
def __init__(
|
| 253 |
+
self, option_name: str, message: str, ctx: Context | None = None
|
| 254 |
+
) -> None:
|
| 255 |
+
super().__init__(message, ctx)
|
| 256 |
+
self.option_name = option_name
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class BadArgumentUsage(UsageError):
|
| 260 |
+
"""Raised if an argument is generally supplied but the use of the argument
|
| 261 |
+
was incorrect. This is for instance raised if the number of values
|
| 262 |
+
for an argument is not correct.
|
| 263 |
+
|
| 264 |
+
.. versionadded:: 6.0
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class NoArgsIsHelpError(UsageError):
|
| 269 |
+
def __init__(self, ctx: Context) -> None:
|
| 270 |
+
self.ctx: Context
|
| 271 |
+
super().__init__(ctx.get_help(), ctx=ctx)
|
| 272 |
+
|
| 273 |
+
def show(self, file: t.IO[t.Any] | None = None) -> None:
|
| 274 |
+
echo(self.format_message(), file=file, err=True, color=self.ctx.color)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class FileError(ClickException):
|
| 278 |
+
"""Raised if a file cannot be opened."""
|
| 279 |
+
|
| 280 |
+
def __init__(self, filename: str, hint: str | None = None) -> None:
|
| 281 |
+
if hint is None:
|
| 282 |
+
hint = _("unknown error")
|
| 283 |
+
|
| 284 |
+
super().__init__(hint)
|
| 285 |
+
self.ui_filename: str = format_filename(filename)
|
| 286 |
+
self.filename = filename
|
| 287 |
+
|
| 288 |
+
def format_message(self) -> str:
|
| 289 |
+
return _("Could not open file {filename!r}: {message}").format(
|
| 290 |
+
filename=self.ui_filename, message=self.message
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class Abort(RuntimeError):
|
| 295 |
+
"""An internal signalling exception that signals Click to abort."""
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class Exit(RuntimeError):
|
| 299 |
+
"""An exception that indicates that the application should exit with some
|
| 300 |
+
status code.
|
| 301 |
+
|
| 302 |
+
:param code: the status code to exit with.
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
__slots__ = ("exit_code",)
|
| 306 |
+
|
| 307 |
+
def __init__(self, code: int = 0) -> None:
|
| 308 |
+
self.exit_code: int = code
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/formatting.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections.abc as cabc
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from gettext import gettext as _
|
| 6 |
+
|
| 7 |
+
from ._compat import term_len
|
| 8 |
+
from .parser import _split_opt
|
| 9 |
+
|
| 10 |
+
# Can force a width. This is used by the test system
|
| 11 |
+
FORCED_WIDTH: int | None = None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]:
|
| 15 |
+
widths: dict[int, int] = {}
|
| 16 |
+
|
| 17 |
+
for row in rows:
|
| 18 |
+
for idx, col in enumerate(row):
|
| 19 |
+
widths[idx] = max(widths.get(idx, 0), term_len(col))
|
| 20 |
+
|
| 21 |
+
return tuple(y for x, y in sorted(widths.items()))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def iter_rows(
|
| 25 |
+
rows: cabc.Iterable[tuple[str, str]], col_count: int
|
| 26 |
+
) -> cabc.Iterator[tuple[str, ...]]:
|
| 27 |
+
for row in rows:
|
| 28 |
+
yield row + ("",) * (col_count - len(row))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def wrap_text(
|
| 32 |
+
text: str,
|
| 33 |
+
width: int = 78,
|
| 34 |
+
initial_indent: str = "",
|
| 35 |
+
subsequent_indent: str = "",
|
| 36 |
+
preserve_paragraphs: bool = False,
|
| 37 |
+
) -> str:
|
| 38 |
+
"""A helper function that intelligently wraps text. By default, it
|
| 39 |
+
assumes that it operates on a single paragraph of text but if the
|
| 40 |
+
`preserve_paragraphs` parameter is provided it will intelligently
|
| 41 |
+
handle paragraphs (defined by two empty lines).
|
| 42 |
+
|
| 43 |
+
If paragraphs are handled, a paragraph can be prefixed with an empty
|
| 44 |
+
line containing the ``\\b`` character (``\\x08``) to indicate that
|
| 45 |
+
no rewrapping should happen in that block.
|
| 46 |
+
|
| 47 |
+
:param text: the text that should be rewrapped.
|
| 48 |
+
:param width: the maximum width for the text.
|
| 49 |
+
:param initial_indent: the initial indent that should be placed on the
|
| 50 |
+
first line as a string.
|
| 51 |
+
:param subsequent_indent: the indent string that should be placed on
|
| 52 |
+
each consecutive line.
|
| 53 |
+
:param preserve_paragraphs: if this flag is set then the wrapping will
|
| 54 |
+
intelligently handle paragraphs.
|
| 55 |
+
"""
|
| 56 |
+
from ._textwrap import TextWrapper
|
| 57 |
+
|
| 58 |
+
text = text.expandtabs()
|
| 59 |
+
wrapper = TextWrapper(
|
| 60 |
+
width,
|
| 61 |
+
initial_indent=initial_indent,
|
| 62 |
+
subsequent_indent=subsequent_indent,
|
| 63 |
+
replace_whitespace=False,
|
| 64 |
+
)
|
| 65 |
+
if not preserve_paragraphs:
|
| 66 |
+
return wrapper.fill(text)
|
| 67 |
+
|
| 68 |
+
p: list[tuple[int, bool, str]] = []
|
| 69 |
+
buf: list[str] = []
|
| 70 |
+
indent = None
|
| 71 |
+
|
| 72 |
+
def _flush_par() -> None:
|
| 73 |
+
if not buf:
|
| 74 |
+
return
|
| 75 |
+
if buf[0].strip() == "\b":
|
| 76 |
+
p.append((indent or 0, True, "\n".join(buf[1:])))
|
| 77 |
+
else:
|
| 78 |
+
p.append((indent or 0, False, " ".join(buf)))
|
| 79 |
+
del buf[:]
|
| 80 |
+
|
| 81 |
+
for line in text.splitlines():
|
| 82 |
+
if not line:
|
| 83 |
+
_flush_par()
|
| 84 |
+
indent = None
|
| 85 |
+
else:
|
| 86 |
+
if indent is None:
|
| 87 |
+
orig_len = term_len(line)
|
| 88 |
+
line = line.lstrip()
|
| 89 |
+
indent = orig_len - term_len(line)
|
| 90 |
+
buf.append(line)
|
| 91 |
+
_flush_par()
|
| 92 |
+
|
| 93 |
+
rv = []
|
| 94 |
+
for indent, raw, text in p:
|
| 95 |
+
with wrapper.extra_indent(" " * indent):
|
| 96 |
+
if raw:
|
| 97 |
+
rv.append(wrapper.indent_only(text))
|
| 98 |
+
else:
|
| 99 |
+
rv.append(wrapper.fill(text))
|
| 100 |
+
|
| 101 |
+
return "\n\n".join(rv)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class HelpFormatter:
|
| 105 |
+
"""This class helps with formatting text-based help pages. It's
|
| 106 |
+
usually just needed for very special internal cases, but it's also
|
| 107 |
+
exposed so that developers can write their own fancy outputs.
|
| 108 |
+
|
| 109 |
+
At present, it always writes into memory.
|
| 110 |
+
|
| 111 |
+
:param indent_increment: the additional increment for each level.
|
| 112 |
+
:param width: the width for the text. This defaults to the terminal
|
| 113 |
+
width clamped to a maximum of 78.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
def __init__(
|
| 117 |
+
self,
|
| 118 |
+
indent_increment: int = 2,
|
| 119 |
+
width: int | None = None,
|
| 120 |
+
max_width: int | None = None,
|
| 121 |
+
) -> None:
|
| 122 |
+
self.indent_increment = indent_increment
|
| 123 |
+
if max_width is None:
|
| 124 |
+
max_width = 80
|
| 125 |
+
if width is None:
|
| 126 |
+
import shutil
|
| 127 |
+
|
| 128 |
+
width = FORCED_WIDTH
|
| 129 |
+
if width is None:
|
| 130 |
+
width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)
|
| 131 |
+
self.width = width
|
| 132 |
+
self.current_indent: int = 0
|
| 133 |
+
self.buffer: list[str] = []
|
| 134 |
+
|
| 135 |
+
def write(self, string: str) -> None:
|
| 136 |
+
"""Writes a unicode string into the internal buffer."""
|
| 137 |
+
self.buffer.append(string)
|
| 138 |
+
|
| 139 |
+
def indent(self) -> None:
|
| 140 |
+
"""Increases the indentation."""
|
| 141 |
+
self.current_indent += self.indent_increment
|
| 142 |
+
|
| 143 |
+
def dedent(self) -> None:
|
| 144 |
+
"""Decreases the indentation."""
|
| 145 |
+
self.current_indent -= self.indent_increment
|
| 146 |
+
|
| 147 |
+
def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None:
|
| 148 |
+
"""Writes a usage line into the buffer.
|
| 149 |
+
|
| 150 |
+
:param prog: the program name.
|
| 151 |
+
:param args: whitespace separated list of arguments.
|
| 152 |
+
:param prefix: The prefix for the first line. Defaults to
|
| 153 |
+
``"Usage: "``.
|
| 154 |
+
"""
|
| 155 |
+
if prefix is None:
|
| 156 |
+
prefix = f"{_('Usage:')} "
|
| 157 |
+
|
| 158 |
+
usage_prefix = f"{prefix:>{self.current_indent}}{prog} "
|
| 159 |
+
text_width = self.width - self.current_indent
|
| 160 |
+
|
| 161 |
+
if text_width >= (term_len(usage_prefix) + 20):
|
| 162 |
+
# The arguments will fit to the right of the prefix.
|
| 163 |
+
indent = " " * term_len(usage_prefix)
|
| 164 |
+
self.write(
|
| 165 |
+
wrap_text(
|
| 166 |
+
args,
|
| 167 |
+
text_width,
|
| 168 |
+
initial_indent=usage_prefix,
|
| 169 |
+
subsequent_indent=indent,
|
| 170 |
+
)
|
| 171 |
+
)
|
| 172 |
+
else:
|
| 173 |
+
# The prefix is too long, put the arguments on the next line.
|
| 174 |
+
self.write(usage_prefix)
|
| 175 |
+
self.write("\n")
|
| 176 |
+
indent = " " * (max(self.current_indent, term_len(prefix)) + 4)
|
| 177 |
+
self.write(
|
| 178 |
+
wrap_text(
|
| 179 |
+
args, text_width, initial_indent=indent, subsequent_indent=indent
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
self.write("\n")
|
| 184 |
+
|
| 185 |
+
def write_heading(self, heading: str) -> None:
|
| 186 |
+
"""Writes a heading into the buffer."""
|
| 187 |
+
self.write(f"{'':>{self.current_indent}}{heading}:\n")
|
| 188 |
+
|
| 189 |
+
def write_paragraph(self) -> None:
|
| 190 |
+
"""Writes a paragraph into the buffer."""
|
| 191 |
+
if self.buffer:
|
| 192 |
+
self.write("\n")
|
| 193 |
+
|
| 194 |
+
def write_text(self, text: str) -> None:
|
| 195 |
+
"""Writes re-indented text into the buffer. This rewraps and
|
| 196 |
+
preserves paragraphs.
|
| 197 |
+
"""
|
| 198 |
+
indent = " " * self.current_indent
|
| 199 |
+
self.write(
|
| 200 |
+
wrap_text(
|
| 201 |
+
text,
|
| 202 |
+
self.width,
|
| 203 |
+
initial_indent=indent,
|
| 204 |
+
subsequent_indent=indent,
|
| 205 |
+
preserve_paragraphs=True,
|
| 206 |
+
)
|
| 207 |
+
)
|
| 208 |
+
self.write("\n")
|
| 209 |
+
|
| 210 |
+
def write_dl(
|
| 211 |
+
self,
|
| 212 |
+
rows: cabc.Sequence[tuple[str, str]],
|
| 213 |
+
col_max: int = 30,
|
| 214 |
+
col_spacing: int = 2,
|
| 215 |
+
) -> None:
|
| 216 |
+
"""Writes a definition list into the buffer. This is how options
|
| 217 |
+
and commands are usually formatted.
|
| 218 |
+
|
| 219 |
+
:param rows: a list of two item tuples for the terms and values.
|
| 220 |
+
:param col_max: the maximum width of the first column.
|
| 221 |
+
:param col_spacing: the number of spaces between the first and
|
| 222 |
+
second column.
|
| 223 |
+
"""
|
| 224 |
+
rows = list(rows)
|
| 225 |
+
widths = measure_table(rows)
|
| 226 |
+
if len(widths) != 2:
|
| 227 |
+
raise TypeError("Expected two columns for definition list")
|
| 228 |
+
|
| 229 |
+
first_col = min(widths[0], col_max) + col_spacing
|
| 230 |
+
|
| 231 |
+
for first, second in iter_rows(rows, len(widths)):
|
| 232 |
+
self.write(f"{'':>{self.current_indent}}{first}")
|
| 233 |
+
if not second:
|
| 234 |
+
self.write("\n")
|
| 235 |
+
continue
|
| 236 |
+
if term_len(first) <= first_col - col_spacing:
|
| 237 |
+
self.write(" " * (first_col - term_len(first)))
|
| 238 |
+
else:
|
| 239 |
+
self.write("\n")
|
| 240 |
+
self.write(" " * (first_col + self.current_indent))
|
| 241 |
+
|
| 242 |
+
text_width = max(self.width - first_col - 2, 10)
|
| 243 |
+
wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)
|
| 244 |
+
lines = wrapped_text.splitlines()
|
| 245 |
+
|
| 246 |
+
if lines:
|
| 247 |
+
self.write(f"{lines[0]}\n")
|
| 248 |
+
|
| 249 |
+
for line in lines[1:]:
|
| 250 |
+
self.write(f"{'':>{first_col + self.current_indent}}{line}\n")
|
| 251 |
+
else:
|
| 252 |
+
self.write("\n")
|
| 253 |
+
|
| 254 |
+
@contextmanager
|
| 255 |
+
def section(self, name: str) -> cabc.Iterator[None]:
|
| 256 |
+
"""Helpful context manager that writes a paragraph, a heading,
|
| 257 |
+
and the indents.
|
| 258 |
+
|
| 259 |
+
:param name: the section name that is written as heading.
|
| 260 |
+
"""
|
| 261 |
+
self.write_paragraph()
|
| 262 |
+
self.write_heading(name)
|
| 263 |
+
self.indent()
|
| 264 |
+
try:
|
| 265 |
+
yield
|
| 266 |
+
finally:
|
| 267 |
+
self.dedent()
|
| 268 |
+
|
| 269 |
+
@contextmanager
|
| 270 |
+
def indentation(self) -> cabc.Iterator[None]:
|
| 271 |
+
"""A context manager that increases the indentation."""
|
| 272 |
+
self.indent()
|
| 273 |
+
try:
|
| 274 |
+
yield
|
| 275 |
+
finally:
|
| 276 |
+
self.dedent()
|
| 277 |
+
|
| 278 |
+
def getvalue(self) -> str:
|
| 279 |
+
"""Returns the buffer contents."""
|
| 280 |
+
return "".join(self.buffer)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]:
|
| 284 |
+
"""Given a list of option strings this joins them in the most appropriate
|
| 285 |
+
way and returns them in the form ``(formatted_string,
|
| 286 |
+
any_prefix_is_slash)`` where the second item in the tuple is a flag that
|
| 287 |
+
indicates if any of the option prefixes was a slash.
|
| 288 |
+
"""
|
| 289 |
+
rv = []
|
| 290 |
+
any_prefix_is_slash = False
|
| 291 |
+
|
| 292 |
+
for opt in options:
|
| 293 |
+
prefix = _split_opt(opt)[0]
|
| 294 |
+
|
| 295 |
+
if prefix == "/":
|
| 296 |
+
any_prefix_is_slash = True
|
| 297 |
+
|
| 298 |
+
rv.append((len(prefix), opt))
|
| 299 |
+
|
| 300 |
+
rv.sort(key=lambda x: x[0])
|
| 301 |
+
return ", ".join(x[1] for x in rv), any_prefix_is_slash
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/globals.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import typing as t
|
| 4 |
+
from threading import local
|
| 5 |
+
|
| 6 |
+
if t.TYPE_CHECKING:
|
| 7 |
+
from .core import Context
|
| 8 |
+
|
| 9 |
+
_local = local()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@t.overload
|
| 13 |
+
def get_current_context(silent: t.Literal[False] = False) -> Context: ...
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@t.overload
|
| 17 |
+
def get_current_context(silent: bool = ...) -> Context | None: ...
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_current_context(silent: bool = False) -> Context | None:
|
| 21 |
+
"""Returns the current click context. This can be used as a way to
|
| 22 |
+
access the current context object from anywhere. This is a more implicit
|
| 23 |
+
alternative to the :func:`pass_context` decorator. This function is
|
| 24 |
+
primarily useful for helpers such as :func:`echo` which might be
|
| 25 |
+
interested in changing its behavior based on the current context.
|
| 26 |
+
|
| 27 |
+
To push the current context, :meth:`Context.scope` can be used.
|
| 28 |
+
|
| 29 |
+
.. versionadded:: 5.0
|
| 30 |
+
|
| 31 |
+
:param silent: if set to `True` the return value is `None` if no context
|
| 32 |
+
is available. The default behavior is to raise a
|
| 33 |
+
:exc:`RuntimeError`.
|
| 34 |
+
"""
|
| 35 |
+
try:
|
| 36 |
+
return t.cast("Context", _local.stack[-1])
|
| 37 |
+
except (AttributeError, IndexError) as e:
|
| 38 |
+
if not silent:
|
| 39 |
+
raise RuntimeError("There is no active click context.") from e
|
| 40 |
+
|
| 41 |
+
return None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def push_context(ctx: Context) -> None:
|
| 45 |
+
"""Pushes a new context to the current stack."""
|
| 46 |
+
_local.__dict__.setdefault("stack", []).append(ctx)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def pop_context() -> None:
|
| 50 |
+
"""Removes the top level from the stack."""
|
| 51 |
+
_local.stack.pop()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def resolve_color_default(color: bool | None = None) -> bool | None:
|
| 55 |
+
"""Internal helper to get the default value of the color flag. If a
|
| 56 |
+
value is passed it's returned unchanged, otherwise it's looked up from
|
| 57 |
+
the current context.
|
| 58 |
+
"""
|
| 59 |
+
if color is not None:
|
| 60 |
+
return color
|
| 61 |
+
|
| 62 |
+
ctx = get_current_context(silent=True)
|
| 63 |
+
|
| 64 |
+
if ctx is not None:
|
| 65 |
+
return ctx.color
|
| 66 |
+
|
| 67 |
+
return None
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/parser.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module started out as largely a copy paste from the stdlib's
|
| 3 |
+
optparse module with the features removed that we do not need from
|
| 4 |
+
optparse because we implement them in Click on a higher level (for
|
| 5 |
+
instance type handling, help formatting and a lot more).
|
| 6 |
+
|
| 7 |
+
The plan is to remove more and more from here over time.
|
| 8 |
+
|
| 9 |
+
The reason this is a different module and not optparse from the stdlib
|
| 10 |
+
is that there are differences in 2.x and 3.x about the error messages
|
| 11 |
+
generated and optparse in the stdlib uses gettext for no good reason
|
| 12 |
+
and might cause us issues.
|
| 13 |
+
|
| 14 |
+
Click uses parts of optparse written by Gregory P. Ward and maintained
|
| 15 |
+
by the Python Software Foundation. This is limited to code in parser.py.
|
| 16 |
+
|
| 17 |
+
Copyright 2001-2006 Gregory P. Ward. All rights reserved.
|
| 18 |
+
Copyright 2002-2006 Python Software Foundation. All rights reserved.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
# This code uses parts of optparse written by Gregory P. Ward and
|
| 22 |
+
# maintained by the Python Software Foundation.
|
| 23 |
+
# Copyright 2001-2006 Gregory P. Ward
|
| 24 |
+
# Copyright 2002-2006 Python Software Foundation
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import collections.abc as cabc
|
| 28 |
+
import typing as t
|
| 29 |
+
from collections import deque
|
| 30 |
+
from gettext import gettext as _
|
| 31 |
+
from gettext import ngettext
|
| 32 |
+
|
| 33 |
+
from ._utils import FLAG_NEEDS_VALUE
|
| 34 |
+
from ._utils import UNSET
|
| 35 |
+
from .exceptions import BadArgumentUsage
|
| 36 |
+
from .exceptions import BadOptionUsage
|
| 37 |
+
from .exceptions import NoSuchOption
|
| 38 |
+
from .exceptions import UsageError
|
| 39 |
+
|
| 40 |
+
if t.TYPE_CHECKING:
|
| 41 |
+
from ._utils import T_FLAG_NEEDS_VALUE
|
| 42 |
+
from ._utils import T_UNSET
|
| 43 |
+
from .core import Argument as CoreArgument
|
| 44 |
+
from .core import Context
|
| 45 |
+
from .core import Option as CoreOption
|
| 46 |
+
from .core import Parameter as CoreParameter
|
| 47 |
+
|
| 48 |
+
V = t.TypeVar("V")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _unpack_args(
|
| 52 |
+
args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]
|
| 53 |
+
) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]:
|
| 54 |
+
"""Given an iterable of arguments and an iterable of nargs specifications,
|
| 55 |
+
it returns a tuple with all the unpacked arguments at the first index
|
| 56 |
+
and all remaining arguments as the second.
|
| 57 |
+
|
| 58 |
+
The nargs specification is the number of arguments that should be consumed
|
| 59 |
+
or `-1` to indicate that this position should eat up all the remainders.
|
| 60 |
+
|
| 61 |
+
Missing items are filled with ``UNSET``.
|
| 62 |
+
"""
|
| 63 |
+
args = deque(args)
|
| 64 |
+
nargs_spec = deque(nargs_spec)
|
| 65 |
+
rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []
|
| 66 |
+
spos: int | None = None
|
| 67 |
+
|
| 68 |
+
def _fetch(c: deque[V]) -> V | T_UNSET:
|
| 69 |
+
try:
|
| 70 |
+
if spos is None:
|
| 71 |
+
return c.popleft()
|
| 72 |
+
else:
|
| 73 |
+
return c.pop()
|
| 74 |
+
except IndexError:
|
| 75 |
+
return UNSET
|
| 76 |
+
|
| 77 |
+
while nargs_spec:
|
| 78 |
+
nargs = _fetch(nargs_spec)
|
| 79 |
+
|
| 80 |
+
if nargs is None:
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
if nargs == 1:
|
| 84 |
+
rv.append(_fetch(args)) # type: ignore[arg-type]
|
| 85 |
+
elif nargs > 1:
|
| 86 |
+
x = [_fetch(args) for _ in range(nargs)]
|
| 87 |
+
|
| 88 |
+
# If we're reversed, we're pulling in the arguments in reverse,
|
| 89 |
+
# so we need to turn them around.
|
| 90 |
+
if spos is not None:
|
| 91 |
+
x.reverse()
|
| 92 |
+
|
| 93 |
+
rv.append(tuple(x))
|
| 94 |
+
elif nargs < 0:
|
| 95 |
+
if spos is not None:
|
| 96 |
+
raise TypeError("Cannot have two nargs < 0")
|
| 97 |
+
|
| 98 |
+
spos = len(rv)
|
| 99 |
+
rv.append(UNSET)
|
| 100 |
+
|
| 101 |
+
# spos is the position of the wildcard (star). If it's not `None`,
|
| 102 |
+
# we fill it with the remainder.
|
| 103 |
+
if spos is not None:
|
| 104 |
+
rv[spos] = tuple(args)
|
| 105 |
+
args = []
|
| 106 |
+
rv[spos + 1 :] = reversed(rv[spos + 1 :])
|
| 107 |
+
|
| 108 |
+
return tuple(rv), list(args)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _split_opt(opt: str) -> tuple[str, str]:
|
| 112 |
+
first = opt[:1]
|
| 113 |
+
if first.isalnum():
|
| 114 |
+
return "", opt
|
| 115 |
+
if opt[1:2] == first:
|
| 116 |
+
return opt[:2], opt[2:]
|
| 117 |
+
return first, opt[1:]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _normalize_opt(opt: str, ctx: Context | None) -> str:
|
| 121 |
+
if ctx is None or ctx.token_normalize_func is None:
|
| 122 |
+
return opt
|
| 123 |
+
prefix, opt = _split_opt(opt)
|
| 124 |
+
return f"{prefix}{ctx.token_normalize_func(opt)}"
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class _Option:
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
obj: CoreOption,
|
| 131 |
+
opts: cabc.Sequence[str],
|
| 132 |
+
dest: str | None,
|
| 133 |
+
action: str | None = None,
|
| 134 |
+
nargs: int = 1,
|
| 135 |
+
const: t.Any | None = None,
|
| 136 |
+
):
|
| 137 |
+
self._short_opts = []
|
| 138 |
+
self._long_opts = []
|
| 139 |
+
self.prefixes: set[str] = set()
|
| 140 |
+
|
| 141 |
+
for opt in opts:
|
| 142 |
+
prefix, value = _split_opt(opt)
|
| 143 |
+
if not prefix:
|
| 144 |
+
raise ValueError(f"Invalid start character for option ({opt})")
|
| 145 |
+
self.prefixes.add(prefix[0])
|
| 146 |
+
if len(prefix) == 1 and len(value) == 1:
|
| 147 |
+
self._short_opts.append(opt)
|
| 148 |
+
else:
|
| 149 |
+
self._long_opts.append(opt)
|
| 150 |
+
self.prefixes.add(prefix)
|
| 151 |
+
|
| 152 |
+
if action is None:
|
| 153 |
+
action = "store"
|
| 154 |
+
|
| 155 |
+
self.dest = dest
|
| 156 |
+
self.action = action
|
| 157 |
+
self.nargs = nargs
|
| 158 |
+
self.const = const
|
| 159 |
+
self.obj = obj
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def takes_value(self) -> bool:
|
| 163 |
+
return self.action in ("store", "append")
|
| 164 |
+
|
| 165 |
+
def process(self, value: t.Any, state: _ParsingState) -> None:
|
| 166 |
+
if self.action == "store":
|
| 167 |
+
state.opts[self.dest] = value # type: ignore
|
| 168 |
+
elif self.action == "store_const":
|
| 169 |
+
state.opts[self.dest] = self.const # type: ignore
|
| 170 |
+
elif self.action == "append":
|
| 171 |
+
state.opts.setdefault(self.dest, []).append(value) # type: ignore
|
| 172 |
+
elif self.action == "append_const":
|
| 173 |
+
state.opts.setdefault(self.dest, []).append(self.const) # type: ignore
|
| 174 |
+
elif self.action == "count":
|
| 175 |
+
state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore
|
| 176 |
+
else:
|
| 177 |
+
raise ValueError(f"unknown action '{self.action}'")
|
| 178 |
+
state.order.append(self.obj)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class _Argument:
|
| 182 |
+
def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1):
|
| 183 |
+
self.dest = dest
|
| 184 |
+
self.nargs = nargs
|
| 185 |
+
self.obj = obj
|
| 186 |
+
|
| 187 |
+
def process(
|
| 188 |
+
self,
|
| 189 |
+
value: str | cabc.Sequence[str | None] | None | T_UNSET,
|
| 190 |
+
state: _ParsingState,
|
| 191 |
+
) -> None:
|
| 192 |
+
if self.nargs > 1:
|
| 193 |
+
assert isinstance(value, cabc.Sequence)
|
| 194 |
+
holes = sum(1 for x in value if x is UNSET)
|
| 195 |
+
if holes == len(value):
|
| 196 |
+
value = UNSET
|
| 197 |
+
elif holes != 0:
|
| 198 |
+
raise BadArgumentUsage(
|
| 199 |
+
_("Argument {name!r} takes {nargs} values.").format(
|
| 200 |
+
name=self.dest, nargs=self.nargs
|
| 201 |
+
)
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# We failed to collect any argument value so we consider the argument as unset.
|
| 205 |
+
if value == ():
|
| 206 |
+
value = UNSET
|
| 207 |
+
|
| 208 |
+
state.opts[self.dest] = value # type: ignore
|
| 209 |
+
state.order.append(self.obj)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class _ParsingState:
|
| 213 |
+
def __init__(self, rargs: list[str]) -> None:
|
| 214 |
+
self.opts: dict[str, t.Any] = {}
|
| 215 |
+
self.largs: list[str] = []
|
| 216 |
+
self.rargs = rargs
|
| 217 |
+
self.order: list[CoreParameter] = []
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class _OptionParser:
|
| 221 |
+
"""The option parser is an internal class that is ultimately used to
|
| 222 |
+
parse options and arguments. It's modelled after optparse and brings
|
| 223 |
+
a similar but vastly simplified API. It should generally not be used
|
| 224 |
+
directly as the high level Click classes wrap it for you.
|
| 225 |
+
|
| 226 |
+
It's not nearly as extensible as optparse or argparse as it does not
|
| 227 |
+
implement features that are implemented on a higher level (such as
|
| 228 |
+
types or defaults).
|
| 229 |
+
|
| 230 |
+
:param ctx: optionally the :class:`~click.Context` where this parser
|
| 231 |
+
should go with.
|
| 232 |
+
|
| 233 |
+
.. deprecated:: 8.2
|
| 234 |
+
Will be removed in Click 9.0.
|
| 235 |
+
"""
|
| 236 |
+
|
| 237 |
+
def __init__(self, ctx: Context | None = None) -> None:
|
| 238 |
+
#: The :class:`~click.Context` for this parser. This might be
|
| 239 |
+
#: `None` for some advanced use cases.
|
| 240 |
+
self.ctx = ctx
|
| 241 |
+
#: This controls how the parser deals with interspersed arguments.
|
| 242 |
+
#: If this is set to `False`, the parser will stop on the first
|
| 243 |
+
#: non-option. Click uses this to implement nested subcommands
|
| 244 |
+
#: safely.
|
| 245 |
+
self.allow_interspersed_args: bool = True
|
| 246 |
+
#: This tells the parser how to deal with unknown options. By
|
| 247 |
+
#: default it will error out (which is sensible), but there is a
|
| 248 |
+
#: second mode where it will ignore it and continue processing
|
| 249 |
+
#: after shifting all the unknown options into the resulting args.
|
| 250 |
+
self.ignore_unknown_options: bool = False
|
| 251 |
+
|
| 252 |
+
if ctx is not None:
|
| 253 |
+
self.allow_interspersed_args = ctx.allow_interspersed_args
|
| 254 |
+
self.ignore_unknown_options = ctx.ignore_unknown_options
|
| 255 |
+
|
| 256 |
+
self._short_opt: dict[str, _Option] = {}
|
| 257 |
+
self._long_opt: dict[str, _Option] = {}
|
| 258 |
+
self._opt_prefixes = {"-", "--"}
|
| 259 |
+
self._args: list[_Argument] = []
|
| 260 |
+
|
| 261 |
+
def add_option(
|
| 262 |
+
self,
|
| 263 |
+
obj: CoreOption,
|
| 264 |
+
opts: cabc.Sequence[str],
|
| 265 |
+
dest: str | None,
|
| 266 |
+
action: str | None = None,
|
| 267 |
+
nargs: int = 1,
|
| 268 |
+
const: t.Any | None = None,
|
| 269 |
+
) -> None:
|
| 270 |
+
"""Adds a new option named `dest` to the parser. The destination
|
| 271 |
+
is not inferred (unlike with optparse) and needs to be explicitly
|
| 272 |
+
provided. Action can be any of ``store``, ``store_const``,
|
| 273 |
+
``append``, ``append_const`` or ``count``.
|
| 274 |
+
|
| 275 |
+
The `obj` can be used to identify the option in the order list
|
| 276 |
+
that is returned from the parser.
|
| 277 |
+
"""
|
| 278 |
+
opts = [_normalize_opt(opt, self.ctx) for opt in opts]
|
| 279 |
+
option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const)
|
| 280 |
+
self._opt_prefixes.update(option.prefixes)
|
| 281 |
+
for opt in option._short_opts:
|
| 282 |
+
self._short_opt[opt] = option
|
| 283 |
+
for opt in option._long_opts:
|
| 284 |
+
self._long_opt[opt] = option
|
| 285 |
+
|
| 286 |
+
def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None:
|
| 287 |
+
"""Adds a positional argument named `dest` to the parser.
|
| 288 |
+
|
| 289 |
+
The `obj` can be used to identify the option in the order list
|
| 290 |
+
that is returned from the parser.
|
| 291 |
+
"""
|
| 292 |
+
self._args.append(_Argument(obj, dest=dest, nargs=nargs))
|
| 293 |
+
|
| 294 |
+
def parse_args(
|
| 295 |
+
self, args: list[str]
|
| 296 |
+
) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]:
|
| 297 |
+
"""Parses positional arguments and returns ``(values, args, order)``
|
| 298 |
+
for the parsed options and arguments as well as the leftover
|
| 299 |
+
arguments if there are any. The order is a list of objects as they
|
| 300 |
+
appear on the command line. If arguments appear multiple times they
|
| 301 |
+
will be memorized multiple times as well.
|
| 302 |
+
"""
|
| 303 |
+
state = _ParsingState(args)
|
| 304 |
+
try:
|
| 305 |
+
self._process_args_for_options(state)
|
| 306 |
+
self._process_args_for_args(state)
|
| 307 |
+
except UsageError:
|
| 308 |
+
if self.ctx is None or not self.ctx.resilient_parsing:
|
| 309 |
+
raise
|
| 310 |
+
return state.opts, state.largs, state.order
|
| 311 |
+
|
| 312 |
+
def _process_args_for_args(self, state: _ParsingState) -> None:
|
| 313 |
+
pargs, args = _unpack_args(
|
| 314 |
+
state.largs + state.rargs, [x.nargs for x in self._args]
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
for idx, arg in enumerate(self._args):
|
| 318 |
+
arg.process(pargs[idx], state)
|
| 319 |
+
|
| 320 |
+
state.largs = args
|
| 321 |
+
state.rargs = []
|
| 322 |
+
|
| 323 |
+
def _process_args_for_options(self, state: _ParsingState) -> None:
|
| 324 |
+
while state.rargs:
|
| 325 |
+
arg = state.rargs.pop(0)
|
| 326 |
+
arglen = len(arg)
|
| 327 |
+
# Double dashes always handled explicitly regardless of what
|
| 328 |
+
# prefixes are valid.
|
| 329 |
+
if arg == "--":
|
| 330 |
+
return
|
| 331 |
+
elif arg[:1] in self._opt_prefixes and arglen > 1:
|
| 332 |
+
self._process_opts(arg, state)
|
| 333 |
+
elif self.allow_interspersed_args:
|
| 334 |
+
state.largs.append(arg)
|
| 335 |
+
else:
|
| 336 |
+
state.rargs.insert(0, arg)
|
| 337 |
+
return
|
| 338 |
+
|
| 339 |
+
# Say this is the original argument list:
|
| 340 |
+
# [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
|
| 341 |
+
# ^
|
| 342 |
+
# (we are about to process arg(i)).
|
| 343 |
+
#
|
| 344 |
+
# Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
|
| 345 |
+
# [arg0, ..., arg(i-1)] (any options and their arguments will have
|
| 346 |
+
# been removed from largs).
|
| 347 |
+
#
|
| 348 |
+
# The while loop will usually consume 1 or more arguments per pass.
|
| 349 |
+
# If it consumes 1 (eg. arg is an option that takes no arguments),
|
| 350 |
+
# then after _process_arg() is done the situation is:
|
| 351 |
+
#
|
| 352 |
+
# largs = subset of [arg0, ..., arg(i)]
|
| 353 |
+
# rargs = [arg(i+1), ..., arg(N-1)]
|
| 354 |
+
#
|
| 355 |
+
# If allow_interspersed_args is false, largs will always be
|
| 356 |
+
# *empty* -- still a subset of [arg0, ..., arg(i-1)], but
|
| 357 |
+
# not a very interesting subset!
|
| 358 |
+
|
| 359 |
+
def _match_long_opt(
|
| 360 |
+
self, opt: str, explicit_value: str | None, state: _ParsingState
|
| 361 |
+
) -> None:
|
| 362 |
+
if opt not in self._long_opt:
|
| 363 |
+
from difflib import get_close_matches
|
| 364 |
+
|
| 365 |
+
possibilities = get_close_matches(opt, self._long_opt)
|
| 366 |
+
raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
|
| 367 |
+
|
| 368 |
+
option = self._long_opt[opt]
|
| 369 |
+
if option.takes_value:
|
| 370 |
+
# At this point it's safe to modify rargs by injecting the
|
| 371 |
+
# explicit value, because no exception is raised in this
|
| 372 |
+
# branch. This means that the inserted value will be fully
|
| 373 |
+
# consumed.
|
| 374 |
+
if explicit_value is not None:
|
| 375 |
+
state.rargs.insert(0, explicit_value)
|
| 376 |
+
|
| 377 |
+
value = self._get_value_from_state(opt, option, state)
|
| 378 |
+
|
| 379 |
+
elif explicit_value is not None:
|
| 380 |
+
raise BadOptionUsage(
|
| 381 |
+
opt, _("Option {name!r} does not take a value.").format(name=opt)
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
else:
|
| 385 |
+
value = UNSET
|
| 386 |
+
|
| 387 |
+
option.process(value, state)
|
| 388 |
+
|
| 389 |
+
def _match_short_opt(self, arg: str, state: _ParsingState) -> None:
|
| 390 |
+
stop = False
|
| 391 |
+
i = 1
|
| 392 |
+
prefix = arg[0]
|
| 393 |
+
unknown_options = []
|
| 394 |
+
|
| 395 |
+
for ch in arg[1:]:
|
| 396 |
+
opt = _normalize_opt(f"{prefix}{ch}", self.ctx)
|
| 397 |
+
option = self._short_opt.get(opt)
|
| 398 |
+
i += 1
|
| 399 |
+
|
| 400 |
+
if not option:
|
| 401 |
+
if self.ignore_unknown_options:
|
| 402 |
+
unknown_options.append(ch)
|
| 403 |
+
continue
|
| 404 |
+
raise NoSuchOption(opt, ctx=self.ctx)
|
| 405 |
+
if option.takes_value:
|
| 406 |
+
# Any characters left in arg? Pretend they're the
|
| 407 |
+
# next arg, and stop consuming characters of arg.
|
| 408 |
+
if i < len(arg):
|
| 409 |
+
state.rargs.insert(0, arg[i:])
|
| 410 |
+
stop = True
|
| 411 |
+
|
| 412 |
+
value = self._get_value_from_state(opt, option, state)
|
| 413 |
+
|
| 414 |
+
else:
|
| 415 |
+
value = UNSET
|
| 416 |
+
|
| 417 |
+
option.process(value, state)
|
| 418 |
+
|
| 419 |
+
if stop:
|
| 420 |
+
break
|
| 421 |
+
|
| 422 |
+
# If we got any unknown options we recombine the string of the
|
| 423 |
+
# remaining options and re-attach the prefix, then report that
|
| 424 |
+
# to the state as new larg. This way there is basic combinatorics
|
| 425 |
+
# that can be achieved while still ignoring unknown arguments.
|
| 426 |
+
if self.ignore_unknown_options and unknown_options:
|
| 427 |
+
state.largs.append(f"{prefix}{''.join(unknown_options)}")
|
| 428 |
+
|
| 429 |
+
def _get_value_from_state(
|
| 430 |
+
self, option_name: str, option: _Option, state: _ParsingState
|
| 431 |
+
) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE:
|
| 432 |
+
nargs = option.nargs
|
| 433 |
+
|
| 434 |
+
value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE
|
| 435 |
+
|
| 436 |
+
if len(state.rargs) < nargs:
|
| 437 |
+
if option.obj._flag_needs_value:
|
| 438 |
+
# Option allows omitting the value.
|
| 439 |
+
value = FLAG_NEEDS_VALUE
|
| 440 |
+
else:
|
| 441 |
+
raise BadOptionUsage(
|
| 442 |
+
option_name,
|
| 443 |
+
ngettext(
|
| 444 |
+
"Option {name!r} requires an argument.",
|
| 445 |
+
"Option {name!r} requires {nargs} arguments.",
|
| 446 |
+
nargs,
|
| 447 |
+
).format(name=option_name, nargs=nargs),
|
| 448 |
+
)
|
| 449 |
+
elif nargs == 1:
|
| 450 |
+
next_rarg = state.rargs[0]
|
| 451 |
+
|
| 452 |
+
if (
|
| 453 |
+
option.obj._flag_needs_value
|
| 454 |
+
and isinstance(next_rarg, str)
|
| 455 |
+
and next_rarg[:1] in self._opt_prefixes
|
| 456 |
+
and len(next_rarg) > 1
|
| 457 |
+
):
|
| 458 |
+
# The next arg looks like the start of an option, don't
|
| 459 |
+
# use it as the value if omitting the value is allowed.
|
| 460 |
+
value = FLAG_NEEDS_VALUE
|
| 461 |
+
else:
|
| 462 |
+
value = state.rargs.pop(0)
|
| 463 |
+
else:
|
| 464 |
+
value = tuple(state.rargs[:nargs])
|
| 465 |
+
del state.rargs[:nargs]
|
| 466 |
+
|
| 467 |
+
return value
|
| 468 |
+
|
| 469 |
+
def _process_opts(self, arg: str, state: _ParsingState) -> None:
|
| 470 |
+
explicit_value = None
|
| 471 |
+
# Long option handling happens in two parts. The first part is
|
| 472 |
+
# supporting explicitly attached values. In any case, we will try
|
| 473 |
+
# to long match the option first.
|
| 474 |
+
if "=" in arg:
|
| 475 |
+
long_opt, explicit_value = arg.split("=", 1)
|
| 476 |
+
else:
|
| 477 |
+
long_opt = arg
|
| 478 |
+
norm_long_opt = _normalize_opt(long_opt, self.ctx)
|
| 479 |
+
|
| 480 |
+
# At this point we will match the (assumed) long option through
|
| 481 |
+
# the long option matching code. Note that this allows options
|
| 482 |
+
# like "-foo" to be matched as long options.
|
| 483 |
+
try:
|
| 484 |
+
self._match_long_opt(norm_long_opt, explicit_value, state)
|
| 485 |
+
except NoSuchOption:
|
| 486 |
+
# At this point the long option matching failed, and we need
|
| 487 |
+
# to try with short options. However there is a special rule
|
| 488 |
+
# which says, that if we have a two character options prefix
|
| 489 |
+
# (applies to "--foo" for instance), we do not dispatch to the
|
| 490 |
+
# short option code and will instead raise the no option
|
| 491 |
+
# error.
|
| 492 |
+
if arg[:2] not in self._opt_prefixes:
|
| 493 |
+
self._match_short_opt(arg, state)
|
| 494 |
+
return
|
| 495 |
+
|
| 496 |
+
if not self.ignore_unknown_options:
|
| 497 |
+
raise
|
| 498 |
+
|
| 499 |
+
state.largs.append(arg)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def __getattr__(name: str) -> object:
|
| 503 |
+
import warnings
|
| 504 |
+
|
| 505 |
+
if name in {
|
| 506 |
+
"OptionParser",
|
| 507 |
+
"Argument",
|
| 508 |
+
"Option",
|
| 509 |
+
"split_opt",
|
| 510 |
+
"normalize_opt",
|
| 511 |
+
"ParsingState",
|
| 512 |
+
}:
|
| 513 |
+
warnings.warn(
|
| 514 |
+
f"'parser.{name}' is deprecated and will be removed in Click 9.0."
|
| 515 |
+
" The old parser is available in 'optparse'.",
|
| 516 |
+
DeprecationWarning,
|
| 517 |
+
stacklevel=2,
|
| 518 |
+
)
|
| 519 |
+
return globals()[f"_{name}"]
|
| 520 |
+
|
| 521 |
+
if name == "split_arg_string":
|
| 522 |
+
from .shell_completion import split_arg_string
|
| 523 |
+
|
| 524 |
+
warnings.warn(
|
| 525 |
+
"Importing 'parser.split_arg_string' is deprecated, it will only be"
|
| 526 |
+
" available in 'shell_completion' in Click 9.0.",
|
| 527 |
+
DeprecationWarning,
|
| 528 |
+
stacklevel=2,
|
| 529 |
+
)
|
| 530 |
+
return split_arg_string
|
| 531 |
+
|
| 532 |
+
raise AttributeError(name)
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/py.typed
ADDED
|
File without changes
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/shell_completion.py
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections.abc as cabc
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import typing as t
|
| 7 |
+
from gettext import gettext as _
|
| 8 |
+
|
| 9 |
+
from .core import Argument
|
| 10 |
+
from .core import Command
|
| 11 |
+
from .core import Context
|
| 12 |
+
from .core import Group
|
| 13 |
+
from .core import Option
|
| 14 |
+
from .core import Parameter
|
| 15 |
+
from .core import ParameterSource
|
| 16 |
+
from .utils import echo
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def shell_complete(
|
| 20 |
+
cli: Command,
|
| 21 |
+
ctx_args: cabc.MutableMapping[str, t.Any],
|
| 22 |
+
prog_name: str,
|
| 23 |
+
complete_var: str,
|
| 24 |
+
instruction: str,
|
| 25 |
+
) -> int:
|
| 26 |
+
"""Perform shell completion for the given CLI program.
|
| 27 |
+
|
| 28 |
+
:param cli: Command being called.
|
| 29 |
+
:param ctx_args: Extra arguments to pass to
|
| 30 |
+
``cli.make_context``.
|
| 31 |
+
:param prog_name: Name of the executable in the shell.
|
| 32 |
+
:param complete_var: Name of the environment variable that holds
|
| 33 |
+
the completion instruction.
|
| 34 |
+
:param instruction: Value of ``complete_var`` with the completion
|
| 35 |
+
instruction and shell, in the form ``instruction_shell``.
|
| 36 |
+
:return: Status code to exit with.
|
| 37 |
+
"""
|
| 38 |
+
shell, _, instruction = instruction.partition("_")
|
| 39 |
+
comp_cls = get_completion_class(shell)
|
| 40 |
+
|
| 41 |
+
if comp_cls is None:
|
| 42 |
+
return 1
|
| 43 |
+
|
| 44 |
+
comp = comp_cls(cli, ctx_args, prog_name, complete_var)
|
| 45 |
+
|
| 46 |
+
if instruction == "source":
|
| 47 |
+
echo(comp.source())
|
| 48 |
+
return 0
|
| 49 |
+
|
| 50 |
+
if instruction == "complete":
|
| 51 |
+
echo(comp.complete())
|
| 52 |
+
return 0
|
| 53 |
+
|
| 54 |
+
return 1
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class CompletionItem:
|
| 58 |
+
"""Represents a completion value and metadata about the value. The
|
| 59 |
+
default metadata is ``type`` to indicate special shell handling,
|
| 60 |
+
and ``help`` if a shell supports showing a help string next to the
|
| 61 |
+
value.
|
| 62 |
+
|
| 63 |
+
Arbitrary parameters can be passed when creating the object, and
|
| 64 |
+
accessed using ``item.attr``. If an attribute wasn't passed,
|
| 65 |
+
accessing it returns ``None``.
|
| 66 |
+
|
| 67 |
+
:param value: The completion suggestion.
|
| 68 |
+
:param type: Tells the shell script to provide special completion
|
| 69 |
+
support for the type. Click uses ``"dir"`` and ``"file"``.
|
| 70 |
+
:param help: String shown next to the value if supported.
|
| 71 |
+
:param kwargs: Arbitrary metadata. The built-in implementations
|
| 72 |
+
don't use this, but custom type completions paired with custom
|
| 73 |
+
shell support could use it.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
__slots__ = ("value", "type", "help", "_info")
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
value: t.Any,
|
| 81 |
+
type: str = "plain",
|
| 82 |
+
help: str | None = None,
|
| 83 |
+
**kwargs: t.Any,
|
| 84 |
+
) -> None:
|
| 85 |
+
self.value: t.Any = value
|
| 86 |
+
self.type: str = type
|
| 87 |
+
self.help: str | None = help
|
| 88 |
+
self._info = kwargs
|
| 89 |
+
|
| 90 |
+
def __getattr__(self, name: str) -> t.Any:
|
| 91 |
+
return self._info.get(name)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# Only Bash >= 4.4 has the nosort option.
|
| 95 |
+
_SOURCE_BASH = """\
|
| 96 |
+
%(complete_func)s() {
|
| 97 |
+
local IFS=$'\\n'
|
| 98 |
+
local response
|
| 99 |
+
|
| 100 |
+
response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
|
| 101 |
+
%(complete_var)s=bash_complete $1)
|
| 102 |
+
|
| 103 |
+
for completion in $response; do
|
| 104 |
+
IFS=',' read type value <<< "$completion"
|
| 105 |
+
|
| 106 |
+
if [[ $type == 'dir' ]]; then
|
| 107 |
+
COMPREPLY=()
|
| 108 |
+
compopt -o dirnames
|
| 109 |
+
elif [[ $type == 'file' ]]; then
|
| 110 |
+
COMPREPLY=()
|
| 111 |
+
compopt -o default
|
| 112 |
+
elif [[ $type == 'plain' ]]; then
|
| 113 |
+
COMPREPLY+=($value)
|
| 114 |
+
fi
|
| 115 |
+
done
|
| 116 |
+
|
| 117 |
+
return 0
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
%(complete_func)s_setup() {
|
| 121 |
+
complete -o nosort -F %(complete_func)s %(prog_name)s
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
%(complete_func)s_setup;
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
# See ZshComplete.format_completion below, and issue #2703, before
|
| 128 |
+
# changing this script.
|
| 129 |
+
#
|
| 130 |
+
# (TL;DR: _describe is picky about the format, but this Zsh script snippet
|
| 131 |
+
# is already widely deployed. So freeze this script, and use clever-ish
|
| 132 |
+
# handling of colons in ZshComplet.format_completion.)
|
| 133 |
+
_SOURCE_ZSH = """\
|
| 134 |
+
#compdef %(prog_name)s
|
| 135 |
+
|
| 136 |
+
%(complete_func)s() {
|
| 137 |
+
local -a completions
|
| 138 |
+
local -a completions_with_descriptions
|
| 139 |
+
local -a response
|
| 140 |
+
(( ! $+commands[%(prog_name)s] )) && return 1
|
| 141 |
+
|
| 142 |
+
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \
|
| 143 |
+
%(complete_var)s=zsh_complete %(prog_name)s)}")
|
| 144 |
+
|
| 145 |
+
for type key descr in ${response}; do
|
| 146 |
+
if [[ "$type" == "plain" ]]; then
|
| 147 |
+
if [[ "$descr" == "_" ]]; then
|
| 148 |
+
completions+=("$key")
|
| 149 |
+
else
|
| 150 |
+
completions_with_descriptions+=("$key":"$descr")
|
| 151 |
+
fi
|
| 152 |
+
elif [[ "$type" == "dir" ]]; then
|
| 153 |
+
_path_files -/
|
| 154 |
+
elif [[ "$type" == "file" ]]; then
|
| 155 |
+
_path_files -f
|
| 156 |
+
fi
|
| 157 |
+
done
|
| 158 |
+
|
| 159 |
+
if [ -n "$completions_with_descriptions" ]; then
|
| 160 |
+
_describe -V unsorted completions_with_descriptions -U
|
| 161 |
+
fi
|
| 162 |
+
|
| 163 |
+
if [ -n "$completions" ]; then
|
| 164 |
+
compadd -U -V unsorted -a completions
|
| 165 |
+
fi
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
|
| 169 |
+
# autoload from fpath, call function directly
|
| 170 |
+
%(complete_func)s "$@"
|
| 171 |
+
else
|
| 172 |
+
# eval/source/. command, register function for later
|
| 173 |
+
compdef %(complete_func)s %(prog_name)s
|
| 174 |
+
fi
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
_SOURCE_FISH = """\
|
| 178 |
+
function %(complete_func)s;
|
| 179 |
+
set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \
|
| 180 |
+
COMP_CWORD=(commandline -t) %(prog_name)s);
|
| 181 |
+
|
| 182 |
+
for completion in $response;
|
| 183 |
+
set -l metadata (string split "," $completion);
|
| 184 |
+
|
| 185 |
+
if test $metadata[1] = "dir";
|
| 186 |
+
__fish_complete_directories $metadata[2];
|
| 187 |
+
else if test $metadata[1] = "file";
|
| 188 |
+
__fish_complete_path $metadata[2];
|
| 189 |
+
else if test $metadata[1] = "plain";
|
| 190 |
+
echo $metadata[2];
|
| 191 |
+
end;
|
| 192 |
+
end;
|
| 193 |
+
end;
|
| 194 |
+
|
| 195 |
+
complete --no-files --command %(prog_name)s --arguments \
|
| 196 |
+
"(%(complete_func)s)";
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class ShellComplete:
|
| 201 |
+
"""Base class for providing shell completion support. A subclass for
|
| 202 |
+
a given shell will override attributes and methods to implement the
|
| 203 |
+
completion instructions (``source`` and ``complete``).
|
| 204 |
+
|
| 205 |
+
:param cli: Command being called.
|
| 206 |
+
:param prog_name: Name of the executable in the shell.
|
| 207 |
+
:param complete_var: Name of the environment variable that holds
|
| 208 |
+
the completion instruction.
|
| 209 |
+
|
| 210 |
+
.. versionadded:: 8.0
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
name: t.ClassVar[str]
|
| 214 |
+
"""Name to register the shell as with :func:`add_completion_class`.
|
| 215 |
+
This is used in completion instructions (``{name}_source`` and
|
| 216 |
+
``{name}_complete``).
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
source_template: t.ClassVar[str]
|
| 220 |
+
"""Completion script template formatted by :meth:`source`. This must
|
| 221 |
+
be provided by subclasses.
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
def __init__(
|
| 225 |
+
self,
|
| 226 |
+
cli: Command,
|
| 227 |
+
ctx_args: cabc.MutableMapping[str, t.Any],
|
| 228 |
+
prog_name: str,
|
| 229 |
+
complete_var: str,
|
| 230 |
+
) -> None:
|
| 231 |
+
self.cli = cli
|
| 232 |
+
self.ctx_args = ctx_args
|
| 233 |
+
self.prog_name = prog_name
|
| 234 |
+
self.complete_var = complete_var
|
| 235 |
+
|
| 236 |
+
@property
|
| 237 |
+
def func_name(self) -> str:
|
| 238 |
+
"""The name of the shell function defined by the completion
|
| 239 |
+
script.
|
| 240 |
+
"""
|
| 241 |
+
safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)
|
| 242 |
+
return f"_{safe_name}_completion"
|
| 243 |
+
|
| 244 |
+
def source_vars(self) -> dict[str, t.Any]:
|
| 245 |
+
"""Vars for formatting :attr:`source_template`.
|
| 246 |
+
|
| 247 |
+
By default this provides ``complete_func``, ``complete_var``,
|
| 248 |
+
and ``prog_name``.
|
| 249 |
+
"""
|
| 250 |
+
return {
|
| 251 |
+
"complete_func": self.func_name,
|
| 252 |
+
"complete_var": self.complete_var,
|
| 253 |
+
"prog_name": self.prog_name,
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
def source(self) -> str:
|
| 257 |
+
"""Produce the shell script that defines the completion
|
| 258 |
+
function. By default this ``%``-style formats
|
| 259 |
+
:attr:`source_template` with the dict returned by
|
| 260 |
+
:meth:`source_vars`.
|
| 261 |
+
"""
|
| 262 |
+
return self.source_template % self.source_vars()
|
| 263 |
+
|
| 264 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 265 |
+
"""Use the env vars defined by the shell script to return a
|
| 266 |
+
tuple of ``args, incomplete``. This must be implemented by
|
| 267 |
+
subclasses.
|
| 268 |
+
"""
|
| 269 |
+
raise NotImplementedError
|
| 270 |
+
|
| 271 |
+
def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:
|
| 272 |
+
"""Determine the context and last complete command or parameter
|
| 273 |
+
from the complete args. Call that object's ``shell_complete``
|
| 274 |
+
method to get the completions for the incomplete value.
|
| 275 |
+
|
| 276 |
+
:param args: List of complete args before the incomplete value.
|
| 277 |
+
:param incomplete: Value being completed. May be empty.
|
| 278 |
+
"""
|
| 279 |
+
ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)
|
| 280 |
+
obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
|
| 281 |
+
return obj.shell_complete(ctx, incomplete)
|
| 282 |
+
|
| 283 |
+
def format_completion(self, item: CompletionItem) -> str:
|
| 284 |
+
"""Format a completion item into the form recognized by the
|
| 285 |
+
shell script. This must be implemented by subclasses.
|
| 286 |
+
|
| 287 |
+
:param item: Completion item to format.
|
| 288 |
+
"""
|
| 289 |
+
raise NotImplementedError
|
| 290 |
+
|
| 291 |
+
def complete(self) -> str:
|
| 292 |
+
"""Produce the completion data to send back to the shell.
|
| 293 |
+
|
| 294 |
+
By default this calls :meth:`get_completion_args`, gets the
|
| 295 |
+
completions, then calls :meth:`format_completion` for each
|
| 296 |
+
completion.
|
| 297 |
+
"""
|
| 298 |
+
args, incomplete = self.get_completion_args()
|
| 299 |
+
completions = self.get_completions(args, incomplete)
|
| 300 |
+
out = [self.format_completion(item) for item in completions]
|
| 301 |
+
return "\n".join(out)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class BashComplete(ShellComplete):
|
| 305 |
+
"""Shell completion for Bash."""
|
| 306 |
+
|
| 307 |
+
name = "bash"
|
| 308 |
+
source_template = _SOURCE_BASH
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def _check_version() -> None:
|
| 312 |
+
import shutil
|
| 313 |
+
import subprocess
|
| 314 |
+
|
| 315 |
+
bash_exe = shutil.which("bash")
|
| 316 |
+
|
| 317 |
+
if bash_exe is None:
|
| 318 |
+
match = None
|
| 319 |
+
else:
|
| 320 |
+
output = subprocess.run(
|
| 321 |
+
[bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],
|
| 322 |
+
stdout=subprocess.PIPE,
|
| 323 |
+
)
|
| 324 |
+
match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
|
| 325 |
+
|
| 326 |
+
if match is not None:
|
| 327 |
+
major, minor = match.groups()
|
| 328 |
+
|
| 329 |
+
if major < "4" or major == "4" and minor < "4":
|
| 330 |
+
echo(
|
| 331 |
+
_(
|
| 332 |
+
"Shell completion is not supported for Bash"
|
| 333 |
+
" versions older than 4.4."
|
| 334 |
+
),
|
| 335 |
+
err=True,
|
| 336 |
+
)
|
| 337 |
+
else:
|
| 338 |
+
echo(
|
| 339 |
+
_("Couldn't detect Bash version, shell completion is not supported."),
|
| 340 |
+
err=True,
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
def source(self) -> str:
|
| 344 |
+
self._check_version()
|
| 345 |
+
return super().source()
|
| 346 |
+
|
| 347 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 348 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
| 349 |
+
cword = int(os.environ["COMP_CWORD"])
|
| 350 |
+
args = cwords[1:cword]
|
| 351 |
+
|
| 352 |
+
try:
|
| 353 |
+
incomplete = cwords[cword]
|
| 354 |
+
except IndexError:
|
| 355 |
+
incomplete = ""
|
| 356 |
+
|
| 357 |
+
return args, incomplete
|
| 358 |
+
|
| 359 |
+
def format_completion(self, item: CompletionItem) -> str:
|
| 360 |
+
return f"{item.type},{item.value}"
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class ZshComplete(ShellComplete):
|
| 364 |
+
"""Shell completion for Zsh."""
|
| 365 |
+
|
| 366 |
+
name = "zsh"
|
| 367 |
+
source_template = _SOURCE_ZSH
|
| 368 |
+
|
| 369 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 370 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
| 371 |
+
cword = int(os.environ["COMP_CWORD"])
|
| 372 |
+
args = cwords[1:cword]
|
| 373 |
+
|
| 374 |
+
try:
|
| 375 |
+
incomplete = cwords[cword]
|
| 376 |
+
except IndexError:
|
| 377 |
+
incomplete = ""
|
| 378 |
+
|
| 379 |
+
return args, incomplete
|
| 380 |
+
|
| 381 |
+
def format_completion(self, item: CompletionItem) -> str:
|
| 382 |
+
help_ = item.help or "_"
|
| 383 |
+
# The zsh completion script uses `_describe` on items with help
|
| 384 |
+
# texts (which splits the item help from the item value at the
|
| 385 |
+
# first unescaped colon) and `compadd` on items without help
|
| 386 |
+
# text (which uses the item value as-is and does not support
|
| 387 |
+
# colon escaping). So escape colons in the item value if and
|
| 388 |
+
# only if the item help is not the sentinel "_" value, as used
|
| 389 |
+
# by the completion script.
|
| 390 |
+
#
|
| 391 |
+
# (The zsh completion script is potentially widely deployed, and
|
| 392 |
+
# thus harder to fix than this method.)
|
| 393 |
+
#
|
| 394 |
+
# See issue #1812 and issue #2703 for further context.
|
| 395 |
+
value = item.value.replace(":", r"\:") if help_ != "_" else item.value
|
| 396 |
+
return f"{item.type}\n{value}\n{help_}"
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class FishComplete(ShellComplete):
|
| 400 |
+
"""Shell completion for Fish."""
|
| 401 |
+
|
| 402 |
+
name = "fish"
|
| 403 |
+
source_template = _SOURCE_FISH
|
| 404 |
+
|
| 405 |
+
def get_completion_args(self) -> tuple[list[str], str]:
|
| 406 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
| 407 |
+
incomplete = os.environ["COMP_CWORD"]
|
| 408 |
+
if incomplete:
|
| 409 |
+
incomplete = split_arg_string(incomplete)[0]
|
| 410 |
+
args = cwords[1:]
|
| 411 |
+
|
| 412 |
+
# Fish stores the partial word in both COMP_WORDS and
|
| 413 |
+
# COMP_CWORD, remove it from complete args.
|
| 414 |
+
if incomplete and args and args[-1] == incomplete:
|
| 415 |
+
args.pop()
|
| 416 |
+
|
| 417 |
+
return args, incomplete
|
| 418 |
+
|
| 419 |
+
def format_completion(self, item: CompletionItem) -> str:
|
| 420 |
+
if item.help:
|
| 421 |
+
return f"{item.type},{item.value}\t{item.help}"
|
| 422 |
+
|
| 423 |
+
return f"{item.type},{item.value}"
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
_available_shells: dict[str, type[ShellComplete]] = {
|
| 430 |
+
"bash": BashComplete,
|
| 431 |
+
"fish": FishComplete,
|
| 432 |
+
"zsh": ZshComplete,
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def add_completion_class(
|
| 437 |
+
cls: ShellCompleteType, name: str | None = None
|
| 438 |
+
) -> ShellCompleteType:
|
| 439 |
+
"""Register a :class:`ShellComplete` subclass under the given name.
|
| 440 |
+
The name will be provided by the completion instruction environment
|
| 441 |
+
variable during completion.
|
| 442 |
+
|
| 443 |
+
:param cls: The completion class that will handle completion for the
|
| 444 |
+
shell.
|
| 445 |
+
:param name: Name to register the class under. Defaults to the
|
| 446 |
+
class's ``name`` attribute.
|
| 447 |
+
"""
|
| 448 |
+
if name is None:
|
| 449 |
+
name = cls.name
|
| 450 |
+
|
| 451 |
+
_available_shells[name] = cls
|
| 452 |
+
|
| 453 |
+
return cls
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def get_completion_class(shell: str) -> type[ShellComplete] | None:
|
| 457 |
+
"""Look up a registered :class:`ShellComplete` subclass by the name
|
| 458 |
+
provided by the completion instruction environment variable. If the
|
| 459 |
+
name isn't registered, returns ``None``.
|
| 460 |
+
|
| 461 |
+
:param shell: Name the class is registered under.
|
| 462 |
+
"""
|
| 463 |
+
return _available_shells.get(shell)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def split_arg_string(string: str) -> list[str]:
|
| 467 |
+
"""Split an argument string as with :func:`shlex.split`, but don't
|
| 468 |
+
fail if the string is incomplete. Ignores a missing closing quote or
|
| 469 |
+
incomplete escape sequence and uses the partial token as-is.
|
| 470 |
+
|
| 471 |
+
.. code-block:: python
|
| 472 |
+
|
| 473 |
+
split_arg_string("example 'my file")
|
| 474 |
+
["example", "my file"]
|
| 475 |
+
|
| 476 |
+
split_arg_string("example my\\")
|
| 477 |
+
["example", "my"]
|
| 478 |
+
|
| 479 |
+
:param string: String to split.
|
| 480 |
+
|
| 481 |
+
.. versionchanged:: 8.2
|
| 482 |
+
Moved to ``shell_completion`` from ``parser``.
|
| 483 |
+
"""
|
| 484 |
+
import shlex
|
| 485 |
+
|
| 486 |
+
lex = shlex.shlex(string, posix=True)
|
| 487 |
+
lex.whitespace_split = True
|
| 488 |
+
lex.commenters = ""
|
| 489 |
+
out = []
|
| 490 |
+
|
| 491 |
+
try:
|
| 492 |
+
for token in lex:
|
| 493 |
+
out.append(token)
|
| 494 |
+
except ValueError:
|
| 495 |
+
# Raised when end-of-string is reached in an invalid state. Use
|
| 496 |
+
# the partial token as-is. The quote or escape character is in
|
| 497 |
+
# lex.state, not lex.token.
|
| 498 |
+
out.append(lex.token)
|
| 499 |
+
|
| 500 |
+
return out
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:
|
| 504 |
+
"""Determine if the given parameter is an argument that can still
|
| 505 |
+
accept values.
|
| 506 |
+
|
| 507 |
+
:param ctx: Invocation context for the command represented by the
|
| 508 |
+
parsed complete args.
|
| 509 |
+
:param param: Argument object being checked.
|
| 510 |
+
"""
|
| 511 |
+
if not isinstance(param, Argument):
|
| 512 |
+
return False
|
| 513 |
+
|
| 514 |
+
assert param.name is not None
|
| 515 |
+
# Will be None if expose_value is False.
|
| 516 |
+
value = ctx.params.get(param.name)
|
| 517 |
+
return (
|
| 518 |
+
param.nargs == -1
|
| 519 |
+
or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
|
| 520 |
+
or (
|
| 521 |
+
param.nargs > 1
|
| 522 |
+
and isinstance(value, (tuple, list))
|
| 523 |
+
and len(value) < param.nargs
|
| 524 |
+
)
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _start_of_option(ctx: Context, value: str) -> bool:
|
| 529 |
+
"""Check if the value looks like the start of an option."""
|
| 530 |
+
if not value:
|
| 531 |
+
return False
|
| 532 |
+
|
| 533 |
+
c = value[0]
|
| 534 |
+
return c in ctx._opt_prefixes
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:
|
| 538 |
+
"""Determine if the given parameter is an option that needs a value.
|
| 539 |
+
|
| 540 |
+
:param args: List of complete args before the incomplete value.
|
| 541 |
+
:param param: Option object being checked.
|
| 542 |
+
"""
|
| 543 |
+
if not isinstance(param, Option):
|
| 544 |
+
return False
|
| 545 |
+
|
| 546 |
+
if param.is_flag or param.count:
|
| 547 |
+
return False
|
| 548 |
+
|
| 549 |
+
last_option = None
|
| 550 |
+
|
| 551 |
+
for index, arg in enumerate(reversed(args)):
|
| 552 |
+
if index + 1 > param.nargs:
|
| 553 |
+
break
|
| 554 |
+
|
| 555 |
+
if _start_of_option(ctx, arg):
|
| 556 |
+
last_option = arg
|
| 557 |
+
break
|
| 558 |
+
|
| 559 |
+
return last_option is not None and last_option in param.opts
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _resolve_context(
|
| 563 |
+
cli: Command,
|
| 564 |
+
ctx_args: cabc.MutableMapping[str, t.Any],
|
| 565 |
+
prog_name: str,
|
| 566 |
+
args: list[str],
|
| 567 |
+
) -> Context:
|
| 568 |
+
"""Produce the context hierarchy starting with the command and
|
| 569 |
+
traversing the complete arguments. This only follows the commands,
|
| 570 |
+
it doesn't trigger input prompts or callbacks.
|
| 571 |
+
|
| 572 |
+
:param cli: Command being called.
|
| 573 |
+
:param prog_name: Name of the executable in the shell.
|
| 574 |
+
:param args: List of complete args before the incomplete value.
|
| 575 |
+
"""
|
| 576 |
+
ctx_args["resilient_parsing"] = True
|
| 577 |
+
with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx:
|
| 578 |
+
args = ctx._protected_args + ctx.args
|
| 579 |
+
|
| 580 |
+
while args:
|
| 581 |
+
command = ctx.command
|
| 582 |
+
|
| 583 |
+
if isinstance(command, Group):
|
| 584 |
+
if not command.chain:
|
| 585 |
+
name, cmd, args = command.resolve_command(ctx, args)
|
| 586 |
+
|
| 587 |
+
if cmd is None:
|
| 588 |
+
return ctx
|
| 589 |
+
|
| 590 |
+
with cmd.make_context(
|
| 591 |
+
name, args, parent=ctx, resilient_parsing=True
|
| 592 |
+
) as sub_ctx:
|
| 593 |
+
ctx = sub_ctx
|
| 594 |
+
args = ctx._protected_args + ctx.args
|
| 595 |
+
else:
|
| 596 |
+
sub_ctx = ctx
|
| 597 |
+
|
| 598 |
+
while args:
|
| 599 |
+
name, cmd, args = command.resolve_command(ctx, args)
|
| 600 |
+
|
| 601 |
+
if cmd is None:
|
| 602 |
+
return ctx
|
| 603 |
+
|
| 604 |
+
with cmd.make_context(
|
| 605 |
+
name,
|
| 606 |
+
args,
|
| 607 |
+
parent=ctx,
|
| 608 |
+
allow_extra_args=True,
|
| 609 |
+
allow_interspersed_args=False,
|
| 610 |
+
resilient_parsing=True,
|
| 611 |
+
) as sub_sub_ctx:
|
| 612 |
+
sub_ctx = sub_sub_ctx
|
| 613 |
+
args = sub_ctx.args
|
| 614 |
+
|
| 615 |
+
ctx = sub_ctx
|
| 616 |
+
args = [*sub_ctx._protected_args, *sub_ctx.args]
|
| 617 |
+
else:
|
| 618 |
+
break
|
| 619 |
+
|
| 620 |
+
return ctx
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def _resolve_incomplete(
|
| 624 |
+
ctx: Context, args: list[str], incomplete: str
|
| 625 |
+
) -> tuple[Command | Parameter, str]:
|
| 626 |
+
"""Find the Click object that will handle the completion of the
|
| 627 |
+
incomplete value. Return the object and the incomplete value.
|
| 628 |
+
|
| 629 |
+
:param ctx: Invocation context for the command represented by
|
| 630 |
+
the parsed complete args.
|
| 631 |
+
:param args: List of complete args before the incomplete value.
|
| 632 |
+
:param incomplete: Value being completed. May be empty.
|
| 633 |
+
"""
|
| 634 |
+
# Different shells treat an "=" between a long option name and
|
| 635 |
+
# value differently. Might keep the value joined, return the "="
|
| 636 |
+
# as a separate item, or return the split name and value. Always
|
| 637 |
+
# split and discard the "=" to make completion easier.
|
| 638 |
+
if incomplete == "=":
|
| 639 |
+
incomplete = ""
|
| 640 |
+
elif "=" in incomplete and _start_of_option(ctx, incomplete):
|
| 641 |
+
name, _, incomplete = incomplete.partition("=")
|
| 642 |
+
args.append(name)
|
| 643 |
+
|
| 644 |
+
# The "--" marker tells Click to stop treating values as options
|
| 645 |
+
# even if they start with the option character. If it hasn't been
|
| 646 |
+
# given and the incomplete arg looks like an option, the current
|
| 647 |
+
# command will provide option name completions.
|
| 648 |
+
if "--" not in args and _start_of_option(ctx, incomplete):
|
| 649 |
+
return ctx.command, incomplete
|
| 650 |
+
|
| 651 |
+
params = ctx.command.get_params(ctx)
|
| 652 |
+
|
| 653 |
+
# If the last complete arg is an option name with an incomplete
|
| 654 |
+
# value, the option will provide value completions.
|
| 655 |
+
for param in params:
|
| 656 |
+
if _is_incomplete_option(ctx, args, param):
|
| 657 |
+
return param, incomplete
|
| 658 |
+
|
| 659 |
+
# It's not an option name or value. The first argument without a
|
| 660 |
+
# parsed value will provide value completions.
|
| 661 |
+
for param in params:
|
| 662 |
+
if _is_incomplete_argument(ctx, param):
|
| 663 |
+
return param, incomplete
|
| 664 |
+
|
| 665 |
+
# There were no unparsed arguments, the command may be a group that
|
| 666 |
+
# will provide command name completions.
|
| 667 |
+
return ctx.command, incomplete
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/termui.py
ADDED
|
@@ -0,0 +1,883 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
import inspect
|
| 5 |
+
import io
|
| 6 |
+
import itertools
|
| 7 |
+
import sys
|
| 8 |
+
import typing as t
|
| 9 |
+
from contextlib import AbstractContextManager
|
| 10 |
+
from gettext import gettext as _
|
| 11 |
+
|
| 12 |
+
from ._compat import isatty
|
| 13 |
+
from ._compat import strip_ansi
|
| 14 |
+
from .exceptions import Abort
|
| 15 |
+
from .exceptions import UsageError
|
| 16 |
+
from .globals import resolve_color_default
|
| 17 |
+
from .types import Choice
|
| 18 |
+
from .types import convert_type
|
| 19 |
+
from .types import ParamType
|
| 20 |
+
from .utils import echo
|
| 21 |
+
from .utils import LazyFile
|
| 22 |
+
|
| 23 |
+
if t.TYPE_CHECKING:
|
| 24 |
+
from ._termui_impl import ProgressBar
|
| 25 |
+
|
| 26 |
+
V = t.TypeVar("V")
|
| 27 |
+
|
| 28 |
+
# The prompt functions to use. The doc tools currently override these
|
| 29 |
+
# functions to customize how they work.
|
| 30 |
+
visible_prompt_func: t.Callable[[str], str] = input
|
| 31 |
+
|
| 32 |
+
_ansi_colors = {
|
| 33 |
+
"black": 30,
|
| 34 |
+
"red": 31,
|
| 35 |
+
"green": 32,
|
| 36 |
+
"yellow": 33,
|
| 37 |
+
"blue": 34,
|
| 38 |
+
"magenta": 35,
|
| 39 |
+
"cyan": 36,
|
| 40 |
+
"white": 37,
|
| 41 |
+
"reset": 39,
|
| 42 |
+
"bright_black": 90,
|
| 43 |
+
"bright_red": 91,
|
| 44 |
+
"bright_green": 92,
|
| 45 |
+
"bright_yellow": 93,
|
| 46 |
+
"bright_blue": 94,
|
| 47 |
+
"bright_magenta": 95,
|
| 48 |
+
"bright_cyan": 96,
|
| 49 |
+
"bright_white": 97,
|
| 50 |
+
}
|
| 51 |
+
_ansi_reset_all = "\033[0m"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def hidden_prompt_func(prompt: str) -> str:
|
| 55 |
+
import getpass
|
| 56 |
+
|
| 57 |
+
return getpass.getpass(prompt)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _build_prompt(
|
| 61 |
+
text: str,
|
| 62 |
+
suffix: str,
|
| 63 |
+
show_default: bool = False,
|
| 64 |
+
default: t.Any | None = None,
|
| 65 |
+
show_choices: bool = True,
|
| 66 |
+
type: ParamType | None = None,
|
| 67 |
+
) -> str:
|
| 68 |
+
prompt = text
|
| 69 |
+
if type is not None and show_choices and isinstance(type, Choice):
|
| 70 |
+
prompt += f" ({', '.join(map(str, type.choices))})"
|
| 71 |
+
if default is not None and show_default:
|
| 72 |
+
prompt = f"{prompt} [{_format_default(default)}]"
|
| 73 |
+
return f"{prompt}{suffix}"
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _format_default(default: t.Any) -> t.Any:
|
| 77 |
+
if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
|
| 78 |
+
return default.name
|
| 79 |
+
|
| 80 |
+
return default
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def prompt(
|
| 84 |
+
text: str,
|
| 85 |
+
default: t.Any | None = None,
|
| 86 |
+
hide_input: bool = False,
|
| 87 |
+
confirmation_prompt: bool | str = False,
|
| 88 |
+
type: ParamType | t.Any | None = None,
|
| 89 |
+
value_proc: t.Callable[[str], t.Any] | None = None,
|
| 90 |
+
prompt_suffix: str = ": ",
|
| 91 |
+
show_default: bool = True,
|
| 92 |
+
err: bool = False,
|
| 93 |
+
show_choices: bool = True,
|
| 94 |
+
) -> t.Any:
|
| 95 |
+
"""Prompts a user for input. This is a convenience function that can
|
| 96 |
+
be used to prompt a user for input later.
|
| 97 |
+
|
| 98 |
+
If the user aborts the input by sending an interrupt signal, this
|
| 99 |
+
function will catch it and raise a :exc:`Abort` exception.
|
| 100 |
+
|
| 101 |
+
:param text: the text to show for the prompt.
|
| 102 |
+
:param default: the default value to use if no input happens. If this
|
| 103 |
+
is not given it will prompt until it's aborted.
|
| 104 |
+
:param hide_input: if this is set to true then the input value will
|
| 105 |
+
be hidden.
|
| 106 |
+
:param confirmation_prompt: Prompt a second time to confirm the
|
| 107 |
+
value. Can be set to a string instead of ``True`` to customize
|
| 108 |
+
the message.
|
| 109 |
+
:param type: the type to use to check the value against.
|
| 110 |
+
:param value_proc: if this parameter is provided it's a function that
|
| 111 |
+
is invoked instead of the type conversion to
|
| 112 |
+
convert a value.
|
| 113 |
+
:param prompt_suffix: a suffix that should be added to the prompt.
|
| 114 |
+
:param show_default: shows or hides the default value in the prompt.
|
| 115 |
+
:param err: if set to true the file defaults to ``stderr`` instead of
|
| 116 |
+
``stdout``, the same as with echo.
|
| 117 |
+
:param show_choices: Show or hide choices if the passed type is a Choice.
|
| 118 |
+
For example if type is a Choice of either day or week,
|
| 119 |
+
show_choices is true and text is "Group by" then the
|
| 120 |
+
prompt will be "Group by (day, week): ".
|
| 121 |
+
|
| 122 |
+
.. versionchanged:: 8.3.1
|
| 123 |
+
A space is no longer appended to the prompt.
|
| 124 |
+
|
| 125 |
+
.. versionadded:: 8.0
|
| 126 |
+
``confirmation_prompt`` can be a custom string.
|
| 127 |
+
|
| 128 |
+
.. versionadded:: 7.0
|
| 129 |
+
Added the ``show_choices`` parameter.
|
| 130 |
+
|
| 131 |
+
.. versionadded:: 6.0
|
| 132 |
+
Added unicode support for cmd.exe on Windows.
|
| 133 |
+
|
| 134 |
+
.. versionadded:: 4.0
|
| 135 |
+
Added the `err` parameter.
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def prompt_func(text: str) -> str:
|
| 140 |
+
f = hidden_prompt_func if hide_input else visible_prompt_func
|
| 141 |
+
try:
|
| 142 |
+
# Write the prompt separately so that we get nice
|
| 143 |
+
# coloring through colorama on Windows
|
| 144 |
+
echo(text[:-1], nl=False, err=err)
|
| 145 |
+
# Echo the last character to stdout to work around an issue where
|
| 146 |
+
# readline causes backspace to clear the whole line.
|
| 147 |
+
return f(text[-1:])
|
| 148 |
+
except (KeyboardInterrupt, EOFError):
|
| 149 |
+
# getpass doesn't print a newline if the user aborts input with ^C.
|
| 150 |
+
# Allegedly this behavior is inherited from getpass(3).
|
| 151 |
+
# A doc bug has been filed at https://bugs.python.org/issue24711
|
| 152 |
+
if hide_input:
|
| 153 |
+
echo(None, err=err)
|
| 154 |
+
raise Abort() from None
|
| 155 |
+
|
| 156 |
+
if value_proc is None:
|
| 157 |
+
value_proc = convert_type(type, default)
|
| 158 |
+
|
| 159 |
+
prompt = _build_prompt(
|
| 160 |
+
text, prompt_suffix, show_default, default, show_choices, type
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
if confirmation_prompt:
|
| 164 |
+
if confirmation_prompt is True:
|
| 165 |
+
confirmation_prompt = _("Repeat for confirmation")
|
| 166 |
+
|
| 167 |
+
confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
|
| 168 |
+
|
| 169 |
+
while True:
|
| 170 |
+
while True:
|
| 171 |
+
value = prompt_func(prompt)
|
| 172 |
+
if value:
|
| 173 |
+
break
|
| 174 |
+
elif default is not None:
|
| 175 |
+
value = default
|
| 176 |
+
break
|
| 177 |
+
try:
|
| 178 |
+
result = value_proc(value)
|
| 179 |
+
except UsageError as e:
|
| 180 |
+
if hide_input:
|
| 181 |
+
echo(_("Error: The value you entered was invalid."), err=err)
|
| 182 |
+
else:
|
| 183 |
+
echo(_("Error: {e.message}").format(e=e), err=err)
|
| 184 |
+
continue
|
| 185 |
+
if not confirmation_prompt:
|
| 186 |
+
return result
|
| 187 |
+
while True:
|
| 188 |
+
value2 = prompt_func(confirmation_prompt)
|
| 189 |
+
is_empty = not value and not value2
|
| 190 |
+
if value2 or is_empty:
|
| 191 |
+
break
|
| 192 |
+
if value == value2:
|
| 193 |
+
return result
|
| 194 |
+
echo(_("Error: The two entered values do not match."), err=err)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def confirm(
|
| 198 |
+
text: str,
|
| 199 |
+
default: bool | None = False,
|
| 200 |
+
abort: bool = False,
|
| 201 |
+
prompt_suffix: str = ": ",
|
| 202 |
+
show_default: bool = True,
|
| 203 |
+
err: bool = False,
|
| 204 |
+
) -> bool:
|
| 205 |
+
"""Prompts for confirmation (yes/no question).
|
| 206 |
+
|
| 207 |
+
If the user aborts the input by sending a interrupt signal this
|
| 208 |
+
function will catch it and raise a :exc:`Abort` exception.
|
| 209 |
+
|
| 210 |
+
:param text: the question to ask.
|
| 211 |
+
:param default: The default value to use when no input is given. If
|
| 212 |
+
``None``, repeat until input is given.
|
| 213 |
+
:param abort: if this is set to `True` a negative answer aborts the
|
| 214 |
+
exception by raising :exc:`Abort`.
|
| 215 |
+
:param prompt_suffix: a suffix that should be added to the prompt.
|
| 216 |
+
:param show_default: shows or hides the default value in the prompt.
|
| 217 |
+
:param err: if set to true the file defaults to ``stderr`` instead of
|
| 218 |
+
``stdout``, the same as with echo.
|
| 219 |
+
|
| 220 |
+
.. versionchanged:: 8.3.1
|
| 221 |
+
A space is no longer appended to the prompt.
|
| 222 |
+
|
| 223 |
+
.. versionchanged:: 8.0
|
| 224 |
+
Repeat until input is given if ``default`` is ``None``.
|
| 225 |
+
|
| 226 |
+
.. versionadded:: 4.0
|
| 227 |
+
Added the ``err`` parameter.
|
| 228 |
+
"""
|
| 229 |
+
prompt = _build_prompt(
|
| 230 |
+
text,
|
| 231 |
+
prompt_suffix,
|
| 232 |
+
show_default,
|
| 233 |
+
"y/n" if default is None else ("Y/n" if default else "y/N"),
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
while True:
|
| 237 |
+
try:
|
| 238 |
+
# Write the prompt separately so that we get nice
|
| 239 |
+
# coloring through colorama on Windows
|
| 240 |
+
echo(prompt[:-1], nl=False, err=err)
|
| 241 |
+
# Echo the last character to stdout to work around an issue where
|
| 242 |
+
# readline causes backspace to clear the whole line.
|
| 243 |
+
value = visible_prompt_func(prompt[-1:]).lower().strip()
|
| 244 |
+
except (KeyboardInterrupt, EOFError):
|
| 245 |
+
raise Abort() from None
|
| 246 |
+
if value in ("y", "yes"):
|
| 247 |
+
rv = True
|
| 248 |
+
elif value in ("n", "no"):
|
| 249 |
+
rv = False
|
| 250 |
+
elif default is not None and value == "":
|
| 251 |
+
rv = default
|
| 252 |
+
else:
|
| 253 |
+
echo(_("Error: invalid input"), err=err)
|
| 254 |
+
continue
|
| 255 |
+
break
|
| 256 |
+
if abort and not rv:
|
| 257 |
+
raise Abort()
|
| 258 |
+
return rv
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def echo_via_pager(
|
| 262 |
+
text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,
|
| 263 |
+
color: bool | None = None,
|
| 264 |
+
) -> None:
|
| 265 |
+
"""This function takes a text and shows it via an environment specific
|
| 266 |
+
pager on stdout.
|
| 267 |
+
|
| 268 |
+
.. versionchanged:: 3.0
|
| 269 |
+
Added the `color` flag.
|
| 270 |
+
|
| 271 |
+
:param text_or_generator: the text to page, or alternatively, a
|
| 272 |
+
generator emitting the text to page.
|
| 273 |
+
:param color: controls if the pager supports ANSI colors or not. The
|
| 274 |
+
default is autodetection.
|
| 275 |
+
"""
|
| 276 |
+
color = resolve_color_default(color)
|
| 277 |
+
|
| 278 |
+
if inspect.isgeneratorfunction(text_or_generator):
|
| 279 |
+
i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()
|
| 280 |
+
elif isinstance(text_or_generator, str):
|
| 281 |
+
i = [text_or_generator]
|
| 282 |
+
else:
|
| 283 |
+
i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
|
| 284 |
+
|
| 285 |
+
# convert every element of i to a text type if necessary
|
| 286 |
+
text_generator = (el if isinstance(el, str) else str(el) for el in i)
|
| 287 |
+
|
| 288 |
+
from ._termui_impl import pager
|
| 289 |
+
|
| 290 |
+
return pager(itertools.chain(text_generator, "\n"), color)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@t.overload
|
| 294 |
+
def progressbar(
|
| 295 |
+
*,
|
| 296 |
+
length: int,
|
| 297 |
+
label: str | None = None,
|
| 298 |
+
hidden: bool = False,
|
| 299 |
+
show_eta: bool = True,
|
| 300 |
+
show_percent: bool | None = None,
|
| 301 |
+
show_pos: bool = False,
|
| 302 |
+
fill_char: str = "#",
|
| 303 |
+
empty_char: str = "-",
|
| 304 |
+
bar_template: str = "%(label)s [%(bar)s] %(info)s",
|
| 305 |
+
info_sep: str = " ",
|
| 306 |
+
width: int = 36,
|
| 307 |
+
file: t.TextIO | None = None,
|
| 308 |
+
color: bool | None = None,
|
| 309 |
+
update_min_steps: int = 1,
|
| 310 |
+
) -> ProgressBar[int]: ...
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@t.overload
|
| 314 |
+
def progressbar(
|
| 315 |
+
iterable: cabc.Iterable[V] | None = None,
|
| 316 |
+
length: int | None = None,
|
| 317 |
+
label: str | None = None,
|
| 318 |
+
hidden: bool = False,
|
| 319 |
+
show_eta: bool = True,
|
| 320 |
+
show_percent: bool | None = None,
|
| 321 |
+
show_pos: bool = False,
|
| 322 |
+
item_show_func: t.Callable[[V | None], str | None] | None = None,
|
| 323 |
+
fill_char: str = "#",
|
| 324 |
+
empty_char: str = "-",
|
| 325 |
+
bar_template: str = "%(label)s [%(bar)s] %(info)s",
|
| 326 |
+
info_sep: str = " ",
|
| 327 |
+
width: int = 36,
|
| 328 |
+
file: t.TextIO | None = None,
|
| 329 |
+
color: bool | None = None,
|
| 330 |
+
update_min_steps: int = 1,
|
| 331 |
+
) -> ProgressBar[V]: ...
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def progressbar(
|
| 335 |
+
iterable: cabc.Iterable[V] | None = None,
|
| 336 |
+
length: int | None = None,
|
| 337 |
+
label: str | None = None,
|
| 338 |
+
hidden: bool = False,
|
| 339 |
+
show_eta: bool = True,
|
| 340 |
+
show_percent: bool | None = None,
|
| 341 |
+
show_pos: bool = False,
|
| 342 |
+
item_show_func: t.Callable[[V | None], str | None] | None = None,
|
| 343 |
+
fill_char: str = "#",
|
| 344 |
+
empty_char: str = "-",
|
| 345 |
+
bar_template: str = "%(label)s [%(bar)s] %(info)s",
|
| 346 |
+
info_sep: str = " ",
|
| 347 |
+
width: int = 36,
|
| 348 |
+
file: t.TextIO | None = None,
|
| 349 |
+
color: bool | None = None,
|
| 350 |
+
update_min_steps: int = 1,
|
| 351 |
+
) -> ProgressBar[V]:
|
| 352 |
+
"""This function creates an iterable context manager that can be used
|
| 353 |
+
to iterate over something while showing a progress bar. It will
|
| 354 |
+
either iterate over the `iterable` or `length` items (that are counted
|
| 355 |
+
up). While iteration happens, this function will print a rendered
|
| 356 |
+
progress bar to the given `file` (defaults to stdout) and will attempt
|
| 357 |
+
to calculate remaining time and more. By default, this progress bar
|
| 358 |
+
will not be rendered if the file is not a terminal.
|
| 359 |
+
|
| 360 |
+
The context manager creates the progress bar. When the context
|
| 361 |
+
manager is entered the progress bar is already created. With every
|
| 362 |
+
iteration over the progress bar, the iterable passed to the bar is
|
| 363 |
+
advanced and the bar is updated. When the context manager exits,
|
| 364 |
+
a newline is printed and the progress bar is finalized on screen.
|
| 365 |
+
|
| 366 |
+
Note: The progress bar is currently designed for use cases where the
|
| 367 |
+
total progress can be expected to take at least several seconds.
|
| 368 |
+
Because of this, the ProgressBar class object won't display
|
| 369 |
+
progress that is considered too fast, and progress where the time
|
| 370 |
+
between steps is less than a second.
|
| 371 |
+
|
| 372 |
+
No printing must happen or the progress bar will be unintentionally
|
| 373 |
+
destroyed.
|
| 374 |
+
|
| 375 |
+
Example usage::
|
| 376 |
+
|
| 377 |
+
with progressbar(items) as bar:
|
| 378 |
+
for item in bar:
|
| 379 |
+
do_something_with(item)
|
| 380 |
+
|
| 381 |
+
Alternatively, if no iterable is specified, one can manually update the
|
| 382 |
+
progress bar through the `update()` method instead of directly
|
| 383 |
+
iterating over the progress bar. The update method accepts the number
|
| 384 |
+
of steps to increment the bar with::
|
| 385 |
+
|
| 386 |
+
with progressbar(length=chunks.total_bytes) as bar:
|
| 387 |
+
for chunk in chunks:
|
| 388 |
+
process_chunk(chunk)
|
| 389 |
+
bar.update(chunks.bytes)
|
| 390 |
+
|
| 391 |
+
The ``update()`` method also takes an optional value specifying the
|
| 392 |
+
``current_item`` at the new position. This is useful when used
|
| 393 |
+
together with ``item_show_func`` to customize the output for each
|
| 394 |
+
manual step::
|
| 395 |
+
|
| 396 |
+
with click.progressbar(
|
| 397 |
+
length=total_size,
|
| 398 |
+
label='Unzipping archive',
|
| 399 |
+
item_show_func=lambda a: a.filename
|
| 400 |
+
) as bar:
|
| 401 |
+
for archive in zip_file:
|
| 402 |
+
archive.extract()
|
| 403 |
+
bar.update(archive.size, archive)
|
| 404 |
+
|
| 405 |
+
:param iterable: an iterable to iterate over. If not provided the length
|
| 406 |
+
is required.
|
| 407 |
+
:param length: the number of items to iterate over. By default the
|
| 408 |
+
progressbar will attempt to ask the iterator about its
|
| 409 |
+
length, which might or might not work. If an iterable is
|
| 410 |
+
also provided this parameter can be used to override the
|
| 411 |
+
length. If an iterable is not provided the progress bar
|
| 412 |
+
will iterate over a range of that length.
|
| 413 |
+
:param label: the label to show next to the progress bar.
|
| 414 |
+
:param hidden: hide the progressbar. Defaults to ``False``. When no tty is
|
| 415 |
+
detected, it will only print the progressbar label. Setting this to
|
| 416 |
+
``False`` also disables that.
|
| 417 |
+
:param show_eta: enables or disables the estimated time display. This is
|
| 418 |
+
automatically disabled if the length cannot be
|
| 419 |
+
determined.
|
| 420 |
+
:param show_percent: enables or disables the percentage display. The
|
| 421 |
+
default is `True` if the iterable has a length or
|
| 422 |
+
`False` if not.
|
| 423 |
+
:param show_pos: enables or disables the absolute position display. The
|
| 424 |
+
default is `False`.
|
| 425 |
+
:param item_show_func: A function called with the current item which
|
| 426 |
+
can return a string to show next to the progress bar. If the
|
| 427 |
+
function returns ``None`` nothing is shown. The current item can
|
| 428 |
+
be ``None``, such as when entering and exiting the bar.
|
| 429 |
+
:param fill_char: the character to use to show the filled part of the
|
| 430 |
+
progress bar.
|
| 431 |
+
:param empty_char: the character to use to show the non-filled part of
|
| 432 |
+
the progress bar.
|
| 433 |
+
:param bar_template: the format string to use as template for the bar.
|
| 434 |
+
The parameters in it are ``label`` for the label,
|
| 435 |
+
``bar`` for the progress bar and ``info`` for the
|
| 436 |
+
info section.
|
| 437 |
+
:param info_sep: the separator between multiple info items (eta etc.)
|
| 438 |
+
:param width: the width of the progress bar in characters, 0 means full
|
| 439 |
+
terminal width
|
| 440 |
+
:param file: The file to write to. If this is not a terminal then
|
| 441 |
+
only the label is printed.
|
| 442 |
+
:param color: controls if the terminal supports ANSI colors or not. The
|
| 443 |
+
default is autodetection. This is only needed if ANSI
|
| 444 |
+
codes are included anywhere in the progress bar output
|
| 445 |
+
which is not the case by default.
|
| 446 |
+
:param update_min_steps: Render only when this many updates have
|
| 447 |
+
completed. This allows tuning for very fast iterators.
|
| 448 |
+
|
| 449 |
+
.. versionadded:: 8.2
|
| 450 |
+
The ``hidden`` argument.
|
| 451 |
+
|
| 452 |
+
.. versionchanged:: 8.0
|
| 453 |
+
Output is shown even if execution time is less than 0.5 seconds.
|
| 454 |
+
|
| 455 |
+
.. versionchanged:: 8.0
|
| 456 |
+
``item_show_func`` shows the current item, not the previous one.
|
| 457 |
+
|
| 458 |
+
.. versionchanged:: 8.0
|
| 459 |
+
Labels are echoed if the output is not a TTY. Reverts a change
|
| 460 |
+
in 7.0 that removed all output.
|
| 461 |
+
|
| 462 |
+
.. versionadded:: 8.0
|
| 463 |
+
The ``update_min_steps`` parameter.
|
| 464 |
+
|
| 465 |
+
.. versionadded:: 4.0
|
| 466 |
+
The ``color`` parameter and ``update`` method.
|
| 467 |
+
|
| 468 |
+
.. versionadded:: 2.0
|
| 469 |
+
"""
|
| 470 |
+
from ._termui_impl import ProgressBar
|
| 471 |
+
|
| 472 |
+
color = resolve_color_default(color)
|
| 473 |
+
return ProgressBar(
|
| 474 |
+
iterable=iterable,
|
| 475 |
+
length=length,
|
| 476 |
+
hidden=hidden,
|
| 477 |
+
show_eta=show_eta,
|
| 478 |
+
show_percent=show_percent,
|
| 479 |
+
show_pos=show_pos,
|
| 480 |
+
item_show_func=item_show_func,
|
| 481 |
+
fill_char=fill_char,
|
| 482 |
+
empty_char=empty_char,
|
| 483 |
+
bar_template=bar_template,
|
| 484 |
+
info_sep=info_sep,
|
| 485 |
+
file=file,
|
| 486 |
+
label=label,
|
| 487 |
+
width=width,
|
| 488 |
+
color=color,
|
| 489 |
+
update_min_steps=update_min_steps,
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def clear() -> None:
|
| 494 |
+
"""Clears the terminal screen. This will have the effect of clearing
|
| 495 |
+
the whole visible space of the terminal and moving the cursor to the
|
| 496 |
+
top left. This does not do anything if not connected to a terminal.
|
| 497 |
+
|
| 498 |
+
.. versionadded:: 2.0
|
| 499 |
+
"""
|
| 500 |
+
if not isatty(sys.stdout):
|
| 501 |
+
return
|
| 502 |
+
|
| 503 |
+
# ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
|
| 504 |
+
echo("\033[2J\033[1;1H", nl=False)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:
|
| 508 |
+
if isinstance(color, int):
|
| 509 |
+
return f"{38 + offset};5;{color:d}"
|
| 510 |
+
|
| 511 |
+
if isinstance(color, (tuple, list)):
|
| 512 |
+
r, g, b = color
|
| 513 |
+
return f"{38 + offset};2;{r:d};{g:d};{b:d}"
|
| 514 |
+
|
| 515 |
+
return str(_ansi_colors[color] + offset)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def style(
|
| 519 |
+
text: t.Any,
|
| 520 |
+
fg: int | tuple[int, int, int] | str | None = None,
|
| 521 |
+
bg: int | tuple[int, int, int] | str | None = None,
|
| 522 |
+
bold: bool | None = None,
|
| 523 |
+
dim: bool | None = None,
|
| 524 |
+
underline: bool | None = None,
|
| 525 |
+
overline: bool | None = None,
|
| 526 |
+
italic: bool | None = None,
|
| 527 |
+
blink: bool | None = None,
|
| 528 |
+
reverse: bool | None = None,
|
| 529 |
+
strikethrough: bool | None = None,
|
| 530 |
+
reset: bool = True,
|
| 531 |
+
) -> str:
|
| 532 |
+
"""Styles a text with ANSI styles and returns the new string. By
|
| 533 |
+
default the styling is self contained which means that at the end
|
| 534 |
+
of the string a reset code is issued. This can be prevented by
|
| 535 |
+
passing ``reset=False``.
|
| 536 |
+
|
| 537 |
+
Examples::
|
| 538 |
+
|
| 539 |
+
click.echo(click.style('Hello World!', fg='green'))
|
| 540 |
+
click.echo(click.style('ATTENTION!', blink=True))
|
| 541 |
+
click.echo(click.style('Some things', reverse=True, fg='cyan'))
|
| 542 |
+
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
|
| 543 |
+
|
| 544 |
+
Supported color names:
|
| 545 |
+
|
| 546 |
+
* ``black`` (might be a gray)
|
| 547 |
+
* ``red``
|
| 548 |
+
* ``green``
|
| 549 |
+
* ``yellow`` (might be an orange)
|
| 550 |
+
* ``blue``
|
| 551 |
+
* ``magenta``
|
| 552 |
+
* ``cyan``
|
| 553 |
+
* ``white`` (might be light gray)
|
| 554 |
+
* ``bright_black``
|
| 555 |
+
* ``bright_red``
|
| 556 |
+
* ``bright_green``
|
| 557 |
+
* ``bright_yellow``
|
| 558 |
+
* ``bright_blue``
|
| 559 |
+
* ``bright_magenta``
|
| 560 |
+
* ``bright_cyan``
|
| 561 |
+
* ``bright_white``
|
| 562 |
+
* ``reset`` (reset the color code only)
|
| 563 |
+
|
| 564 |
+
If the terminal supports it, color may also be specified as:
|
| 565 |
+
|
| 566 |
+
- An integer in the interval [0, 255]. The terminal must support
|
| 567 |
+
8-bit/256-color mode.
|
| 568 |
+
- An RGB tuple of three integers in [0, 255]. The terminal must
|
| 569 |
+
support 24-bit/true-color mode.
|
| 570 |
+
|
| 571 |
+
See https://en.wikipedia.org/wiki/ANSI_color and
|
| 572 |
+
https://gist.github.com/XVilka/8346728 for more information.
|
| 573 |
+
|
| 574 |
+
:param text: the string to style with ansi codes.
|
| 575 |
+
:param fg: if provided this will become the foreground color.
|
| 576 |
+
:param bg: if provided this will become the background color.
|
| 577 |
+
:param bold: if provided this will enable or disable bold mode.
|
| 578 |
+
:param dim: if provided this will enable or disable dim mode. This is
|
| 579 |
+
badly supported.
|
| 580 |
+
:param underline: if provided this will enable or disable underline.
|
| 581 |
+
:param overline: if provided this will enable or disable overline.
|
| 582 |
+
:param italic: if provided this will enable or disable italic.
|
| 583 |
+
:param blink: if provided this will enable or disable blinking.
|
| 584 |
+
:param reverse: if provided this will enable or disable inverse
|
| 585 |
+
rendering (foreground becomes background and the
|
| 586 |
+
other way round).
|
| 587 |
+
:param strikethrough: if provided this will enable or disable
|
| 588 |
+
striking through text.
|
| 589 |
+
:param reset: by default a reset-all code is added at the end of the
|
| 590 |
+
string which means that styles do not carry over. This
|
| 591 |
+
can be disabled to compose styles.
|
| 592 |
+
|
| 593 |
+
.. versionchanged:: 8.0
|
| 594 |
+
A non-string ``message`` is converted to a string.
|
| 595 |
+
|
| 596 |
+
.. versionchanged:: 8.0
|
| 597 |
+
Added support for 256 and RGB color codes.
|
| 598 |
+
|
| 599 |
+
.. versionchanged:: 8.0
|
| 600 |
+
Added the ``strikethrough``, ``italic``, and ``overline``
|
| 601 |
+
parameters.
|
| 602 |
+
|
| 603 |
+
.. versionchanged:: 7.0
|
| 604 |
+
Added support for bright colors.
|
| 605 |
+
|
| 606 |
+
.. versionadded:: 2.0
|
| 607 |
+
"""
|
| 608 |
+
if not isinstance(text, str):
|
| 609 |
+
text = str(text)
|
| 610 |
+
|
| 611 |
+
bits = []
|
| 612 |
+
|
| 613 |
+
if fg:
|
| 614 |
+
try:
|
| 615 |
+
bits.append(f"\033[{_interpret_color(fg)}m")
|
| 616 |
+
except KeyError:
|
| 617 |
+
raise TypeError(f"Unknown color {fg!r}") from None
|
| 618 |
+
|
| 619 |
+
if bg:
|
| 620 |
+
try:
|
| 621 |
+
bits.append(f"\033[{_interpret_color(bg, 10)}m")
|
| 622 |
+
except KeyError:
|
| 623 |
+
raise TypeError(f"Unknown color {bg!r}") from None
|
| 624 |
+
|
| 625 |
+
if bold is not None:
|
| 626 |
+
bits.append(f"\033[{1 if bold else 22}m")
|
| 627 |
+
if dim is not None:
|
| 628 |
+
bits.append(f"\033[{2 if dim else 22}m")
|
| 629 |
+
if underline is not None:
|
| 630 |
+
bits.append(f"\033[{4 if underline else 24}m")
|
| 631 |
+
if overline is not None:
|
| 632 |
+
bits.append(f"\033[{53 if overline else 55}m")
|
| 633 |
+
if italic is not None:
|
| 634 |
+
bits.append(f"\033[{3 if italic else 23}m")
|
| 635 |
+
if blink is not None:
|
| 636 |
+
bits.append(f"\033[{5 if blink else 25}m")
|
| 637 |
+
if reverse is not None:
|
| 638 |
+
bits.append(f"\033[{7 if reverse else 27}m")
|
| 639 |
+
if strikethrough is not None:
|
| 640 |
+
bits.append(f"\033[{9 if strikethrough else 29}m")
|
| 641 |
+
bits.append(text)
|
| 642 |
+
if reset:
|
| 643 |
+
bits.append(_ansi_reset_all)
|
| 644 |
+
return "".join(bits)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def unstyle(text: str) -> str:
|
| 648 |
+
"""Removes ANSI styling information from a string. Usually it's not
|
| 649 |
+
necessary to use this function as Click's echo function will
|
| 650 |
+
automatically remove styling if necessary.
|
| 651 |
+
|
| 652 |
+
.. versionadded:: 2.0
|
| 653 |
+
|
| 654 |
+
:param text: the text to remove style information from.
|
| 655 |
+
"""
|
| 656 |
+
return strip_ansi(text)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def secho(
|
| 660 |
+
message: t.Any | None = None,
|
| 661 |
+
file: t.IO[t.AnyStr] | None = None,
|
| 662 |
+
nl: bool = True,
|
| 663 |
+
err: bool = False,
|
| 664 |
+
color: bool | None = None,
|
| 665 |
+
**styles: t.Any,
|
| 666 |
+
) -> None:
|
| 667 |
+
"""This function combines :func:`echo` and :func:`style` into one
|
| 668 |
+
call. As such the following two calls are the same::
|
| 669 |
+
|
| 670 |
+
click.secho('Hello World!', fg='green')
|
| 671 |
+
click.echo(click.style('Hello World!', fg='green'))
|
| 672 |
+
|
| 673 |
+
All keyword arguments are forwarded to the underlying functions
|
| 674 |
+
depending on which one they go with.
|
| 675 |
+
|
| 676 |
+
Non-string types will be converted to :class:`str`. However,
|
| 677 |
+
:class:`bytes` are passed directly to :meth:`echo` without applying
|
| 678 |
+
style. If you want to style bytes that represent text, call
|
| 679 |
+
:meth:`bytes.decode` first.
|
| 680 |
+
|
| 681 |
+
.. versionchanged:: 8.0
|
| 682 |
+
A non-string ``message`` is converted to a string. Bytes are
|
| 683 |
+
passed through without style applied.
|
| 684 |
+
|
| 685 |
+
.. versionadded:: 2.0
|
| 686 |
+
"""
|
| 687 |
+
if message is not None and not isinstance(message, (bytes, bytearray)):
|
| 688 |
+
message = style(message, **styles)
|
| 689 |
+
|
| 690 |
+
return echo(message, file=file, nl=nl, err=err, color=color)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
@t.overload
|
| 694 |
+
def edit(
|
| 695 |
+
text: bytes | bytearray,
|
| 696 |
+
editor: str | None = None,
|
| 697 |
+
env: cabc.Mapping[str, str] | None = None,
|
| 698 |
+
require_save: bool = False,
|
| 699 |
+
extension: str = ".txt",
|
| 700 |
+
) -> bytes | None: ...
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
@t.overload
|
| 704 |
+
def edit(
|
| 705 |
+
text: str,
|
| 706 |
+
editor: str | None = None,
|
| 707 |
+
env: cabc.Mapping[str, str] | None = None,
|
| 708 |
+
require_save: bool = True,
|
| 709 |
+
extension: str = ".txt",
|
| 710 |
+
) -> str | None: ...
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
@t.overload
|
| 714 |
+
def edit(
|
| 715 |
+
text: None = None,
|
| 716 |
+
editor: str | None = None,
|
| 717 |
+
env: cabc.Mapping[str, str] | None = None,
|
| 718 |
+
require_save: bool = True,
|
| 719 |
+
extension: str = ".txt",
|
| 720 |
+
filename: str | cabc.Iterable[str] | None = None,
|
| 721 |
+
) -> None: ...
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def edit(
|
| 725 |
+
text: str | bytes | bytearray | None = None,
|
| 726 |
+
editor: str | None = None,
|
| 727 |
+
env: cabc.Mapping[str, str] | None = None,
|
| 728 |
+
require_save: bool = True,
|
| 729 |
+
extension: str = ".txt",
|
| 730 |
+
filename: str | cabc.Iterable[str] | None = None,
|
| 731 |
+
) -> str | bytes | bytearray | None:
|
| 732 |
+
r"""Edits the given text in the defined editor. If an editor is given
|
| 733 |
+
(should be the full path to the executable but the regular operating
|
| 734 |
+
system search path is used for finding the executable) it overrides
|
| 735 |
+
the detected editor. Optionally, some environment variables can be
|
| 736 |
+
used. If the editor is closed without changes, `None` is returned. In
|
| 737 |
+
case a file is edited directly the return value is always `None` and
|
| 738 |
+
`require_save` and `extension` are ignored.
|
| 739 |
+
|
| 740 |
+
If the editor cannot be opened a :exc:`UsageError` is raised.
|
| 741 |
+
|
| 742 |
+
Note for Windows: to simplify cross-platform usage, the newlines are
|
| 743 |
+
automatically converted from POSIX to Windows and vice versa. As such,
|
| 744 |
+
the message here will have ``\n`` as newline markers.
|
| 745 |
+
|
| 746 |
+
:param text: the text to edit.
|
| 747 |
+
:param editor: optionally the editor to use. Defaults to automatic
|
| 748 |
+
detection.
|
| 749 |
+
:param env: environment variables to forward to the editor.
|
| 750 |
+
:param require_save: if this is true, then not saving in the editor
|
| 751 |
+
will make the return value become `None`.
|
| 752 |
+
:param extension: the extension to tell the editor about. This defaults
|
| 753 |
+
to `.txt` but changing this might change syntax
|
| 754 |
+
highlighting.
|
| 755 |
+
:param filename: if provided it will edit this file instead of the
|
| 756 |
+
provided text contents. It will not use a temporary
|
| 757 |
+
file as an indirection in that case. If the editor supports
|
| 758 |
+
editing multiple files at once, a sequence of files may be
|
| 759 |
+
passed as well. Invoke `click.file` once per file instead
|
| 760 |
+
if multiple files cannot be managed at once or editing the
|
| 761 |
+
files serially is desired.
|
| 762 |
+
|
| 763 |
+
.. versionchanged:: 8.2.0
|
| 764 |
+
``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``
|
| 765 |
+
if the ``editor`` supports editing multiple files at once.
|
| 766 |
+
|
| 767 |
+
"""
|
| 768 |
+
from ._termui_impl import Editor
|
| 769 |
+
|
| 770 |
+
ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
|
| 771 |
+
|
| 772 |
+
if filename is None:
|
| 773 |
+
return ed.edit(text)
|
| 774 |
+
|
| 775 |
+
if isinstance(filename, str):
|
| 776 |
+
filename = (filename,)
|
| 777 |
+
|
| 778 |
+
ed.edit_files(filenames=filename)
|
| 779 |
+
return None
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
def launch(url: str, wait: bool = False, locate: bool = False) -> int:
|
| 783 |
+
"""This function launches the given URL (or filename) in the default
|
| 784 |
+
viewer application for this file type. If this is an executable, it
|
| 785 |
+
might launch the executable in a new session. The return value is
|
| 786 |
+
the exit code of the launched application. Usually, ``0`` indicates
|
| 787 |
+
success.
|
| 788 |
+
|
| 789 |
+
Examples::
|
| 790 |
+
|
| 791 |
+
click.launch('https://click.palletsprojects.com/')
|
| 792 |
+
click.launch('/my/downloaded/file', locate=True)
|
| 793 |
+
|
| 794 |
+
.. versionadded:: 2.0
|
| 795 |
+
|
| 796 |
+
:param url: URL or filename of the thing to launch.
|
| 797 |
+
:param wait: Wait for the program to exit before returning. This
|
| 798 |
+
only works if the launched program blocks. In particular,
|
| 799 |
+
``xdg-open`` on Linux does not block.
|
| 800 |
+
:param locate: if this is set to `True` then instead of launching the
|
| 801 |
+
application associated with the URL it will attempt to
|
| 802 |
+
launch a file manager with the file located. This
|
| 803 |
+
might have weird effects if the URL does not point to
|
| 804 |
+
the filesystem.
|
| 805 |
+
"""
|
| 806 |
+
from ._termui_impl import open_url
|
| 807 |
+
|
| 808 |
+
return open_url(url, wait=wait, locate=locate)
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
# If this is provided, getchar() calls into this instead. This is used
|
| 812 |
+
# for unittesting purposes.
|
| 813 |
+
_getchar: t.Callable[[bool], str] | None = None
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
def getchar(echo: bool = False) -> str:
|
| 817 |
+
"""Fetches a single character from the terminal and returns it. This
|
| 818 |
+
will always return a unicode character and under certain rare
|
| 819 |
+
circumstances this might return more than one character. The
|
| 820 |
+
situations which more than one character is returned is when for
|
| 821 |
+
whatever reason multiple characters end up in the terminal buffer or
|
| 822 |
+
standard input was not actually a terminal.
|
| 823 |
+
|
| 824 |
+
Note that this will always read from the terminal, even if something
|
| 825 |
+
is piped into the standard input.
|
| 826 |
+
|
| 827 |
+
Note for Windows: in rare cases when typing non-ASCII characters, this
|
| 828 |
+
function might wait for a second character and then return both at once.
|
| 829 |
+
This is because certain Unicode characters look like special-key markers.
|
| 830 |
+
|
| 831 |
+
.. versionadded:: 2.0
|
| 832 |
+
|
| 833 |
+
:param echo: if set to `True`, the character read will also show up on
|
| 834 |
+
the terminal. The default is to not show it.
|
| 835 |
+
"""
|
| 836 |
+
global _getchar
|
| 837 |
+
|
| 838 |
+
if _getchar is None:
|
| 839 |
+
from ._termui_impl import getchar as f
|
| 840 |
+
|
| 841 |
+
_getchar = f
|
| 842 |
+
|
| 843 |
+
return _getchar(echo)
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def raw_terminal() -> AbstractContextManager[int]:
|
| 847 |
+
from ._termui_impl import raw_terminal as f
|
| 848 |
+
|
| 849 |
+
return f()
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
def pause(info: str | None = None, err: bool = False) -> None:
|
| 853 |
+
"""This command stops execution and waits for the user to press any
|
| 854 |
+
key to continue. This is similar to the Windows batch "pause"
|
| 855 |
+
command. If the program is not run through a terminal, this command
|
| 856 |
+
will instead do nothing.
|
| 857 |
+
|
| 858 |
+
.. versionadded:: 2.0
|
| 859 |
+
|
| 860 |
+
.. versionadded:: 4.0
|
| 861 |
+
Added the `err` parameter.
|
| 862 |
+
|
| 863 |
+
:param info: The message to print before pausing. Defaults to
|
| 864 |
+
``"Press any key to continue..."``.
|
| 865 |
+
:param err: if set to message goes to ``stderr`` instead of
|
| 866 |
+
``stdout``, the same as with echo.
|
| 867 |
+
"""
|
| 868 |
+
if not isatty(sys.stdin) or not isatty(sys.stdout):
|
| 869 |
+
return
|
| 870 |
+
|
| 871 |
+
if info is None:
|
| 872 |
+
info = _("Press any key to continue...")
|
| 873 |
+
|
| 874 |
+
try:
|
| 875 |
+
if info:
|
| 876 |
+
echo(info, nl=False, err=err)
|
| 877 |
+
try:
|
| 878 |
+
getchar()
|
| 879 |
+
except (KeyboardInterrupt, EOFError):
|
| 880 |
+
pass
|
| 881 |
+
finally:
|
| 882 |
+
if info:
|
| 883 |
+
echo(err=err)
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/testing.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections.abc as cabc
|
| 4 |
+
import contextlib
|
| 5 |
+
import io
|
| 6 |
+
import os
|
| 7 |
+
import shlex
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
import typing as t
|
| 11 |
+
from types import TracebackType
|
| 12 |
+
|
| 13 |
+
from . import _compat
|
| 14 |
+
from . import formatting
|
| 15 |
+
from . import termui
|
| 16 |
+
from . import utils
|
| 17 |
+
from ._compat import _find_binary_reader
|
| 18 |
+
|
| 19 |
+
if t.TYPE_CHECKING:
|
| 20 |
+
from _typeshed import ReadableBuffer
|
| 21 |
+
|
| 22 |
+
from .core import Command
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class EchoingStdin:
|
| 26 |
+
def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:
|
| 27 |
+
self._input = input
|
| 28 |
+
self._output = output
|
| 29 |
+
self._paused = False
|
| 30 |
+
|
| 31 |
+
def __getattr__(self, x: str) -> t.Any:
|
| 32 |
+
return getattr(self._input, x)
|
| 33 |
+
|
| 34 |
+
def _echo(self, rv: bytes) -> bytes:
|
| 35 |
+
if not self._paused:
|
| 36 |
+
self._output.write(rv)
|
| 37 |
+
|
| 38 |
+
return rv
|
| 39 |
+
|
| 40 |
+
def read(self, n: int = -1) -> bytes:
|
| 41 |
+
return self._echo(self._input.read(n))
|
| 42 |
+
|
| 43 |
+
def read1(self, n: int = -1) -> bytes:
|
| 44 |
+
return self._echo(self._input.read1(n)) # type: ignore
|
| 45 |
+
|
| 46 |
+
def readline(self, n: int = -1) -> bytes:
|
| 47 |
+
return self._echo(self._input.readline(n))
|
| 48 |
+
|
| 49 |
+
def readlines(self) -> list[bytes]:
|
| 50 |
+
return [self._echo(x) for x in self._input.readlines()]
|
| 51 |
+
|
| 52 |
+
def __iter__(self) -> cabc.Iterator[bytes]:
|
| 53 |
+
return iter(self._echo(x) for x in self._input)
|
| 54 |
+
|
| 55 |
+
def __repr__(self) -> str:
|
| 56 |
+
return repr(self._input)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@contextlib.contextmanager
|
| 60 |
+
def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]:
|
| 61 |
+
if stream is None:
|
| 62 |
+
yield
|
| 63 |
+
else:
|
| 64 |
+
stream._paused = True
|
| 65 |
+
yield
|
| 66 |
+
stream._paused = False
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class BytesIOCopy(io.BytesIO):
|
| 70 |
+
"""Patch ``io.BytesIO`` to let the written stream be copied to another.
|
| 71 |
+
|
| 72 |
+
.. versionadded:: 8.2
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(self, copy_to: io.BytesIO) -> None:
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.copy_to = copy_to
|
| 78 |
+
|
| 79 |
+
def flush(self) -> None:
|
| 80 |
+
super().flush()
|
| 81 |
+
self.copy_to.flush()
|
| 82 |
+
|
| 83 |
+
def write(self, b: ReadableBuffer) -> int:
|
| 84 |
+
self.copy_to.write(b)
|
| 85 |
+
return super().write(b)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class StreamMixer:
|
| 89 |
+
"""Mixes `<stdout>` and `<stderr>` streams.
|
| 90 |
+
|
| 91 |
+
The result is available in the ``output`` attribute.
|
| 92 |
+
|
| 93 |
+
.. versionadded:: 8.2
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def __init__(self) -> None:
|
| 97 |
+
self.output: io.BytesIO = io.BytesIO()
|
| 98 |
+
self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)
|
| 99 |
+
self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class _NamedTextIOWrapper(io.TextIOWrapper):
|
| 103 |
+
def __init__(
|
| 104 |
+
self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any
|
| 105 |
+
) -> None:
|
| 106 |
+
super().__init__(buffer, **kwargs)
|
| 107 |
+
self._name = name
|
| 108 |
+
self._mode = mode
|
| 109 |
+
|
| 110 |
+
def close(self) -> None:
|
| 111 |
+
"""
|
| 112 |
+
The buffer this object contains belongs to some other object, so
|
| 113 |
+
prevent the default __del__ implementation from closing that buffer.
|
| 114 |
+
|
| 115 |
+
.. versionadded:: 8.3.2
|
| 116 |
+
"""
|
| 117 |
+
...
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def name(self) -> str:
|
| 121 |
+
return self._name
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def mode(self) -> str:
|
| 125 |
+
return self._mode
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def make_input_stream(
|
| 129 |
+
input: str | bytes | t.IO[t.Any] | None, charset: str
|
| 130 |
+
) -> t.BinaryIO:
|
| 131 |
+
# Is already an input stream.
|
| 132 |
+
if hasattr(input, "read"):
|
| 133 |
+
rv = _find_binary_reader(t.cast("t.IO[t.Any]", input))
|
| 134 |
+
|
| 135 |
+
if rv is not None:
|
| 136 |
+
return rv
|
| 137 |
+
|
| 138 |
+
raise TypeError("Could not find binary reader for input stream.")
|
| 139 |
+
|
| 140 |
+
if input is None:
|
| 141 |
+
input = b""
|
| 142 |
+
elif isinstance(input, str):
|
| 143 |
+
input = input.encode(charset)
|
| 144 |
+
|
| 145 |
+
return io.BytesIO(input)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class Result:
|
| 149 |
+
"""Holds the captured result of an invoked CLI script.
|
| 150 |
+
|
| 151 |
+
:param runner: The runner that created the result
|
| 152 |
+
:param stdout_bytes: The standard output as bytes.
|
| 153 |
+
:param stderr_bytes: The standard error as bytes.
|
| 154 |
+
:param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the
|
| 155 |
+
user would see it in its terminal.
|
| 156 |
+
:param return_value: The value returned from the invoked command.
|
| 157 |
+
:param exit_code: The exit code as integer.
|
| 158 |
+
:param exception: The exception that happened if one did.
|
| 159 |
+
:param exc_info: Exception information (exception type, exception instance,
|
| 160 |
+
traceback type).
|
| 161 |
+
|
| 162 |
+
.. versionchanged:: 8.2
|
| 163 |
+
``stderr_bytes`` no longer optional, ``output_bytes`` introduced and
|
| 164 |
+
``mix_stderr`` has been removed.
|
| 165 |
+
|
| 166 |
+
.. versionadded:: 8.0
|
| 167 |
+
Added ``return_value``.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
def __init__(
|
| 171 |
+
self,
|
| 172 |
+
runner: CliRunner,
|
| 173 |
+
stdout_bytes: bytes,
|
| 174 |
+
stderr_bytes: bytes,
|
| 175 |
+
output_bytes: bytes,
|
| 176 |
+
return_value: t.Any,
|
| 177 |
+
exit_code: int,
|
| 178 |
+
exception: BaseException | None,
|
| 179 |
+
exc_info: tuple[type[BaseException], BaseException, TracebackType]
|
| 180 |
+
| None = None,
|
| 181 |
+
):
|
| 182 |
+
self.runner = runner
|
| 183 |
+
self.stdout_bytes = stdout_bytes
|
| 184 |
+
self.stderr_bytes = stderr_bytes
|
| 185 |
+
self.output_bytes = output_bytes
|
| 186 |
+
self.return_value = return_value
|
| 187 |
+
self.exit_code = exit_code
|
| 188 |
+
self.exception = exception
|
| 189 |
+
self.exc_info = exc_info
|
| 190 |
+
|
| 191 |
+
@property
|
| 192 |
+
def output(self) -> str:
|
| 193 |
+
"""The terminal output as unicode string, as the user would see it.
|
| 194 |
+
|
| 195 |
+
.. versionchanged:: 8.2
|
| 196 |
+
No longer a proxy for ``self.stdout``. Now has its own independent stream
|
| 197 |
+
that is mixing `<stdout>` and `<stderr>`, in the order they were written.
|
| 198 |
+
"""
|
| 199 |
+
return self.output_bytes.decode(self.runner.charset, "replace").replace(
|
| 200 |
+
"\r\n", "\n"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
@property
|
| 204 |
+
def stdout(self) -> str:
|
| 205 |
+
"""The standard output as unicode string."""
|
| 206 |
+
return self.stdout_bytes.decode(self.runner.charset, "replace").replace(
|
| 207 |
+
"\r\n", "\n"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
@property
|
| 211 |
+
def stderr(self) -> str:
|
| 212 |
+
"""The standard error as unicode string.
|
| 213 |
+
|
| 214 |
+
.. versionchanged:: 8.2
|
| 215 |
+
No longer raise an exception, always returns the `<stderr>` string.
|
| 216 |
+
"""
|
| 217 |
+
return self.stderr_bytes.decode(self.runner.charset, "replace").replace(
|
| 218 |
+
"\r\n", "\n"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
def __repr__(self) -> str:
|
| 222 |
+
exc_str = repr(self.exception) if self.exception else "okay"
|
| 223 |
+
return f"<{type(self).__name__} {exc_str}>"
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class CliRunner:
|
| 227 |
+
"""The CLI runner provides functionality to invoke a Click command line
|
| 228 |
+
script for unittesting purposes in a isolated environment. This only
|
| 229 |
+
works in single-threaded systems without any concurrency as it changes the
|
| 230 |
+
global interpreter state.
|
| 231 |
+
|
| 232 |
+
:param charset: the character set for the input and output data.
|
| 233 |
+
:param env: a dictionary with environment variables for overriding.
|
| 234 |
+
:param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes
|
| 235 |
+
to `<stdout>`. This is useful for showing examples in
|
| 236 |
+
some circumstances. Note that regular prompts
|
| 237 |
+
will automatically echo the input.
|
| 238 |
+
:param catch_exceptions: Whether to catch any exceptions other than
|
| 239 |
+
``SystemExit`` when running :meth:`~CliRunner.invoke`.
|
| 240 |
+
|
| 241 |
+
.. versionchanged:: 8.2
|
| 242 |
+
Added the ``catch_exceptions`` parameter.
|
| 243 |
+
|
| 244 |
+
.. versionchanged:: 8.2
|
| 245 |
+
``mix_stderr`` parameter has been removed.
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
def __init__(
|
| 249 |
+
self,
|
| 250 |
+
charset: str = "utf-8",
|
| 251 |
+
env: cabc.Mapping[str, str | None] | None = None,
|
| 252 |
+
echo_stdin: bool = False,
|
| 253 |
+
catch_exceptions: bool = True,
|
| 254 |
+
) -> None:
|
| 255 |
+
self.charset = charset
|
| 256 |
+
self.env: cabc.Mapping[str, str | None] = env or {}
|
| 257 |
+
self.echo_stdin = echo_stdin
|
| 258 |
+
self.catch_exceptions = catch_exceptions
|
| 259 |
+
|
| 260 |
+
def get_default_prog_name(self, cli: Command) -> str:
|
| 261 |
+
"""Given a command object it will return the default program name
|
| 262 |
+
for it. The default is the `name` attribute or ``"root"`` if not
|
| 263 |
+
set.
|
| 264 |
+
"""
|
| 265 |
+
return cli.name or "root"
|
| 266 |
+
|
| 267 |
+
def make_env(
|
| 268 |
+
self, overrides: cabc.Mapping[str, str | None] | None = None
|
| 269 |
+
) -> cabc.Mapping[str, str | None]:
|
| 270 |
+
"""Returns the environment overrides for invoking a script."""
|
| 271 |
+
rv = dict(self.env)
|
| 272 |
+
if overrides:
|
| 273 |
+
rv.update(overrides)
|
| 274 |
+
return rv
|
| 275 |
+
|
| 276 |
+
@contextlib.contextmanager
|
| 277 |
+
def isolation(
|
| 278 |
+
self,
|
| 279 |
+
input: str | bytes | t.IO[t.Any] | None = None,
|
| 280 |
+
env: cabc.Mapping[str, str | None] | None = None,
|
| 281 |
+
color: bool = False,
|
| 282 |
+
) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:
|
| 283 |
+
"""A context manager that sets up the isolation for invoking of a
|
| 284 |
+
command line tool. This sets up `<stdin>` with the given input data
|
| 285 |
+
and `os.environ` with the overrides from the given dictionary.
|
| 286 |
+
This also rebinds some internals in Click to be mocked (like the
|
| 287 |
+
prompt functionality).
|
| 288 |
+
|
| 289 |
+
This is automatically done in the :meth:`invoke` method.
|
| 290 |
+
|
| 291 |
+
:param input: the input stream to put into `sys.stdin`.
|
| 292 |
+
:param env: the environment overrides as dictionary.
|
| 293 |
+
:param color: whether the output should contain color codes. The
|
| 294 |
+
application can still override this explicitly.
|
| 295 |
+
|
| 296 |
+
.. versionadded:: 8.2
|
| 297 |
+
An additional output stream is returned, which is a mix of
|
| 298 |
+
`<stdout>` and `<stderr>` streams.
|
| 299 |
+
|
| 300 |
+
.. versionchanged:: 8.2
|
| 301 |
+
Always returns the `<stderr>` stream.
|
| 302 |
+
|
| 303 |
+
.. versionchanged:: 8.0
|
| 304 |
+
`<stderr>` is opened with ``errors="backslashreplace"``
|
| 305 |
+
instead of the default ``"strict"``.
|
| 306 |
+
|
| 307 |
+
.. versionchanged:: 4.0
|
| 308 |
+
Added the ``color`` parameter.
|
| 309 |
+
"""
|
| 310 |
+
bytes_input = make_input_stream(input, self.charset)
|
| 311 |
+
echo_input = None
|
| 312 |
+
|
| 313 |
+
old_stdin = sys.stdin
|
| 314 |
+
old_stdout = sys.stdout
|
| 315 |
+
old_stderr = sys.stderr
|
| 316 |
+
old_forced_width = formatting.FORCED_WIDTH
|
| 317 |
+
formatting.FORCED_WIDTH = 80
|
| 318 |
+
|
| 319 |
+
env = self.make_env(env)
|
| 320 |
+
|
| 321 |
+
stream_mixer = StreamMixer()
|
| 322 |
+
|
| 323 |
+
if self.echo_stdin:
|
| 324 |
+
bytes_input = echo_input = t.cast(
|
| 325 |
+
t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
sys.stdin = text_input = _NamedTextIOWrapper(
|
| 329 |
+
bytes_input, encoding=self.charset, name="<stdin>", mode="r"
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
if self.echo_stdin:
|
| 333 |
+
# Force unbuffered reads, otherwise TextIOWrapper reads a
|
| 334 |
+
# large chunk which is echoed early.
|
| 335 |
+
text_input._CHUNK_SIZE = 1 # type: ignore
|
| 336 |
+
|
| 337 |
+
sys.stdout = _NamedTextIOWrapper(
|
| 338 |
+
stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w"
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
sys.stderr = _NamedTextIOWrapper(
|
| 342 |
+
stream_mixer.stderr,
|
| 343 |
+
encoding=self.charset,
|
| 344 |
+
name="<stderr>",
|
| 345 |
+
mode="w",
|
| 346 |
+
errors="backslashreplace",
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
@_pause_echo(echo_input) # type: ignore
|
| 350 |
+
def visible_input(prompt: str | None = None) -> str:
|
| 351 |
+
sys.stdout.write(prompt or "")
|
| 352 |
+
try:
|
| 353 |
+
val = next(text_input).rstrip("\r\n")
|
| 354 |
+
except StopIteration as e:
|
| 355 |
+
raise EOFError() from e
|
| 356 |
+
sys.stdout.write(f"{val}\n")
|
| 357 |
+
sys.stdout.flush()
|
| 358 |
+
return val
|
| 359 |
+
|
| 360 |
+
@_pause_echo(echo_input) # type: ignore
|
| 361 |
+
def hidden_input(prompt: str | None = None) -> str:
|
| 362 |
+
sys.stdout.write(f"{prompt or ''}\n")
|
| 363 |
+
sys.stdout.flush()
|
| 364 |
+
try:
|
| 365 |
+
return next(text_input).rstrip("\r\n")
|
| 366 |
+
except StopIteration as e:
|
| 367 |
+
raise EOFError() from e
|
| 368 |
+
|
| 369 |
+
@_pause_echo(echo_input) # type: ignore
|
| 370 |
+
def _getchar(echo: bool) -> str:
|
| 371 |
+
char = sys.stdin.read(1)
|
| 372 |
+
|
| 373 |
+
if echo:
|
| 374 |
+
sys.stdout.write(char)
|
| 375 |
+
|
| 376 |
+
sys.stdout.flush()
|
| 377 |
+
return char
|
| 378 |
+
|
| 379 |
+
default_color = color
|
| 380 |
+
|
| 381 |
+
def should_strip_ansi(
|
| 382 |
+
stream: t.IO[t.Any] | None = None, color: bool | None = None
|
| 383 |
+
) -> bool:
|
| 384 |
+
if color is None:
|
| 385 |
+
return not default_color
|
| 386 |
+
return not color
|
| 387 |
+
|
| 388 |
+
old_visible_prompt_func = termui.visible_prompt_func
|
| 389 |
+
old_hidden_prompt_func = termui.hidden_prompt_func
|
| 390 |
+
old__getchar_func = termui._getchar
|
| 391 |
+
old_should_strip_ansi = utils.should_strip_ansi # type: ignore
|
| 392 |
+
old__compat_should_strip_ansi = _compat.should_strip_ansi
|
| 393 |
+
termui.visible_prompt_func = visible_input
|
| 394 |
+
termui.hidden_prompt_func = hidden_input
|
| 395 |
+
termui._getchar = _getchar
|
| 396 |
+
utils.should_strip_ansi = should_strip_ansi # type: ignore
|
| 397 |
+
_compat.should_strip_ansi = should_strip_ansi
|
| 398 |
+
|
| 399 |
+
old_env = {}
|
| 400 |
+
try:
|
| 401 |
+
for key, value in env.items():
|
| 402 |
+
old_env[key] = os.environ.get(key)
|
| 403 |
+
if value is None:
|
| 404 |
+
try:
|
| 405 |
+
del os.environ[key]
|
| 406 |
+
except Exception:
|
| 407 |
+
pass
|
| 408 |
+
else:
|
| 409 |
+
os.environ[key] = value
|
| 410 |
+
yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)
|
| 411 |
+
finally:
|
| 412 |
+
for key, value in old_env.items():
|
| 413 |
+
if value is None:
|
| 414 |
+
try:
|
| 415 |
+
del os.environ[key]
|
| 416 |
+
except Exception:
|
| 417 |
+
pass
|
| 418 |
+
else:
|
| 419 |
+
os.environ[key] = value
|
| 420 |
+
sys.stdout = old_stdout
|
| 421 |
+
sys.stderr = old_stderr
|
| 422 |
+
sys.stdin = old_stdin
|
| 423 |
+
termui.visible_prompt_func = old_visible_prompt_func
|
| 424 |
+
termui.hidden_prompt_func = old_hidden_prompt_func
|
| 425 |
+
termui._getchar = old__getchar_func
|
| 426 |
+
utils.should_strip_ansi = old_should_strip_ansi # type: ignore
|
| 427 |
+
_compat.should_strip_ansi = old__compat_should_strip_ansi
|
| 428 |
+
formatting.FORCED_WIDTH = old_forced_width
|
| 429 |
+
|
| 430 |
+
def invoke(
|
| 431 |
+
self,
|
| 432 |
+
cli: Command,
|
| 433 |
+
args: str | cabc.Sequence[str] | None = None,
|
| 434 |
+
input: str | bytes | t.IO[t.Any] | None = None,
|
| 435 |
+
env: cabc.Mapping[str, str | None] | None = None,
|
| 436 |
+
catch_exceptions: bool | None = None,
|
| 437 |
+
color: bool = False,
|
| 438 |
+
**extra: t.Any,
|
| 439 |
+
) -> Result:
|
| 440 |
+
"""Invokes a command in an isolated environment. The arguments are
|
| 441 |
+
forwarded directly to the command line script, the `extra` keyword
|
| 442 |
+
arguments are passed to the :meth:`~clickpkg.Command.main` function of
|
| 443 |
+
the command.
|
| 444 |
+
|
| 445 |
+
This returns a :class:`Result` object.
|
| 446 |
+
|
| 447 |
+
:param cli: the command to invoke
|
| 448 |
+
:param args: the arguments to invoke. It may be given as an iterable
|
| 449 |
+
or a string. When given as string it will be interpreted
|
| 450 |
+
as a Unix shell command. More details at
|
| 451 |
+
:func:`shlex.split`.
|
| 452 |
+
:param input: the input data for `sys.stdin`.
|
| 453 |
+
:param env: the environment overrides.
|
| 454 |
+
:param catch_exceptions: Whether to catch any other exceptions than
|
| 455 |
+
``SystemExit``. If :data:`None`, the value
|
| 456 |
+
from :class:`CliRunner` is used.
|
| 457 |
+
:param extra: the keyword arguments to pass to :meth:`main`.
|
| 458 |
+
:param color: whether the output should contain color codes. The
|
| 459 |
+
application can still override this explicitly.
|
| 460 |
+
|
| 461 |
+
.. versionadded:: 8.2
|
| 462 |
+
The result object has the ``output_bytes`` attribute with
|
| 463 |
+
the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would
|
| 464 |
+
see it in its terminal.
|
| 465 |
+
|
| 466 |
+
.. versionchanged:: 8.2
|
| 467 |
+
The result object always returns the ``stderr_bytes`` stream.
|
| 468 |
+
|
| 469 |
+
.. versionchanged:: 8.0
|
| 470 |
+
The result object has the ``return_value`` attribute with
|
| 471 |
+
the value returned from the invoked command.
|
| 472 |
+
|
| 473 |
+
.. versionchanged:: 4.0
|
| 474 |
+
Added the ``color`` parameter.
|
| 475 |
+
|
| 476 |
+
.. versionchanged:: 3.0
|
| 477 |
+
Added the ``catch_exceptions`` parameter.
|
| 478 |
+
|
| 479 |
+
.. versionchanged:: 3.0
|
| 480 |
+
The result object has the ``exc_info`` attribute with the
|
| 481 |
+
traceback if available.
|
| 482 |
+
"""
|
| 483 |
+
exc_info = None
|
| 484 |
+
if catch_exceptions is None:
|
| 485 |
+
catch_exceptions = self.catch_exceptions
|
| 486 |
+
|
| 487 |
+
with self.isolation(input=input, env=env, color=color) as outstreams:
|
| 488 |
+
return_value = None
|
| 489 |
+
exception: BaseException | None = None
|
| 490 |
+
exit_code = 0
|
| 491 |
+
|
| 492 |
+
if isinstance(args, str):
|
| 493 |
+
args = shlex.split(args)
|
| 494 |
+
|
| 495 |
+
try:
|
| 496 |
+
prog_name = extra.pop("prog_name")
|
| 497 |
+
except KeyError:
|
| 498 |
+
prog_name = self.get_default_prog_name(cli)
|
| 499 |
+
|
| 500 |
+
try:
|
| 501 |
+
return_value = cli.main(args=args or (), prog_name=prog_name, **extra)
|
| 502 |
+
except SystemExit as e:
|
| 503 |
+
exc_info = sys.exc_info()
|
| 504 |
+
e_code = t.cast("int | t.Any | None", e.code)
|
| 505 |
+
|
| 506 |
+
if e_code is None:
|
| 507 |
+
e_code = 0
|
| 508 |
+
|
| 509 |
+
if e_code != 0:
|
| 510 |
+
exception = e
|
| 511 |
+
|
| 512 |
+
if not isinstance(e_code, int):
|
| 513 |
+
sys.stdout.write(str(e_code))
|
| 514 |
+
sys.stdout.write("\n")
|
| 515 |
+
e_code = 1
|
| 516 |
+
|
| 517 |
+
exit_code = e_code
|
| 518 |
+
|
| 519 |
+
except Exception as e:
|
| 520 |
+
if not catch_exceptions:
|
| 521 |
+
raise
|
| 522 |
+
exception = e
|
| 523 |
+
exit_code = 1
|
| 524 |
+
exc_info = sys.exc_info()
|
| 525 |
+
finally:
|
| 526 |
+
sys.stdout.flush()
|
| 527 |
+
sys.stderr.flush()
|
| 528 |
+
stdout = outstreams[0].getvalue()
|
| 529 |
+
stderr = outstreams[1].getvalue()
|
| 530 |
+
output = outstreams[2].getvalue()
|
| 531 |
+
|
| 532 |
+
return Result(
|
| 533 |
+
runner=self,
|
| 534 |
+
stdout_bytes=stdout,
|
| 535 |
+
stderr_bytes=stderr,
|
| 536 |
+
output_bytes=output,
|
| 537 |
+
return_value=return_value,
|
| 538 |
+
exit_code=exit_code,
|
| 539 |
+
exception=exception,
|
| 540 |
+
exc_info=exc_info, # type: ignore
|
| 541 |
+
)
|
| 542 |
+
|
| 543 |
+
@contextlib.contextmanager
|
| 544 |
+
def isolated_filesystem(
|
| 545 |
+
self, temp_dir: str | os.PathLike[str] | None = None
|
| 546 |
+
) -> cabc.Iterator[str]:
|
| 547 |
+
"""A context manager that creates a temporary directory and
|
| 548 |
+
changes the current working directory to it. This isolates tests
|
| 549 |
+
that affect the contents of the CWD to prevent them from
|
| 550 |
+
interfering with each other.
|
| 551 |
+
|
| 552 |
+
:param temp_dir: Create the temporary directory under this
|
| 553 |
+
directory. If given, the created directory is not removed
|
| 554 |
+
when exiting.
|
| 555 |
+
|
| 556 |
+
.. versionchanged:: 8.0
|
| 557 |
+
Added the ``temp_dir`` parameter.
|
| 558 |
+
"""
|
| 559 |
+
cwd = os.getcwd()
|
| 560 |
+
dt = tempfile.mkdtemp(dir=temp_dir)
|
| 561 |
+
os.chdir(dt)
|
| 562 |
+
|
| 563 |
+
try:
|
| 564 |
+
yield dt
|
| 565 |
+
finally:
|
| 566 |
+
os.chdir(cwd)
|
| 567 |
+
|
| 568 |
+
if temp_dir is None:
|
| 569 |
+
import shutil
|
| 570 |
+
|
| 571 |
+
try:
|
| 572 |
+
shutil.rmtree(dt)
|
| 573 |
+
except OSError:
|
| 574 |
+
pass
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/types.py
ADDED
|
@@ -0,0 +1,1209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections.abc as cabc
|
| 4 |
+
import enum
|
| 5 |
+
import os
|
| 6 |
+
import stat
|
| 7 |
+
import sys
|
| 8 |
+
import typing as t
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from gettext import gettext as _
|
| 11 |
+
from gettext import ngettext
|
| 12 |
+
|
| 13 |
+
from ._compat import _get_argv_encoding
|
| 14 |
+
from ._compat import open_stream
|
| 15 |
+
from .exceptions import BadParameter
|
| 16 |
+
from .utils import format_filename
|
| 17 |
+
from .utils import LazyFile
|
| 18 |
+
from .utils import safecall
|
| 19 |
+
|
| 20 |
+
if t.TYPE_CHECKING:
|
| 21 |
+
import typing_extensions as te
|
| 22 |
+
|
| 23 |
+
from .core import Context
|
| 24 |
+
from .core import Parameter
|
| 25 |
+
from .shell_completion import CompletionItem
|
| 26 |
+
|
| 27 |
+
ParamTypeValue = t.TypeVar("ParamTypeValue")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ParamType:
|
| 31 |
+
"""Represents the type of a parameter. Validates and converts values
|
| 32 |
+
from the command line or Python into the correct type.
|
| 33 |
+
|
| 34 |
+
To implement a custom type, subclass and implement at least the
|
| 35 |
+
following:
|
| 36 |
+
|
| 37 |
+
- The :attr:`name` class attribute must be set.
|
| 38 |
+
- Calling an instance of the type with ``None`` must return
|
| 39 |
+
``None``. This is already implemented by default.
|
| 40 |
+
- :meth:`convert` must convert string values to the correct type.
|
| 41 |
+
- :meth:`convert` must accept values that are already the correct
|
| 42 |
+
type.
|
| 43 |
+
- It must be able to convert a value if the ``ctx`` and ``param``
|
| 44 |
+
arguments are ``None``. This can occur when converting prompt
|
| 45 |
+
input.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
is_composite: t.ClassVar[bool] = False
|
| 49 |
+
arity: t.ClassVar[int] = 1
|
| 50 |
+
|
| 51 |
+
#: the descriptive name of this type
|
| 52 |
+
name: str
|
| 53 |
+
|
| 54 |
+
#: if a list of this type is expected and the value is pulled from a
|
| 55 |
+
#: string environment variable, this is what splits it up. `None`
|
| 56 |
+
#: means any whitespace. For all parameters the general rule is that
|
| 57 |
+
#: whitespace splits them up. The exception are paths and files which
|
| 58 |
+
#: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on
|
| 59 |
+
#: Windows).
|
| 60 |
+
envvar_list_splitter: t.ClassVar[str | None] = None
|
| 61 |
+
|
| 62 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 63 |
+
"""Gather information that could be useful for a tool generating
|
| 64 |
+
user-facing documentation.
|
| 65 |
+
|
| 66 |
+
Use :meth:`click.Context.to_info_dict` to traverse the entire
|
| 67 |
+
CLI structure.
|
| 68 |
+
|
| 69 |
+
.. versionadded:: 8.0
|
| 70 |
+
"""
|
| 71 |
+
# The class name without the "ParamType" suffix.
|
| 72 |
+
param_type = type(self).__name__.partition("ParamType")[0]
|
| 73 |
+
param_type = param_type.partition("ParameterType")[0]
|
| 74 |
+
|
| 75 |
+
# Custom subclasses might not remember to set a name.
|
| 76 |
+
if hasattr(self, "name"):
|
| 77 |
+
name = self.name
|
| 78 |
+
else:
|
| 79 |
+
name = param_type
|
| 80 |
+
|
| 81 |
+
return {"param_type": param_type, "name": name}
|
| 82 |
+
|
| 83 |
+
def __call__(
|
| 84 |
+
self,
|
| 85 |
+
value: t.Any,
|
| 86 |
+
param: Parameter | None = None,
|
| 87 |
+
ctx: Context | None = None,
|
| 88 |
+
) -> t.Any:
|
| 89 |
+
if value is not None:
|
| 90 |
+
return self.convert(value, param, ctx)
|
| 91 |
+
|
| 92 |
+
def get_metavar(self, param: Parameter, ctx: Context) -> str | None:
|
| 93 |
+
"""Returns the metavar default for this param if it provides one."""
|
| 94 |
+
|
| 95 |
+
def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None:
|
| 96 |
+
"""Optionally might return extra information about a missing
|
| 97 |
+
parameter.
|
| 98 |
+
|
| 99 |
+
.. versionadded:: 2.0
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def convert(
|
| 103 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 104 |
+
) -> t.Any:
|
| 105 |
+
"""Convert the value to the correct type. This is not called if
|
| 106 |
+
the value is ``None`` (the missing value).
|
| 107 |
+
|
| 108 |
+
This must accept string values from the command line, as well as
|
| 109 |
+
values that are already the correct type. It may also convert
|
| 110 |
+
other compatible types.
|
| 111 |
+
|
| 112 |
+
The ``param`` and ``ctx`` arguments may be ``None`` in certain
|
| 113 |
+
situations, such as when converting prompt input.
|
| 114 |
+
|
| 115 |
+
If the value cannot be converted, call :meth:`fail` with a
|
| 116 |
+
descriptive message.
|
| 117 |
+
|
| 118 |
+
:param value: The value to convert.
|
| 119 |
+
:param param: The parameter that is using this type to convert
|
| 120 |
+
its value. May be ``None``.
|
| 121 |
+
:param ctx: The current context that arrived at this value. May
|
| 122 |
+
be ``None``.
|
| 123 |
+
"""
|
| 124 |
+
return value
|
| 125 |
+
|
| 126 |
+
def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:
|
| 127 |
+
"""Given a value from an environment variable this splits it up
|
| 128 |
+
into small chunks depending on the defined envvar list splitter.
|
| 129 |
+
|
| 130 |
+
If the splitter is set to `None`, which means that whitespace splits,
|
| 131 |
+
then leading and trailing whitespace is ignored. Otherwise, leading
|
| 132 |
+
and trailing splitters usually lead to empty items being included.
|
| 133 |
+
"""
|
| 134 |
+
return (rv or "").split(self.envvar_list_splitter)
|
| 135 |
+
|
| 136 |
+
def fail(
|
| 137 |
+
self,
|
| 138 |
+
message: str,
|
| 139 |
+
param: Parameter | None = None,
|
| 140 |
+
ctx: Context | None = None,
|
| 141 |
+
) -> t.NoReturn:
|
| 142 |
+
"""Helper method to fail with an invalid value message."""
|
| 143 |
+
raise BadParameter(message, ctx=ctx, param=param)
|
| 144 |
+
|
| 145 |
+
def shell_complete(
|
| 146 |
+
self, ctx: Context, param: Parameter, incomplete: str
|
| 147 |
+
) -> list[CompletionItem]:
|
| 148 |
+
"""Return a list of
|
| 149 |
+
:class:`~click.shell_completion.CompletionItem` objects for the
|
| 150 |
+
incomplete value. Most types do not provide completions, but
|
| 151 |
+
some do, and this allows custom types to provide custom
|
| 152 |
+
completions as well.
|
| 153 |
+
|
| 154 |
+
:param ctx: Invocation context for this command.
|
| 155 |
+
:param param: The parameter that is requesting completion.
|
| 156 |
+
:param incomplete: Value being completed. May be empty.
|
| 157 |
+
|
| 158 |
+
.. versionadded:: 8.0
|
| 159 |
+
"""
|
| 160 |
+
return []
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class CompositeParamType(ParamType):
|
| 164 |
+
is_composite = True
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def arity(self) -> int: # type: ignore
|
| 168 |
+
raise NotImplementedError()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class FuncParamType(ParamType):
|
| 172 |
+
def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:
|
| 173 |
+
self.name: str = func.__name__
|
| 174 |
+
self.func = func
|
| 175 |
+
|
| 176 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 177 |
+
info_dict = super().to_info_dict()
|
| 178 |
+
info_dict["func"] = self.func
|
| 179 |
+
return info_dict
|
| 180 |
+
|
| 181 |
+
def convert(
|
| 182 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 183 |
+
) -> t.Any:
|
| 184 |
+
try:
|
| 185 |
+
return self.func(value)
|
| 186 |
+
except ValueError:
|
| 187 |
+
try:
|
| 188 |
+
value = str(value)
|
| 189 |
+
except UnicodeError:
|
| 190 |
+
value = value.decode("utf-8", "replace")
|
| 191 |
+
|
| 192 |
+
self.fail(value, param, ctx)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class UnprocessedParamType(ParamType):
|
| 196 |
+
name = "text"
|
| 197 |
+
|
| 198 |
+
def convert(
|
| 199 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 200 |
+
) -> t.Any:
|
| 201 |
+
return value
|
| 202 |
+
|
| 203 |
+
def __repr__(self) -> str:
|
| 204 |
+
return "UNPROCESSED"
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class StringParamType(ParamType):
|
| 208 |
+
name = "text"
|
| 209 |
+
|
| 210 |
+
def convert(
|
| 211 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 212 |
+
) -> t.Any:
|
| 213 |
+
if isinstance(value, bytes):
|
| 214 |
+
enc = _get_argv_encoding()
|
| 215 |
+
try:
|
| 216 |
+
value = value.decode(enc)
|
| 217 |
+
except UnicodeError:
|
| 218 |
+
fs_enc = sys.getfilesystemencoding()
|
| 219 |
+
if fs_enc != enc:
|
| 220 |
+
try:
|
| 221 |
+
value = value.decode(fs_enc)
|
| 222 |
+
except UnicodeError:
|
| 223 |
+
value = value.decode("utf-8", "replace")
|
| 224 |
+
else:
|
| 225 |
+
value = value.decode("utf-8", "replace")
|
| 226 |
+
return value
|
| 227 |
+
return str(value)
|
| 228 |
+
|
| 229 |
+
def __repr__(self) -> str:
|
| 230 |
+
return "STRING"
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class Choice(ParamType, t.Generic[ParamTypeValue]):
|
| 234 |
+
"""The choice type allows a value to be checked against a fixed set
|
| 235 |
+
of supported values.
|
| 236 |
+
|
| 237 |
+
You may pass any iterable value which will be converted to a tuple
|
| 238 |
+
and thus will only be iterated once.
|
| 239 |
+
|
| 240 |
+
The resulting value will always be one of the originally passed choices.
|
| 241 |
+
See :meth:`normalize_choice` for more info on the mapping of strings
|
| 242 |
+
to choices. See :ref:`choice-opts` for an example.
|
| 243 |
+
|
| 244 |
+
:param case_sensitive: Set to false to make choices case
|
| 245 |
+
insensitive. Defaults to true.
|
| 246 |
+
|
| 247 |
+
.. versionchanged:: 8.2.0
|
| 248 |
+
Non-``str`` ``choices`` are now supported. It can additionally be any
|
| 249 |
+
iterable. Before you were not recommended to pass anything but a list or
|
| 250 |
+
tuple.
|
| 251 |
+
|
| 252 |
+
.. versionadded:: 8.2.0
|
| 253 |
+
Choice normalization can be overridden via :meth:`normalize_choice`.
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
name = "choice"
|
| 257 |
+
|
| 258 |
+
def __init__(
|
| 259 |
+
self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True
|
| 260 |
+
) -> None:
|
| 261 |
+
self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)
|
| 262 |
+
self.case_sensitive = case_sensitive
|
| 263 |
+
|
| 264 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 265 |
+
info_dict = super().to_info_dict()
|
| 266 |
+
info_dict["choices"] = self.choices
|
| 267 |
+
info_dict["case_sensitive"] = self.case_sensitive
|
| 268 |
+
return info_dict
|
| 269 |
+
|
| 270 |
+
def _normalized_mapping(
|
| 271 |
+
self, ctx: Context | None = None
|
| 272 |
+
) -> cabc.Mapping[ParamTypeValue, str]:
|
| 273 |
+
"""
|
| 274 |
+
Returns mapping where keys are the original choices and the values are
|
| 275 |
+
the normalized values that are accepted via the command line.
|
| 276 |
+
|
| 277 |
+
This is a simple wrapper around :meth:`normalize_choice`, use that
|
| 278 |
+
instead which is supported.
|
| 279 |
+
"""
|
| 280 |
+
return {
|
| 281 |
+
choice: self.normalize_choice(
|
| 282 |
+
choice=choice,
|
| 283 |
+
ctx=ctx,
|
| 284 |
+
)
|
| 285 |
+
for choice in self.choices
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:
|
| 289 |
+
"""
|
| 290 |
+
Normalize a choice value, used to map a passed string to a choice.
|
| 291 |
+
Each choice must have a unique normalized value.
|
| 292 |
+
|
| 293 |
+
By default uses :meth:`Context.token_normalize_func` and if not case
|
| 294 |
+
sensitive, convert it to a casefolded value.
|
| 295 |
+
|
| 296 |
+
.. versionadded:: 8.2.0
|
| 297 |
+
"""
|
| 298 |
+
normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)
|
| 299 |
+
|
| 300 |
+
if ctx is not None and ctx.token_normalize_func is not None:
|
| 301 |
+
normed_value = ctx.token_normalize_func(normed_value)
|
| 302 |
+
|
| 303 |
+
if not self.case_sensitive:
|
| 304 |
+
normed_value = normed_value.casefold()
|
| 305 |
+
|
| 306 |
+
return normed_value
|
| 307 |
+
|
| 308 |
+
def get_metavar(self, param: Parameter, ctx: Context) -> str | None:
|
| 309 |
+
if param.param_type_name == "option" and not param.show_choices: # type: ignore
|
| 310 |
+
choice_metavars = [
|
| 311 |
+
convert_type(type(choice)).name.upper() for choice in self.choices
|
| 312 |
+
]
|
| 313 |
+
choices_str = "|".join([*dict.fromkeys(choice_metavars)])
|
| 314 |
+
else:
|
| 315 |
+
choices_str = "|".join(
|
| 316 |
+
[str(i) for i in self._normalized_mapping(ctx=ctx).values()]
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
# Use curly braces to indicate a required argument.
|
| 320 |
+
if param.required and param.param_type_name == "argument":
|
| 321 |
+
return f"{{{choices_str}}}"
|
| 322 |
+
|
| 323 |
+
# Use square braces to indicate an option or optional argument.
|
| 324 |
+
return f"[{choices_str}]"
|
| 325 |
+
|
| 326 |
+
def get_missing_message(self, param: Parameter, ctx: Context | None) -> str:
|
| 327 |
+
"""
|
| 328 |
+
Message shown when no choice is passed.
|
| 329 |
+
|
| 330 |
+
.. versionchanged:: 8.2.0 Added ``ctx`` argument.
|
| 331 |
+
"""
|
| 332 |
+
return _("Choose from:\n\t{choices}").format(
|
| 333 |
+
choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values())
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def convert(
|
| 337 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 338 |
+
) -> ParamTypeValue:
|
| 339 |
+
"""
|
| 340 |
+
For a given value from the parser, normalize it and find its
|
| 341 |
+
matching normalized value in the list of choices. Then return the
|
| 342 |
+
matched "original" choice.
|
| 343 |
+
"""
|
| 344 |
+
normed_value = self.normalize_choice(choice=value, ctx=ctx)
|
| 345 |
+
normalized_mapping = self._normalized_mapping(ctx=ctx)
|
| 346 |
+
|
| 347 |
+
try:
|
| 348 |
+
return next(
|
| 349 |
+
original
|
| 350 |
+
for original, normalized in normalized_mapping.items()
|
| 351 |
+
if normalized == normed_value
|
| 352 |
+
)
|
| 353 |
+
except StopIteration:
|
| 354 |
+
self.fail(
|
| 355 |
+
self.get_invalid_choice_message(value=value, ctx=ctx),
|
| 356 |
+
param=param,
|
| 357 |
+
ctx=ctx,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str:
|
| 361 |
+
"""Get the error message when the given choice is invalid.
|
| 362 |
+
|
| 363 |
+
:param value: The invalid value.
|
| 364 |
+
|
| 365 |
+
.. versionadded:: 8.2
|
| 366 |
+
"""
|
| 367 |
+
choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values()))
|
| 368 |
+
return ngettext(
|
| 369 |
+
"{value!r} is not {choice}.",
|
| 370 |
+
"{value!r} is not one of {choices}.",
|
| 371 |
+
len(self.choices),
|
| 372 |
+
).format(value=value, choice=choices_str, choices=choices_str)
|
| 373 |
+
|
| 374 |
+
def __repr__(self) -> str:
|
| 375 |
+
return f"Choice({list(self.choices)})"
|
| 376 |
+
|
| 377 |
+
def shell_complete(
|
| 378 |
+
self, ctx: Context, param: Parameter, incomplete: str
|
| 379 |
+
) -> list[CompletionItem]:
|
| 380 |
+
"""Complete choices that start with the incomplete value.
|
| 381 |
+
|
| 382 |
+
:param ctx: Invocation context for this command.
|
| 383 |
+
:param param: The parameter that is requesting completion.
|
| 384 |
+
:param incomplete: Value being completed. May be empty.
|
| 385 |
+
|
| 386 |
+
.. versionadded:: 8.0
|
| 387 |
+
"""
|
| 388 |
+
from click.shell_completion import CompletionItem
|
| 389 |
+
|
| 390 |
+
str_choices = map(str, self.choices)
|
| 391 |
+
|
| 392 |
+
if self.case_sensitive:
|
| 393 |
+
matched = (c for c in str_choices if c.startswith(incomplete))
|
| 394 |
+
else:
|
| 395 |
+
incomplete = incomplete.lower()
|
| 396 |
+
matched = (c for c in str_choices if c.lower().startswith(incomplete))
|
| 397 |
+
|
| 398 |
+
return [CompletionItem(c) for c in matched]
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
class DateTime(ParamType):
|
| 402 |
+
"""The DateTime type converts date strings into `datetime` objects.
|
| 403 |
+
|
| 404 |
+
The format strings which are checked are configurable, but default to some
|
| 405 |
+
common (non-timezone aware) ISO 8601 formats.
|
| 406 |
+
|
| 407 |
+
When specifying *DateTime* formats, you should only pass a list or a tuple.
|
| 408 |
+
Other iterables, like generators, may lead to surprising results.
|
| 409 |
+
|
| 410 |
+
The format strings are processed using ``datetime.strptime``, and this
|
| 411 |
+
consequently defines the format strings which are allowed.
|
| 412 |
+
|
| 413 |
+
Parsing is tried using each format, in order, and the first format which
|
| 414 |
+
parses successfully is used.
|
| 415 |
+
|
| 416 |
+
:param formats: A list or tuple of date format strings, in the order in
|
| 417 |
+
which they should be tried. Defaults to
|
| 418 |
+
``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,
|
| 419 |
+
``'%Y-%m-%d %H:%M:%S'``.
|
| 420 |
+
"""
|
| 421 |
+
|
| 422 |
+
name = "datetime"
|
| 423 |
+
|
| 424 |
+
def __init__(self, formats: cabc.Sequence[str] | None = None):
|
| 425 |
+
self.formats: cabc.Sequence[str] = formats or [
|
| 426 |
+
"%Y-%m-%d",
|
| 427 |
+
"%Y-%m-%dT%H:%M:%S",
|
| 428 |
+
"%Y-%m-%d %H:%M:%S",
|
| 429 |
+
]
|
| 430 |
+
|
| 431 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 432 |
+
info_dict = super().to_info_dict()
|
| 433 |
+
info_dict["formats"] = self.formats
|
| 434 |
+
return info_dict
|
| 435 |
+
|
| 436 |
+
def get_metavar(self, param: Parameter, ctx: Context) -> str | None:
|
| 437 |
+
return f"[{'|'.join(self.formats)}]"
|
| 438 |
+
|
| 439 |
+
def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:
|
| 440 |
+
try:
|
| 441 |
+
return datetime.strptime(value, format)
|
| 442 |
+
except ValueError:
|
| 443 |
+
return None
|
| 444 |
+
|
| 445 |
+
def convert(
|
| 446 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 447 |
+
) -> t.Any:
|
| 448 |
+
if isinstance(value, datetime):
|
| 449 |
+
return value
|
| 450 |
+
|
| 451 |
+
for format in self.formats:
|
| 452 |
+
converted = self._try_to_convert_date(value, format)
|
| 453 |
+
|
| 454 |
+
if converted is not None:
|
| 455 |
+
return converted
|
| 456 |
+
|
| 457 |
+
formats_str = ", ".join(map(repr, self.formats))
|
| 458 |
+
self.fail(
|
| 459 |
+
ngettext(
|
| 460 |
+
"{value!r} does not match the format {format}.",
|
| 461 |
+
"{value!r} does not match the formats {formats}.",
|
| 462 |
+
len(self.formats),
|
| 463 |
+
).format(value=value, format=formats_str, formats=formats_str),
|
| 464 |
+
param,
|
| 465 |
+
ctx,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
def __repr__(self) -> str:
|
| 469 |
+
return "DateTime"
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class _NumberParamTypeBase(ParamType):
|
| 473 |
+
_number_class: t.ClassVar[type[t.Any]]
|
| 474 |
+
|
| 475 |
+
def convert(
|
| 476 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 477 |
+
) -> t.Any:
|
| 478 |
+
try:
|
| 479 |
+
return self._number_class(value)
|
| 480 |
+
except ValueError:
|
| 481 |
+
self.fail(
|
| 482 |
+
_("{value!r} is not a valid {number_type}.").format(
|
| 483 |
+
value=value, number_type=self.name
|
| 484 |
+
),
|
| 485 |
+
param,
|
| 486 |
+
ctx,
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class _NumberRangeBase(_NumberParamTypeBase):
|
| 491 |
+
def __init__(
|
| 492 |
+
self,
|
| 493 |
+
min: float | None = None,
|
| 494 |
+
max: float | None = None,
|
| 495 |
+
min_open: bool = False,
|
| 496 |
+
max_open: bool = False,
|
| 497 |
+
clamp: bool = False,
|
| 498 |
+
) -> None:
|
| 499 |
+
self.min = min
|
| 500 |
+
self.max = max
|
| 501 |
+
self.min_open = min_open
|
| 502 |
+
self.max_open = max_open
|
| 503 |
+
self.clamp = clamp
|
| 504 |
+
|
| 505 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 506 |
+
info_dict = super().to_info_dict()
|
| 507 |
+
info_dict.update(
|
| 508 |
+
min=self.min,
|
| 509 |
+
max=self.max,
|
| 510 |
+
min_open=self.min_open,
|
| 511 |
+
max_open=self.max_open,
|
| 512 |
+
clamp=self.clamp,
|
| 513 |
+
)
|
| 514 |
+
return info_dict
|
| 515 |
+
|
| 516 |
+
def convert(
|
| 517 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 518 |
+
) -> t.Any:
|
| 519 |
+
import operator
|
| 520 |
+
|
| 521 |
+
rv = super().convert(value, param, ctx)
|
| 522 |
+
lt_min: bool = self.min is not None and (
|
| 523 |
+
operator.le if self.min_open else operator.lt
|
| 524 |
+
)(rv, self.min)
|
| 525 |
+
gt_max: bool = self.max is not None and (
|
| 526 |
+
operator.ge if self.max_open else operator.gt
|
| 527 |
+
)(rv, self.max)
|
| 528 |
+
|
| 529 |
+
if self.clamp:
|
| 530 |
+
if lt_min:
|
| 531 |
+
return self._clamp(self.min, 1, self.min_open) # type: ignore
|
| 532 |
+
|
| 533 |
+
if gt_max:
|
| 534 |
+
return self._clamp(self.max, -1, self.max_open) # type: ignore
|
| 535 |
+
|
| 536 |
+
if lt_min or gt_max:
|
| 537 |
+
self.fail(
|
| 538 |
+
_("{value} is not in the range {range}.").format(
|
| 539 |
+
value=rv, range=self._describe_range()
|
| 540 |
+
),
|
| 541 |
+
param,
|
| 542 |
+
ctx,
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
return rv
|
| 546 |
+
|
| 547 |
+
def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:
|
| 548 |
+
"""Find the valid value to clamp to bound in the given
|
| 549 |
+
direction.
|
| 550 |
+
|
| 551 |
+
:param bound: The boundary value.
|
| 552 |
+
:param dir: 1 or -1 indicating the direction to move.
|
| 553 |
+
:param open: If true, the range does not include the bound.
|
| 554 |
+
"""
|
| 555 |
+
raise NotImplementedError
|
| 556 |
+
|
| 557 |
+
def _describe_range(self) -> str:
|
| 558 |
+
"""Describe the range for use in help text."""
|
| 559 |
+
if self.min is None:
|
| 560 |
+
op = "<" if self.max_open else "<="
|
| 561 |
+
return f"x{op}{self.max}"
|
| 562 |
+
|
| 563 |
+
if self.max is None:
|
| 564 |
+
op = ">" if self.min_open else ">="
|
| 565 |
+
return f"x{op}{self.min}"
|
| 566 |
+
|
| 567 |
+
lop = "<" if self.min_open else "<="
|
| 568 |
+
rop = "<" if self.max_open else "<="
|
| 569 |
+
return f"{self.min}{lop}x{rop}{self.max}"
|
| 570 |
+
|
| 571 |
+
def __repr__(self) -> str:
|
| 572 |
+
clamp = " clamped" if self.clamp else ""
|
| 573 |
+
return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
class IntParamType(_NumberParamTypeBase):
|
| 577 |
+
name = "integer"
|
| 578 |
+
_number_class = int
|
| 579 |
+
|
| 580 |
+
def __repr__(self) -> str:
|
| 581 |
+
return "INT"
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
class IntRange(_NumberRangeBase, IntParamType):
|
| 585 |
+
"""Restrict an :data:`click.INT` value to a range of accepted
|
| 586 |
+
values. See :ref:`ranges`.
|
| 587 |
+
|
| 588 |
+
If ``min`` or ``max`` are not passed, any value is accepted in that
|
| 589 |
+
direction. If ``min_open`` or ``max_open`` are enabled, the
|
| 590 |
+
corresponding boundary is not included in the range.
|
| 591 |
+
|
| 592 |
+
If ``clamp`` is enabled, a value outside the range is clamped to the
|
| 593 |
+
boundary instead of failing.
|
| 594 |
+
|
| 595 |
+
.. versionchanged:: 8.0
|
| 596 |
+
Added the ``min_open`` and ``max_open`` parameters.
|
| 597 |
+
"""
|
| 598 |
+
|
| 599 |
+
name = "integer range"
|
| 600 |
+
|
| 601 |
+
def _clamp( # type: ignore
|
| 602 |
+
self, bound: int, dir: t.Literal[1, -1], open: bool
|
| 603 |
+
) -> int:
|
| 604 |
+
if not open:
|
| 605 |
+
return bound
|
| 606 |
+
|
| 607 |
+
return bound + dir
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
class FloatParamType(_NumberParamTypeBase):
|
| 611 |
+
name = "float"
|
| 612 |
+
_number_class = float
|
| 613 |
+
|
| 614 |
+
def __repr__(self) -> str:
|
| 615 |
+
return "FLOAT"
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class FloatRange(_NumberRangeBase, FloatParamType):
|
| 619 |
+
"""Restrict a :data:`click.FLOAT` value to a range of accepted
|
| 620 |
+
values. See :ref:`ranges`.
|
| 621 |
+
|
| 622 |
+
If ``min`` or ``max`` are not passed, any value is accepted in that
|
| 623 |
+
direction. If ``min_open`` or ``max_open`` are enabled, the
|
| 624 |
+
corresponding boundary is not included in the range.
|
| 625 |
+
|
| 626 |
+
If ``clamp`` is enabled, a value outside the range is clamped to the
|
| 627 |
+
boundary instead of failing. This is not supported if either
|
| 628 |
+
boundary is marked ``open``.
|
| 629 |
+
|
| 630 |
+
.. versionchanged:: 8.0
|
| 631 |
+
Added the ``min_open`` and ``max_open`` parameters.
|
| 632 |
+
"""
|
| 633 |
+
|
| 634 |
+
name = "float range"
|
| 635 |
+
|
| 636 |
+
def __init__(
|
| 637 |
+
self,
|
| 638 |
+
min: float | None = None,
|
| 639 |
+
max: float | None = None,
|
| 640 |
+
min_open: bool = False,
|
| 641 |
+
max_open: bool = False,
|
| 642 |
+
clamp: bool = False,
|
| 643 |
+
) -> None:
|
| 644 |
+
super().__init__(
|
| 645 |
+
min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
if (min_open or max_open) and clamp:
|
| 649 |
+
raise TypeError("Clamping is not supported for open bounds.")
|
| 650 |
+
|
| 651 |
+
def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:
|
| 652 |
+
if not open:
|
| 653 |
+
return bound
|
| 654 |
+
|
| 655 |
+
# Could use math.nextafter here, but clamping an
|
| 656 |
+
# open float range doesn't seem to be particularly useful. It's
|
| 657 |
+
# left up to the user to write a callback to do it if needed.
|
| 658 |
+
raise RuntimeError("Clamping is not supported for open bounds.")
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
class BoolParamType(ParamType):
|
| 662 |
+
name = "boolean"
|
| 663 |
+
|
| 664 |
+
bool_states: dict[str, bool] = {
|
| 665 |
+
"1": True,
|
| 666 |
+
"0": False,
|
| 667 |
+
"yes": True,
|
| 668 |
+
"no": False,
|
| 669 |
+
"true": True,
|
| 670 |
+
"false": False,
|
| 671 |
+
"on": True,
|
| 672 |
+
"off": False,
|
| 673 |
+
"t": True,
|
| 674 |
+
"f": False,
|
| 675 |
+
"y": True,
|
| 676 |
+
"n": False,
|
| 677 |
+
# Absence of value is considered False.
|
| 678 |
+
"": False,
|
| 679 |
+
}
|
| 680 |
+
"""A mapping of string values to boolean states.
|
| 681 |
+
|
| 682 |
+
Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`
|
| 683 |
+
and extends it.
|
| 684 |
+
|
| 685 |
+
.. caution::
|
| 686 |
+
String values are lower-cased, as the ``str_to_bool`` comparison function
|
| 687 |
+
below is case-insensitive.
|
| 688 |
+
|
| 689 |
+
.. warning::
|
| 690 |
+
The mapping is not exhaustive, and does not cover all possible boolean strings
|
| 691 |
+
representations. It will remains as it is to avoid endless bikeshedding.
|
| 692 |
+
|
| 693 |
+
Future work my be considered to make this mapping user-configurable from public
|
| 694 |
+
API.
|
| 695 |
+
"""
|
| 696 |
+
|
| 697 |
+
@staticmethod
|
| 698 |
+
def str_to_bool(value: str | bool) -> bool | None:
|
| 699 |
+
"""Convert a string to a boolean value.
|
| 700 |
+
|
| 701 |
+
If the value is already a boolean, it is returned as-is. If the value is a
|
| 702 |
+
string, it is stripped of whitespaces and lower-cased, then checked against
|
| 703 |
+
the known boolean states pre-defined in the `BoolParamType.bool_states` mapping
|
| 704 |
+
above.
|
| 705 |
+
|
| 706 |
+
Returns `None` if the value does not match any known boolean state.
|
| 707 |
+
"""
|
| 708 |
+
if isinstance(value, bool):
|
| 709 |
+
return value
|
| 710 |
+
return BoolParamType.bool_states.get(value.strip().lower())
|
| 711 |
+
|
| 712 |
+
def convert(
|
| 713 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 714 |
+
) -> bool:
|
| 715 |
+
normalized = self.str_to_bool(value)
|
| 716 |
+
if normalized is None:
|
| 717 |
+
self.fail(
|
| 718 |
+
_(
|
| 719 |
+
"{value!r} is not a valid boolean. Recognized values: {states}"
|
| 720 |
+
).format(value=value, states=", ".join(sorted(self.bool_states))),
|
| 721 |
+
param,
|
| 722 |
+
ctx,
|
| 723 |
+
)
|
| 724 |
+
return normalized
|
| 725 |
+
|
| 726 |
+
def __repr__(self) -> str:
|
| 727 |
+
return "BOOL"
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
class UUIDParameterType(ParamType):
|
| 731 |
+
name = "uuid"
|
| 732 |
+
|
| 733 |
+
def convert(
|
| 734 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 735 |
+
) -> t.Any:
|
| 736 |
+
import uuid
|
| 737 |
+
|
| 738 |
+
if isinstance(value, uuid.UUID):
|
| 739 |
+
return value
|
| 740 |
+
|
| 741 |
+
value = value.strip()
|
| 742 |
+
|
| 743 |
+
try:
|
| 744 |
+
return uuid.UUID(value)
|
| 745 |
+
except ValueError:
|
| 746 |
+
self.fail(
|
| 747 |
+
_("{value!r} is not a valid UUID.").format(value=value), param, ctx
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
def __repr__(self) -> str:
|
| 751 |
+
return "UUID"
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class File(ParamType):
|
| 755 |
+
"""Declares a parameter to be a file for reading or writing. The file
|
| 756 |
+
is automatically closed once the context tears down (after the command
|
| 757 |
+
finished working).
|
| 758 |
+
|
| 759 |
+
Files can be opened for reading or writing. The special value ``-``
|
| 760 |
+
indicates stdin or stdout depending on the mode.
|
| 761 |
+
|
| 762 |
+
By default, the file is opened for reading text data, but it can also be
|
| 763 |
+
opened in binary mode or for writing. The encoding parameter can be used
|
| 764 |
+
to force a specific encoding.
|
| 765 |
+
|
| 766 |
+
The `lazy` flag controls if the file should be opened immediately or upon
|
| 767 |
+
first IO. The default is to be non-lazy for standard input and output
|
| 768 |
+
streams as well as files opened for reading, `lazy` otherwise. When opening a
|
| 769 |
+
file lazily for reading, it is still opened temporarily for validation, but
|
| 770 |
+
will not be held open until first IO. lazy is mainly useful when opening
|
| 771 |
+
for writing to avoid creating the file until it is needed.
|
| 772 |
+
|
| 773 |
+
Files can also be opened atomically in which case all writes go into a
|
| 774 |
+
separate file in the same folder and upon completion the file will
|
| 775 |
+
be moved over to the original location. This is useful if a file
|
| 776 |
+
regularly read by other users is modified.
|
| 777 |
+
|
| 778 |
+
See :ref:`file-args` for more information.
|
| 779 |
+
|
| 780 |
+
.. versionchanged:: 2.0
|
| 781 |
+
Added the ``atomic`` parameter.
|
| 782 |
+
"""
|
| 783 |
+
|
| 784 |
+
name = "filename"
|
| 785 |
+
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
|
| 786 |
+
|
| 787 |
+
def __init__(
|
| 788 |
+
self,
|
| 789 |
+
mode: str = "r",
|
| 790 |
+
encoding: str | None = None,
|
| 791 |
+
errors: str | None = "strict",
|
| 792 |
+
lazy: bool | None = None,
|
| 793 |
+
atomic: bool = False,
|
| 794 |
+
) -> None:
|
| 795 |
+
self.mode = mode
|
| 796 |
+
self.encoding = encoding
|
| 797 |
+
self.errors = errors
|
| 798 |
+
self.lazy = lazy
|
| 799 |
+
self.atomic = atomic
|
| 800 |
+
|
| 801 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 802 |
+
info_dict = super().to_info_dict()
|
| 803 |
+
info_dict.update(mode=self.mode, encoding=self.encoding)
|
| 804 |
+
return info_dict
|
| 805 |
+
|
| 806 |
+
def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:
|
| 807 |
+
if self.lazy is not None:
|
| 808 |
+
return self.lazy
|
| 809 |
+
if os.fspath(value) == "-":
|
| 810 |
+
return False
|
| 811 |
+
elif "w" in self.mode:
|
| 812 |
+
return True
|
| 813 |
+
return False
|
| 814 |
+
|
| 815 |
+
def convert(
|
| 816 |
+
self,
|
| 817 |
+
value: str | os.PathLike[str] | t.IO[t.Any],
|
| 818 |
+
param: Parameter | None,
|
| 819 |
+
ctx: Context | None,
|
| 820 |
+
) -> t.IO[t.Any]:
|
| 821 |
+
if _is_file_like(value):
|
| 822 |
+
return value
|
| 823 |
+
|
| 824 |
+
value = t.cast("str | os.PathLike[str]", value)
|
| 825 |
+
|
| 826 |
+
try:
|
| 827 |
+
lazy = self.resolve_lazy_flag(value)
|
| 828 |
+
|
| 829 |
+
if lazy:
|
| 830 |
+
lf = LazyFile(
|
| 831 |
+
value, self.mode, self.encoding, self.errors, atomic=self.atomic
|
| 832 |
+
)
|
| 833 |
+
|
| 834 |
+
if ctx is not None:
|
| 835 |
+
ctx.call_on_close(lf.close_intelligently)
|
| 836 |
+
|
| 837 |
+
return t.cast("t.IO[t.Any]", lf)
|
| 838 |
+
|
| 839 |
+
f, should_close = open_stream(
|
| 840 |
+
value, self.mode, self.encoding, self.errors, atomic=self.atomic
|
| 841 |
+
)
|
| 842 |
+
|
| 843 |
+
# If a context is provided, we automatically close the file
|
| 844 |
+
# at the end of the context execution (or flush out). If a
|
| 845 |
+
# context does not exist, it's the caller's responsibility to
|
| 846 |
+
# properly close the file. This for instance happens when the
|
| 847 |
+
# type is used with prompts.
|
| 848 |
+
if ctx is not None:
|
| 849 |
+
if should_close:
|
| 850 |
+
ctx.call_on_close(safecall(f.close))
|
| 851 |
+
else:
|
| 852 |
+
ctx.call_on_close(safecall(f.flush))
|
| 853 |
+
|
| 854 |
+
return f
|
| 855 |
+
except OSError as e:
|
| 856 |
+
self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)
|
| 857 |
+
|
| 858 |
+
def shell_complete(
|
| 859 |
+
self, ctx: Context, param: Parameter, incomplete: str
|
| 860 |
+
) -> list[CompletionItem]:
|
| 861 |
+
"""Return a special completion marker that tells the completion
|
| 862 |
+
system to use the shell to provide file path completions.
|
| 863 |
+
|
| 864 |
+
:param ctx: Invocation context for this command.
|
| 865 |
+
:param param: The parameter that is requesting completion.
|
| 866 |
+
:param incomplete: Value being completed. May be empty.
|
| 867 |
+
|
| 868 |
+
.. versionadded:: 8.0
|
| 869 |
+
"""
|
| 870 |
+
from click.shell_completion import CompletionItem
|
| 871 |
+
|
| 872 |
+
return [CompletionItem(incomplete, type="file")]
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:
|
| 876 |
+
return hasattr(value, "read") or hasattr(value, "write")
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
class Path(ParamType):
|
| 880 |
+
"""The ``Path`` type is similar to the :class:`File` type, but
|
| 881 |
+
returns the filename instead of an open file. Various checks can be
|
| 882 |
+
enabled to validate the type of file and permissions.
|
| 883 |
+
|
| 884 |
+
:param exists: The file or directory needs to exist for the value to
|
| 885 |
+
be valid. If this is not set to ``True``, and the file does not
|
| 886 |
+
exist, then all further checks are silently skipped.
|
| 887 |
+
:param file_okay: Allow a file as a value.
|
| 888 |
+
:param dir_okay: Allow a directory as a value.
|
| 889 |
+
:param readable: if true, a readable check is performed.
|
| 890 |
+
:param writable: if true, a writable check is performed.
|
| 891 |
+
:param executable: if true, an executable check is performed.
|
| 892 |
+
:param resolve_path: Make the value absolute and resolve any
|
| 893 |
+
symlinks. A ``~`` is not expanded, as this is supposed to be
|
| 894 |
+
done by the shell only.
|
| 895 |
+
:param allow_dash: Allow a single dash as a value, which indicates
|
| 896 |
+
a standard stream (but does not open it). Use
|
| 897 |
+
:func:`~click.open_file` to handle opening this value.
|
| 898 |
+
:param path_type: Convert the incoming path value to this type. If
|
| 899 |
+
``None``, keep Python's default, which is ``str``. Useful to
|
| 900 |
+
convert to :class:`pathlib.Path`.
|
| 901 |
+
|
| 902 |
+
.. versionchanged:: 8.1
|
| 903 |
+
Added the ``executable`` parameter.
|
| 904 |
+
|
| 905 |
+
.. versionchanged:: 8.0
|
| 906 |
+
Allow passing ``path_type=pathlib.Path``.
|
| 907 |
+
|
| 908 |
+
.. versionchanged:: 6.0
|
| 909 |
+
Added the ``allow_dash`` parameter.
|
| 910 |
+
"""
|
| 911 |
+
|
| 912 |
+
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
|
| 913 |
+
|
| 914 |
+
def __init__(
|
| 915 |
+
self,
|
| 916 |
+
exists: bool = False,
|
| 917 |
+
file_okay: bool = True,
|
| 918 |
+
dir_okay: bool = True,
|
| 919 |
+
writable: bool = False,
|
| 920 |
+
readable: bool = True,
|
| 921 |
+
resolve_path: bool = False,
|
| 922 |
+
allow_dash: bool = False,
|
| 923 |
+
path_type: type[t.Any] | None = None,
|
| 924 |
+
executable: bool = False,
|
| 925 |
+
):
|
| 926 |
+
self.exists = exists
|
| 927 |
+
self.file_okay = file_okay
|
| 928 |
+
self.dir_okay = dir_okay
|
| 929 |
+
self.readable = readable
|
| 930 |
+
self.writable = writable
|
| 931 |
+
self.executable = executable
|
| 932 |
+
self.resolve_path = resolve_path
|
| 933 |
+
self.allow_dash = allow_dash
|
| 934 |
+
self.type = path_type
|
| 935 |
+
|
| 936 |
+
if self.file_okay and not self.dir_okay:
|
| 937 |
+
self.name: str = _("file")
|
| 938 |
+
elif self.dir_okay and not self.file_okay:
|
| 939 |
+
self.name = _("directory")
|
| 940 |
+
else:
|
| 941 |
+
self.name = _("path")
|
| 942 |
+
|
| 943 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 944 |
+
info_dict = super().to_info_dict()
|
| 945 |
+
info_dict.update(
|
| 946 |
+
exists=self.exists,
|
| 947 |
+
file_okay=self.file_okay,
|
| 948 |
+
dir_okay=self.dir_okay,
|
| 949 |
+
writable=self.writable,
|
| 950 |
+
readable=self.readable,
|
| 951 |
+
allow_dash=self.allow_dash,
|
| 952 |
+
)
|
| 953 |
+
return info_dict
|
| 954 |
+
|
| 955 |
+
def coerce_path_result(
|
| 956 |
+
self, value: str | os.PathLike[str]
|
| 957 |
+
) -> str | bytes | os.PathLike[str]:
|
| 958 |
+
if self.type is not None and not isinstance(value, self.type):
|
| 959 |
+
if self.type is str:
|
| 960 |
+
return os.fsdecode(value)
|
| 961 |
+
elif self.type is bytes:
|
| 962 |
+
return os.fsencode(value)
|
| 963 |
+
else:
|
| 964 |
+
return t.cast("os.PathLike[str]", self.type(value))
|
| 965 |
+
|
| 966 |
+
return value
|
| 967 |
+
|
| 968 |
+
def convert(
|
| 969 |
+
self,
|
| 970 |
+
value: str | os.PathLike[str],
|
| 971 |
+
param: Parameter | None,
|
| 972 |
+
ctx: Context | None,
|
| 973 |
+
) -> str | bytes | os.PathLike[str]:
|
| 974 |
+
rv = value
|
| 975 |
+
|
| 976 |
+
is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")
|
| 977 |
+
|
| 978 |
+
if not is_dash:
|
| 979 |
+
if self.resolve_path:
|
| 980 |
+
rv = os.path.realpath(rv)
|
| 981 |
+
|
| 982 |
+
try:
|
| 983 |
+
st = os.stat(rv)
|
| 984 |
+
except OSError:
|
| 985 |
+
if not self.exists:
|
| 986 |
+
return self.coerce_path_result(rv)
|
| 987 |
+
self.fail(
|
| 988 |
+
_("{name} {filename!r} does not exist.").format(
|
| 989 |
+
name=self.name.title(), filename=format_filename(value)
|
| 990 |
+
),
|
| 991 |
+
param,
|
| 992 |
+
ctx,
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
if not self.file_okay and stat.S_ISREG(st.st_mode):
|
| 996 |
+
self.fail(
|
| 997 |
+
_("{name} {filename!r} is a file.").format(
|
| 998 |
+
name=self.name.title(), filename=format_filename(value)
|
| 999 |
+
),
|
| 1000 |
+
param,
|
| 1001 |
+
ctx,
|
| 1002 |
+
)
|
| 1003 |
+
if not self.dir_okay and stat.S_ISDIR(st.st_mode):
|
| 1004 |
+
self.fail(
|
| 1005 |
+
_("{name} {filename!r} is a directory.").format(
|
| 1006 |
+
name=self.name.title(), filename=format_filename(value)
|
| 1007 |
+
),
|
| 1008 |
+
param,
|
| 1009 |
+
ctx,
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
if self.readable and not os.access(rv, os.R_OK):
|
| 1013 |
+
self.fail(
|
| 1014 |
+
_("{name} {filename!r} is not readable.").format(
|
| 1015 |
+
name=self.name.title(), filename=format_filename(value)
|
| 1016 |
+
),
|
| 1017 |
+
param,
|
| 1018 |
+
ctx,
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
if self.writable and not os.access(rv, os.W_OK):
|
| 1022 |
+
self.fail(
|
| 1023 |
+
_("{name} {filename!r} is not writable.").format(
|
| 1024 |
+
name=self.name.title(), filename=format_filename(value)
|
| 1025 |
+
),
|
| 1026 |
+
param,
|
| 1027 |
+
ctx,
|
| 1028 |
+
)
|
| 1029 |
+
|
| 1030 |
+
if self.executable and not os.access(value, os.X_OK):
|
| 1031 |
+
self.fail(
|
| 1032 |
+
_("{name} {filename!r} is not executable.").format(
|
| 1033 |
+
name=self.name.title(), filename=format_filename(value)
|
| 1034 |
+
),
|
| 1035 |
+
param,
|
| 1036 |
+
ctx,
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
return self.coerce_path_result(rv)
|
| 1040 |
+
|
| 1041 |
+
def shell_complete(
|
| 1042 |
+
self, ctx: Context, param: Parameter, incomplete: str
|
| 1043 |
+
) -> list[CompletionItem]:
|
| 1044 |
+
"""Return a special completion marker that tells the completion
|
| 1045 |
+
system to use the shell to provide path completions for only
|
| 1046 |
+
directories or any paths.
|
| 1047 |
+
|
| 1048 |
+
:param ctx: Invocation context for this command.
|
| 1049 |
+
:param param: The parameter that is requesting completion.
|
| 1050 |
+
:param incomplete: Value being completed. May be empty.
|
| 1051 |
+
|
| 1052 |
+
.. versionadded:: 8.0
|
| 1053 |
+
"""
|
| 1054 |
+
from click.shell_completion import CompletionItem
|
| 1055 |
+
|
| 1056 |
+
type = "dir" if self.dir_okay and not self.file_okay else "file"
|
| 1057 |
+
return [CompletionItem(incomplete, type=type)]
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
class Tuple(CompositeParamType):
|
| 1061 |
+
"""The default behavior of Click is to apply a type on a value directly.
|
| 1062 |
+
This works well in most cases, except for when `nargs` is set to a fixed
|
| 1063 |
+
count and different types should be used for different items. In this
|
| 1064 |
+
case the :class:`Tuple` type can be used. This type can only be used
|
| 1065 |
+
if `nargs` is set to a fixed number.
|
| 1066 |
+
|
| 1067 |
+
For more information see :ref:`tuple-type`.
|
| 1068 |
+
|
| 1069 |
+
This can be selected by using a Python tuple literal as a type.
|
| 1070 |
+
|
| 1071 |
+
:param types: a list of types that should be used for the tuple items.
|
| 1072 |
+
"""
|
| 1073 |
+
|
| 1074 |
+
def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None:
|
| 1075 |
+
self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]
|
| 1076 |
+
|
| 1077 |
+
def to_info_dict(self) -> dict[str, t.Any]:
|
| 1078 |
+
info_dict = super().to_info_dict()
|
| 1079 |
+
info_dict["types"] = [t.to_info_dict() for t in self.types]
|
| 1080 |
+
return info_dict
|
| 1081 |
+
|
| 1082 |
+
@property
|
| 1083 |
+
def name(self) -> str: # type: ignore
|
| 1084 |
+
return f"<{' '.join(ty.name for ty in self.types)}>"
|
| 1085 |
+
|
| 1086 |
+
@property
|
| 1087 |
+
def arity(self) -> int: # type: ignore
|
| 1088 |
+
return len(self.types)
|
| 1089 |
+
|
| 1090 |
+
def convert(
|
| 1091 |
+
self, value: t.Any, param: Parameter | None, ctx: Context | None
|
| 1092 |
+
) -> t.Any:
|
| 1093 |
+
len_type = len(self.types)
|
| 1094 |
+
len_value = len(value)
|
| 1095 |
+
|
| 1096 |
+
if len_value != len_type:
|
| 1097 |
+
self.fail(
|
| 1098 |
+
ngettext(
|
| 1099 |
+
"{len_type} values are required, but {len_value} was given.",
|
| 1100 |
+
"{len_type} values are required, but {len_value} were given.",
|
| 1101 |
+
len_value,
|
| 1102 |
+
).format(len_type=len_type, len_value=len_value),
|
| 1103 |
+
param=param,
|
| 1104 |
+
ctx=ctx,
|
| 1105 |
+
)
|
| 1106 |
+
|
| 1107 |
+
return tuple(
|
| 1108 |
+
ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)
|
| 1109 |
+
)
|
| 1110 |
+
|
| 1111 |
+
|
| 1112 |
+
def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:
|
| 1113 |
+
"""Find the most appropriate :class:`ParamType` for the given Python
|
| 1114 |
+
type. If the type isn't provided, it can be inferred from a default
|
| 1115 |
+
value.
|
| 1116 |
+
"""
|
| 1117 |
+
guessed_type = False
|
| 1118 |
+
|
| 1119 |
+
if ty is None and default is not None:
|
| 1120 |
+
if isinstance(default, (tuple, list)):
|
| 1121 |
+
# If the default is empty, ty will remain None and will
|
| 1122 |
+
# return STRING.
|
| 1123 |
+
if default:
|
| 1124 |
+
item = default[0]
|
| 1125 |
+
|
| 1126 |
+
# A tuple of tuples needs to detect the inner types.
|
| 1127 |
+
# Can't call convert recursively because that would
|
| 1128 |
+
# incorrectly unwind the tuple to a single type.
|
| 1129 |
+
if isinstance(item, (tuple, list)):
|
| 1130 |
+
ty = tuple(map(type, item))
|
| 1131 |
+
else:
|
| 1132 |
+
ty = type(item)
|
| 1133 |
+
else:
|
| 1134 |
+
ty = type(default)
|
| 1135 |
+
|
| 1136 |
+
guessed_type = True
|
| 1137 |
+
|
| 1138 |
+
if isinstance(ty, tuple):
|
| 1139 |
+
return Tuple(ty)
|
| 1140 |
+
|
| 1141 |
+
if isinstance(ty, ParamType):
|
| 1142 |
+
return ty
|
| 1143 |
+
|
| 1144 |
+
if ty is str or ty is None:
|
| 1145 |
+
return STRING
|
| 1146 |
+
|
| 1147 |
+
if ty is int:
|
| 1148 |
+
return INT
|
| 1149 |
+
|
| 1150 |
+
if ty is float:
|
| 1151 |
+
return FLOAT
|
| 1152 |
+
|
| 1153 |
+
if ty is bool:
|
| 1154 |
+
return BOOL
|
| 1155 |
+
|
| 1156 |
+
if guessed_type:
|
| 1157 |
+
return STRING
|
| 1158 |
+
|
| 1159 |
+
if __debug__:
|
| 1160 |
+
try:
|
| 1161 |
+
if issubclass(ty, ParamType):
|
| 1162 |
+
raise AssertionError(
|
| 1163 |
+
f"Attempted to use an uninstantiated parameter type ({ty})."
|
| 1164 |
+
)
|
| 1165 |
+
except TypeError:
|
| 1166 |
+
# ty is an instance (correct), so issubclass fails.
|
| 1167 |
+
pass
|
| 1168 |
+
|
| 1169 |
+
return FuncParamType(ty)
|
| 1170 |
+
|
| 1171 |
+
|
| 1172 |
+
#: A dummy parameter type that just does nothing. From a user's
|
| 1173 |
+
#: perspective this appears to just be the same as `STRING` but
|
| 1174 |
+
#: internally no string conversion takes place if the input was bytes.
|
| 1175 |
+
#: This is usually useful when working with file paths as they can
|
| 1176 |
+
#: appear in bytes and unicode.
|
| 1177 |
+
#:
|
| 1178 |
+
#: For path related uses the :class:`Path` type is a better choice but
|
| 1179 |
+
#: there are situations where an unprocessed type is useful which is why
|
| 1180 |
+
#: it is is provided.
|
| 1181 |
+
#:
|
| 1182 |
+
#: .. versionadded:: 4.0
|
| 1183 |
+
UNPROCESSED = UnprocessedParamType()
|
| 1184 |
+
|
| 1185 |
+
#: A unicode string parameter type which is the implicit default. This
|
| 1186 |
+
#: can also be selected by using ``str`` as type.
|
| 1187 |
+
STRING = StringParamType()
|
| 1188 |
+
|
| 1189 |
+
#: An integer parameter. This can also be selected by using ``int`` as
|
| 1190 |
+
#: type.
|
| 1191 |
+
INT = IntParamType()
|
| 1192 |
+
|
| 1193 |
+
#: A floating point value parameter. This can also be selected by using
|
| 1194 |
+
#: ``float`` as type.
|
| 1195 |
+
FLOAT = FloatParamType()
|
| 1196 |
+
|
| 1197 |
+
#: A boolean parameter. This is the default for boolean flags. This can
|
| 1198 |
+
#: also be selected by using ``bool`` as a type.
|
| 1199 |
+
BOOL = BoolParamType()
|
| 1200 |
+
|
| 1201 |
+
#: A UUID parameter.
|
| 1202 |
+
UUID = UUIDParameterType()
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
class OptionHelpExtra(t.TypedDict, total=False):
|
| 1206 |
+
envvars: tuple[str, ...]
|
| 1207 |
+
default: str
|
| 1208 |
+
range: str
|
| 1209 |
+
required: str
|
.cache/uv/archive-v0/68XaObtIWaNp5r1uyoeZg/click/utils.py
ADDED
|
@@ -0,0 +1,627 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import typing as t
|
| 8 |
+
from functools import update_wrapper
|
| 9 |
+
from types import ModuleType
|
| 10 |
+
from types import TracebackType
|
| 11 |
+
|
| 12 |
+
from ._compat import _default_text_stderr
|
| 13 |
+
from ._compat import _default_text_stdout
|
| 14 |
+
from ._compat import _find_binary_writer
|
| 15 |
+
from ._compat import auto_wrap_for_ansi
|
| 16 |
+
from ._compat import binary_streams
|
| 17 |
+
from ._compat import open_stream
|
| 18 |
+
from ._compat import should_strip_ansi
|
| 19 |
+
from ._compat import strip_ansi
|
| 20 |
+
from ._compat import text_streams
|
| 21 |
+
from ._compat import WIN
|
| 22 |
+
from .globals import resolve_color_default
|
| 23 |
+
|
| 24 |
+
if t.TYPE_CHECKING:
|
| 25 |
+
import typing_extensions as te
|
| 26 |
+
|
| 27 |
+
P = te.ParamSpec("P")
|
| 28 |
+
|
| 29 |
+
R = t.TypeVar("R")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _posixify(name: str) -> str:
|
| 33 |
+
return "-".join(name.split()).lower()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:
|
| 37 |
+
"""Wraps a function so that it swallows exceptions."""
|
| 38 |
+
|
| 39 |
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
|
| 40 |
+
try:
|
| 41 |
+
return func(*args, **kwargs)
|
| 42 |
+
except Exception:
|
| 43 |
+
pass
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
return update_wrapper(wrapper, func)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def make_str(value: t.Any) -> str:
|
| 50 |
+
"""Converts a value into a valid string."""
|
| 51 |
+
if isinstance(value, bytes):
|
| 52 |
+
try:
|
| 53 |
+
return value.decode(sys.getfilesystemencoding())
|
| 54 |
+
except UnicodeError:
|
| 55 |
+
return value.decode("utf-8", "replace")
|
| 56 |
+
return str(value)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def make_default_short_help(help: str, max_length: int = 45) -> str:
|
| 60 |
+
"""Returns a condensed version of help string."""
|
| 61 |
+
# Consider only the first paragraph.
|
| 62 |
+
paragraph_end = help.find("\n\n")
|
| 63 |
+
|
| 64 |
+
if paragraph_end != -1:
|
| 65 |
+
help = help[:paragraph_end]
|
| 66 |
+
|
| 67 |
+
# Collapse newlines, tabs, and spaces.
|
| 68 |
+
words = help.split()
|
| 69 |
+
|
| 70 |
+
if not words:
|
| 71 |
+
return ""
|
| 72 |
+
|
| 73 |
+
# The first paragraph started with a "no rewrap" marker, ignore it.
|
| 74 |
+
if words[0] == "\b":
|
| 75 |
+
words = words[1:]
|
| 76 |
+
|
| 77 |
+
total_length = 0
|
| 78 |
+
last_index = len(words) - 1
|
| 79 |
+
|
| 80 |
+
for i, word in enumerate(words):
|
| 81 |
+
total_length += len(word) + (i > 0)
|
| 82 |
+
|
| 83 |
+
if total_length > max_length: # too long, truncate
|
| 84 |
+
break
|
| 85 |
+
|
| 86 |
+
if word[-1] == ".": # sentence end, truncate without "..."
|
| 87 |
+
return " ".join(words[: i + 1])
|
| 88 |
+
|
| 89 |
+
if total_length == max_length and i != last_index:
|
| 90 |
+
break # not at sentence end, truncate with "..."
|
| 91 |
+
else:
|
| 92 |
+
return " ".join(words) # no truncation needed
|
| 93 |
+
|
| 94 |
+
# Account for the length of the suffix.
|
| 95 |
+
total_length += len("...")
|
| 96 |
+
|
| 97 |
+
# remove words until the length is short enough
|
| 98 |
+
while i > 0:
|
| 99 |
+
total_length -= len(words[i]) + (i > 0)
|
| 100 |
+
|
| 101 |
+
if total_length <= max_length:
|
| 102 |
+
break
|
| 103 |
+
|
| 104 |
+
i -= 1
|
| 105 |
+
|
| 106 |
+
return " ".join(words[:i]) + "..."
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class LazyFile:
|
| 110 |
+
"""A lazy file works like a regular file but it does not fully open
|
| 111 |
+
the file but it does perform some basic checks early to see if the
|
| 112 |
+
filename parameter does make sense. This is useful for safely opening
|
| 113 |
+
files for writing.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
def __init__(
|
| 117 |
+
self,
|
| 118 |
+
filename: str | os.PathLike[str],
|
| 119 |
+
mode: str = "r",
|
| 120 |
+
encoding: str | None = None,
|
| 121 |
+
errors: str | None = "strict",
|
| 122 |
+
atomic: bool = False,
|
| 123 |
+
):
|
| 124 |
+
self.name: str = os.fspath(filename)
|
| 125 |
+
self.mode = mode
|
| 126 |
+
self.encoding = encoding
|
| 127 |
+
self.errors = errors
|
| 128 |
+
self.atomic = atomic
|
| 129 |
+
self._f: t.IO[t.Any] | None
|
| 130 |
+
self.should_close: bool
|
| 131 |
+
|
| 132 |
+
if self.name == "-":
|
| 133 |
+
self._f, self.should_close = open_stream(filename, mode, encoding, errors)
|
| 134 |
+
else:
|
| 135 |
+
if "r" in mode:
|
| 136 |
+
# Open and close the file in case we're opening it for
|
| 137 |
+
# reading so that we can catch at least some errors in
|
| 138 |
+
# some cases early.
|
| 139 |
+
open(filename, mode).close()
|
| 140 |
+
self._f = None
|
| 141 |
+
self.should_close = True
|
| 142 |
+
|
| 143 |
+
def __getattr__(self, name: str) -> t.Any:
|
| 144 |
+
return getattr(self.open(), name)
|
| 145 |
+
|
| 146 |
+
def __repr__(self) -> str:
|
| 147 |
+
if self._f is not None:
|
| 148 |
+
return repr(self._f)
|
| 149 |
+
return f"<unopened file '{format_filename(self.name)}' {self.mode}>"
|
| 150 |
+
|
| 151 |
+
def open(self) -> t.IO[t.Any]:
|
| 152 |
+
"""Opens the file if it's not yet open. This call might fail with
|
| 153 |
+
a :exc:`FileError`. Not handling this error will produce an error
|
| 154 |
+
that Click shows.
|
| 155 |
+
"""
|
| 156 |
+
if self._f is not None:
|
| 157 |
+
return self._f
|
| 158 |
+
try:
|
| 159 |
+
rv, self.should_close = open_stream(
|
| 160 |
+
self.name, self.mode, self.encoding, self.errors, atomic=self.atomic
|
| 161 |
+
)
|
| 162 |
+
except OSError as e:
|
| 163 |
+
from .exceptions import FileError
|
| 164 |
+
|
| 165 |
+
raise FileError(self.name, hint=e.strerror) from e
|
| 166 |
+
self._f = rv
|
| 167 |
+
return rv
|
| 168 |
+
|
| 169 |
+
def close(self) -> None:
|
| 170 |
+
"""Closes the underlying file, no matter what."""
|
| 171 |
+
if self._f is not None:
|
| 172 |
+
self._f.close()
|
| 173 |
+
|
| 174 |
+
def close_intelligently(self) -> None:
|
| 175 |
+
"""This function only closes the file if it was opened by the lazy
|
| 176 |
+
file wrapper. For instance this will never close stdin.
|
| 177 |
+
"""
|
| 178 |
+
if self.should_close:
|
| 179 |
+
self.close()
|
| 180 |
+
|
| 181 |
+
def __enter__(self) -> LazyFile:
|
| 182 |
+
return self
|
| 183 |
+
|
| 184 |
+
def __exit__(
|
| 185 |
+
self,
|
| 186 |
+
exc_type: type[BaseException] | None,
|
| 187 |
+
exc_value: BaseException | None,
|
| 188 |
+
tb: TracebackType | None,
|
| 189 |
+
) -> None:
|
| 190 |
+
self.close_intelligently()
|
| 191 |
+
|
| 192 |
+
def __iter__(self) -> cabc.Iterator[t.AnyStr]:
|
| 193 |
+
self.open()
|
| 194 |
+
return iter(self._f) # type: ignore
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class KeepOpenFile:
|
| 198 |
+
def __init__(self, file: t.IO[t.Any]) -> None:
|
| 199 |
+
self._file: t.IO[t.Any] = file
|
| 200 |
+
|
| 201 |
+
def __getattr__(self, name: str) -> t.Any:
|
| 202 |
+
return getattr(self._file, name)
|
| 203 |
+
|
| 204 |
+
def __enter__(self) -> KeepOpenFile:
|
| 205 |
+
return self
|
| 206 |
+
|
| 207 |
+
def __exit__(
|
| 208 |
+
self,
|
| 209 |
+
exc_type: type[BaseException] | None,
|
| 210 |
+
exc_value: BaseException | None,
|
| 211 |
+
tb: TracebackType | None,
|
| 212 |
+
) -> None:
|
| 213 |
+
pass
|
| 214 |
+
|
| 215 |
+
def __repr__(self) -> str:
|
| 216 |
+
return repr(self._file)
|
| 217 |
+
|
| 218 |
+
def __iter__(self) -> cabc.Iterator[t.AnyStr]:
|
| 219 |
+
return iter(self._file)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def echo(
|
| 223 |
+
message: t.Any | None = None,
|
| 224 |
+
file: t.IO[t.Any] | None = None,
|
| 225 |
+
nl: bool = True,
|
| 226 |
+
err: bool = False,
|
| 227 |
+
color: bool | None = None,
|
| 228 |
+
) -> None:
|
| 229 |
+
"""Print a message and newline to stdout or a file. This should be
|
| 230 |
+
used instead of :func:`print` because it provides better support
|
| 231 |
+
for different data, files, and environments.
|
| 232 |
+
|
| 233 |
+
Compared to :func:`print`, this does the following:
|
| 234 |
+
|
| 235 |
+
- Ensures that the output encoding is not misconfigured on Linux.
|
| 236 |
+
- Supports Unicode in the Windows console.
|
| 237 |
+
- Supports writing to binary outputs, and supports writing bytes
|
| 238 |
+
to text outputs.
|
| 239 |
+
- Supports colors and styles on Windows.
|
| 240 |
+
- Removes ANSI color and style codes if the output does not look
|
| 241 |
+
like an interactive terminal.
|
| 242 |
+
- Always flushes the output.
|
| 243 |
+
|
| 244 |
+
:param message: The string or bytes to output. Other objects are
|
| 245 |
+
converted to strings.
|
| 246 |
+
:param file: The file to write to. Defaults to ``stdout``.
|
| 247 |
+
:param err: Write to ``stderr`` instead of ``stdout``.
|
| 248 |
+
:param nl: Print a newline after the message. Enabled by default.
|
| 249 |
+
:param color: Force showing or hiding colors and other styles. By
|
| 250 |
+
default Click will remove color if the output does not look like
|
| 251 |
+
an interactive terminal.
|
| 252 |
+
|
| 253 |
+
.. versionchanged:: 6.0
|
| 254 |
+
Support Unicode output on the Windows console. Click does not
|
| 255 |
+
modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``
|
| 256 |
+
will still not support Unicode.
|
| 257 |
+
|
| 258 |
+
.. versionchanged:: 4.0
|
| 259 |
+
Added the ``color`` parameter.
|
| 260 |
+
|
| 261 |
+
.. versionadded:: 3.0
|
| 262 |
+
Added the ``err`` parameter.
|
| 263 |
+
|
| 264 |
+
.. versionchanged:: 2.0
|
| 265 |
+
Support colors on Windows if colorama is installed.
|
| 266 |
+
"""
|
| 267 |
+
if file is None:
|
| 268 |
+
if err:
|
| 269 |
+
file = _default_text_stderr()
|
| 270 |
+
else:
|
| 271 |
+
file = _default_text_stdout()
|
| 272 |
+
|
| 273 |
+
# There are no standard streams attached to write to. For example,
|
| 274 |
+
# pythonw on Windows.
|
| 275 |
+
if file is None:
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
+
# Convert non bytes/text into the native string type.
|
| 279 |
+
if message is not None and not isinstance(message, (str, bytes, bytearray)):
|
| 280 |
+
out: str | bytes | bytearray | None = str(message)
|
| 281 |
+
else:
|
| 282 |
+
out = message
|
| 283 |
+
|
| 284 |
+
if nl:
|
| 285 |
+
out = out or ""
|
| 286 |
+
if isinstance(out, str):
|
| 287 |
+
out += "\n"
|
| 288 |
+
else:
|
| 289 |
+
out += b"\n"
|
| 290 |
+
|
| 291 |
+
if not out:
|
| 292 |
+
file.flush()
|
| 293 |
+
return
|
| 294 |
+
|
| 295 |
+
# If there is a message and the value looks like bytes, we manually
|
| 296 |
+
# need to find the binary stream and write the message in there.
|
| 297 |
+
# This is done separately so that most stream types will work as you
|
| 298 |
+
# would expect. Eg: you can write to StringIO for other cases.
|
| 299 |
+
if isinstance(out, (bytes, bytearray)):
|
| 300 |
+
binary_file = _find_binary_writer(file)
|
| 301 |
+
|
| 302 |
+
if binary_file is not None:
|
| 303 |
+
file.flush()
|
| 304 |
+
binary_file.write(out)
|
| 305 |
+
binary_file.flush()
|
| 306 |
+
return
|
| 307 |
+
|
| 308 |
+
# ANSI style code support. For no message or bytes, nothing happens.
|
| 309 |
+
# When outputting to a file instead of a terminal, strip codes.
|
| 310 |
+
else:
|
| 311 |
+
color = resolve_color_default(color)
|
| 312 |
+
|
| 313 |
+
if should_strip_ansi(file, color):
|
| 314 |
+
out = strip_ansi(out)
|
| 315 |
+
elif WIN:
|
| 316 |
+
if auto_wrap_for_ansi is not None:
|
| 317 |
+
file = auto_wrap_for_ansi(file, color) # type: ignore
|
| 318 |
+
elif not color:
|
| 319 |
+
out = strip_ansi(out)
|
| 320 |
+
|
| 321 |
+
file.write(out) # type: ignore
|
| 322 |
+
file.flush()
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:
|
| 326 |
+
"""Returns a system stream for byte processing.
|
| 327 |
+
|
| 328 |
+
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
| 329 |
+
``'stdout'`` and ``'stderr'``
|
| 330 |
+
"""
|
| 331 |
+
opener = binary_streams.get(name)
|
| 332 |
+
if opener is None:
|
| 333 |
+
raise TypeError(f"Unknown standard stream '{name}'")
|
| 334 |
+
return opener()
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def get_text_stream(
|
| 338 |
+
name: t.Literal["stdin", "stdout", "stderr"],
|
| 339 |
+
encoding: str | None = None,
|
| 340 |
+
errors: str | None = "strict",
|
| 341 |
+
) -> t.TextIO:
|
| 342 |
+
"""Returns a system stream for text processing. This usually returns
|
| 343 |
+
a wrapped stream around a binary stream returned from
|
| 344 |
+
:func:`get_binary_stream` but it also can take shortcuts for already
|
| 345 |
+
correctly configured streams.
|
| 346 |
+
|
| 347 |
+
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
| 348 |
+
``'stdout'`` and ``'stderr'``
|
| 349 |
+
:param encoding: overrides the detected default encoding.
|
| 350 |
+
:param errors: overrides the default error mode.
|
| 351 |
+
"""
|
| 352 |
+
opener = text_streams.get(name)
|
| 353 |
+
if opener is None:
|
| 354 |
+
raise TypeError(f"Unknown standard stream '{name}'")
|
| 355 |
+
return opener(encoding, errors)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def open_file(
|
| 359 |
+
filename: str | os.PathLike[str],
|
| 360 |
+
mode: str = "r",
|
| 361 |
+
encoding: str | None = None,
|
| 362 |
+
errors: str | None = "strict",
|
| 363 |
+
lazy: bool = False,
|
| 364 |
+
atomic: bool = False,
|
| 365 |
+
) -> t.IO[t.Any]:
|
| 366 |
+
"""Open a file, with extra behavior to handle ``'-'`` to indicate
|
| 367 |
+
a standard stream, lazy open on write, and atomic write. Similar to
|
| 368 |
+
the behavior of the :class:`~click.File` param type.
|
| 369 |
+
|
| 370 |
+
If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is
|
| 371 |
+
wrapped so that using it in a context manager will not close it.
|
| 372 |
+
This makes it possible to use the function without accidentally
|
| 373 |
+
closing a standard stream:
|
| 374 |
+
|
| 375 |
+
.. code-block:: python
|
| 376 |
+
|
| 377 |
+
with open_file(filename) as f:
|
| 378 |
+
...
|
| 379 |
+
|
| 380 |
+
:param filename: The name or Path of the file to open, or ``'-'`` for
|
| 381 |
+
``stdin``/``stdout``.
|
| 382 |
+
:param mode: The mode in which to open the file.
|
| 383 |
+
:param encoding: The encoding to decode or encode a file opened in
|
| 384 |
+
text mode.
|
| 385 |
+
:param errors: The error handling mode.
|
| 386 |
+
:param lazy: Wait to open the file until it is accessed. For read
|
| 387 |
+
mode, the file is temporarily opened to raise access errors
|
| 388 |
+
early, then closed until it is read again.
|
| 389 |
+
:param atomic: Write to a temporary file and replace the given file
|
| 390 |
+
on close.
|
| 391 |
+
|
| 392 |
+
.. versionadded:: 3.0
|
| 393 |
+
"""
|
| 394 |
+
if lazy:
|
| 395 |
+
return t.cast(
|
| 396 |
+
"t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
|
| 400 |
+
|
| 401 |
+
if not should_close:
|
| 402 |
+
f = t.cast("t.IO[t.Any]", KeepOpenFile(f))
|
| 403 |
+
|
| 404 |
+
return f
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def format_filename(
|
| 408 |
+
filename: str | bytes | os.PathLike[str] | os.PathLike[bytes],
|
| 409 |
+
shorten: bool = False,
|
| 410 |
+
) -> str:
|
| 411 |
+
"""Format a filename as a string for display. Ensures the filename can be
|
| 412 |
+
displayed by replacing any invalid bytes or surrogate escapes in the name
|
| 413 |
+
with the replacement character ``�``.
|
| 414 |
+
|
| 415 |
+
Invalid bytes or surrogate escapes will raise an error when written to a
|
| 416 |
+
stream with ``errors="strict"``. This will typically happen with ``stdout``
|
| 417 |
+
when the locale is something like ``en_GB.UTF-8``.
|
| 418 |
+
|
| 419 |
+
Many scenarios *are* safe to write surrogates though, due to PEP 538 and
|
| 420 |
+
PEP 540, including:
|
| 421 |
+
|
| 422 |
+
- Writing to ``stderr``, which uses ``errors="backslashreplace"``.
|
| 423 |
+
- The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens
|
| 424 |
+
stdout and stderr with ``errors="surrogateescape"``.
|
| 425 |
+
- None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.
|
| 426 |
+
- Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.
|
| 427 |
+
Python opens stdout and stderr with ``errors="surrogateescape"``.
|
| 428 |
+
|
| 429 |
+
:param filename: formats a filename for UI display. This will also convert
|
| 430 |
+
the filename into unicode without failing.
|
| 431 |
+
:param shorten: this optionally shortens the filename to strip of the
|
| 432 |
+
path that leads up to it.
|
| 433 |
+
"""
|
| 434 |
+
if shorten:
|
| 435 |
+
filename = os.path.basename(filename)
|
| 436 |
+
else:
|
| 437 |
+
filename = os.fspath(filename)
|
| 438 |
+
|
| 439 |
+
if isinstance(filename, bytes):
|
| 440 |
+
filename = filename.decode(sys.getfilesystemencoding(), "replace")
|
| 441 |
+
else:
|
| 442 |
+
filename = filename.encode("utf-8", "surrogateescape").decode(
|
| 443 |
+
"utf-8", "replace"
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
return filename
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
|
| 450 |
+
r"""Returns the config folder for the application. The default behavior
|
| 451 |
+
is to return whatever is most appropriate for the operating system.
|
| 452 |
+
|
| 453 |
+
To give you an idea, for an app called ``"Foo Bar"``, something like
|
| 454 |
+
the following folders could be returned:
|
| 455 |
+
|
| 456 |
+
Mac OS X:
|
| 457 |
+
``~/Library/Application Support/Foo Bar``
|
| 458 |
+
Mac OS X (POSIX):
|
| 459 |
+
``~/.foo-bar``
|
| 460 |
+
Unix:
|
| 461 |
+
``~/.config/foo-bar``
|
| 462 |
+
Unix (POSIX):
|
| 463 |
+
``~/.foo-bar``
|
| 464 |
+
Windows (roaming):
|
| 465 |
+
``C:\Users\<user>\AppData\Roaming\Foo Bar``
|
| 466 |
+
Windows (not roaming):
|
| 467 |
+
``C:\Users\<user>\AppData\Local\Foo Bar``
|
| 468 |
+
|
| 469 |
+
.. versionadded:: 2.0
|
| 470 |
+
|
| 471 |
+
:param app_name: the application name. This should be properly capitalized
|
| 472 |
+
and can contain whitespace.
|
| 473 |
+
:param roaming: controls if the folder should be roaming or not on Windows.
|
| 474 |
+
Has no effect otherwise.
|
| 475 |
+
:param force_posix: if this is set to `True` then on any POSIX system the
|
| 476 |
+
folder will be stored in the home folder with a leading
|
| 477 |
+
dot instead of the XDG config home or darwin's
|
| 478 |
+
application support folder.
|
| 479 |
+
"""
|
| 480 |
+
if WIN:
|
| 481 |
+
key = "APPDATA" if roaming else "LOCALAPPDATA"
|
| 482 |
+
folder = os.environ.get(key)
|
| 483 |
+
if folder is None:
|
| 484 |
+
folder = os.path.expanduser("~")
|
| 485 |
+
return os.path.join(folder, app_name)
|
| 486 |
+
if force_posix:
|
| 487 |
+
return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))
|
| 488 |
+
if sys.platform == "darwin":
|
| 489 |
+
return os.path.join(
|
| 490 |
+
os.path.expanduser("~/Library/Application Support"), app_name
|
| 491 |
+
)
|
| 492 |
+
return os.path.join(
|
| 493 |
+
os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
|
| 494 |
+
_posixify(app_name),
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
class PacifyFlushWrapper:
|
| 499 |
+
"""This wrapper is used to catch and suppress BrokenPipeErrors resulting
|
| 500 |
+
from ``.flush()`` being called on broken pipe during the shutdown/final-GC
|
| 501 |
+
of the Python interpreter. Notably ``.flush()`` is always called on
|
| 502 |
+
``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any
|
| 503 |
+
other cleanup code, and the case where the underlying file is not a broken
|
| 504 |
+
pipe, all calls and attributes are proxied.
|
| 505 |
+
"""
|
| 506 |
+
|
| 507 |
+
def __init__(self, wrapped: t.IO[t.Any]) -> None:
|
| 508 |
+
self.wrapped = wrapped
|
| 509 |
+
|
| 510 |
+
def flush(self) -> None:
|
| 511 |
+
try:
|
| 512 |
+
self.wrapped.flush()
|
| 513 |
+
except OSError as e:
|
| 514 |
+
import errno
|
| 515 |
+
|
| 516 |
+
if e.errno != errno.EPIPE:
|
| 517 |
+
raise
|
| 518 |
+
|
| 519 |
+
def __getattr__(self, attr: str) -> t.Any:
|
| 520 |
+
return getattr(self.wrapped, attr)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def _detect_program_name(
|
| 524 |
+
path: str | None = None, _main: ModuleType | None = None
|
| 525 |
+
) -> str:
|
| 526 |
+
"""Determine the command used to run the program, for use in help
|
| 527 |
+
text. If a file or entry point was executed, the file name is
|
| 528 |
+
returned. If ``python -m`` was used to execute a module or package,
|
| 529 |
+
``python -m name`` is returned.
|
| 530 |
+
|
| 531 |
+
This doesn't try to be too precise, the goal is to give a concise
|
| 532 |
+
name for help text. Files are only shown as their name without the
|
| 533 |
+
path. ``python`` is only shown for modules, and the full path to
|
| 534 |
+
``sys.executable`` is not shown.
|
| 535 |
+
|
| 536 |
+
:param path: The Python file being executed. Python puts this in
|
| 537 |
+
``sys.argv[0]``, which is used by default.
|
| 538 |
+
:param _main: The ``__main__`` module. This should only be passed
|
| 539 |
+
during internal testing.
|
| 540 |
+
|
| 541 |
+
.. versionadded:: 8.0
|
| 542 |
+
Based on command args detection in the Werkzeug reloader.
|
| 543 |
+
|
| 544 |
+
:meta private:
|
| 545 |
+
"""
|
| 546 |
+
if _main is None:
|
| 547 |
+
_main = sys.modules["__main__"]
|
| 548 |
+
|
| 549 |
+
if not path:
|
| 550 |
+
path = sys.argv[0]
|
| 551 |
+
|
| 552 |
+
# The value of __package__ indicates how Python was called. It may
|
| 553 |
+
# not exist if a setuptools script is installed as an egg. It may be
|
| 554 |
+
# set incorrectly for entry points created with pip on Windows.
|
| 555 |
+
# It is set to "" inside a Shiv or PEX zipapp.
|
| 556 |
+
if getattr(_main, "__package__", None) in {None, ""} or (
|
| 557 |
+
os.name == "nt"
|
| 558 |
+
and _main.__package__ == ""
|
| 559 |
+
and not os.path.exists(path)
|
| 560 |
+
and os.path.exists(f"{path}.exe")
|
| 561 |
+
):
|
| 562 |
+
# Executed a file, like "python app.py".
|
| 563 |
+
return os.path.basename(path)
|
| 564 |
+
|
| 565 |
+
# Executed a module, like "python -m example".
|
| 566 |
+
# Rewritten by Python from "-m script" to "/path/to/script.py".
|
| 567 |
+
# Need to look at main module to determine how it was executed.
|
| 568 |
+
py_module = t.cast(str, _main.__package__)
|
| 569 |
+
name = os.path.splitext(os.path.basename(path))[0]
|
| 570 |
+
|
| 571 |
+
# A submodule like "example.cli".
|
| 572 |
+
if name != "__main__":
|
| 573 |
+
py_module = f"{py_module}.{name}"
|
| 574 |
+
|
| 575 |
+
return f"python -m {py_module.lstrip('.')}"
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def _expand_args(
|
| 579 |
+
args: cabc.Iterable[str],
|
| 580 |
+
*,
|
| 581 |
+
user: bool = True,
|
| 582 |
+
env: bool = True,
|
| 583 |
+
glob_recursive: bool = True,
|
| 584 |
+
) -> list[str]:
|
| 585 |
+
"""Simulate Unix shell expansion with Python functions.
|
| 586 |
+
|
| 587 |
+
See :func:`glob.glob`, :func:`os.path.expanduser`, and
|
| 588 |
+
:func:`os.path.expandvars`.
|
| 589 |
+
|
| 590 |
+
This is intended for use on Windows, where the shell does not do any
|
| 591 |
+
expansion. It may not exactly match what a Unix shell would do.
|
| 592 |
+
|
| 593 |
+
:param args: List of command line arguments to expand.
|
| 594 |
+
:param user: Expand user home directory.
|
| 595 |
+
:param env: Expand environment variables.
|
| 596 |
+
:param glob_recursive: ``**`` matches directories recursively.
|
| 597 |
+
|
| 598 |
+
.. versionchanged:: 8.1
|
| 599 |
+
Invalid glob patterns are treated as empty expansions rather
|
| 600 |
+
than raising an error.
|
| 601 |
+
|
| 602 |
+
.. versionadded:: 8.0
|
| 603 |
+
|
| 604 |
+
:meta private:
|
| 605 |
+
"""
|
| 606 |
+
from glob import glob
|
| 607 |
+
|
| 608 |
+
out = []
|
| 609 |
+
|
| 610 |
+
for arg in args:
|
| 611 |
+
if user:
|
| 612 |
+
arg = os.path.expanduser(arg)
|
| 613 |
+
|
| 614 |
+
if env:
|
| 615 |
+
arg = os.path.expandvars(arg)
|
| 616 |
+
|
| 617 |
+
try:
|
| 618 |
+
matches = glob(arg, recursive=glob_recursive)
|
| 619 |
+
except re.error:
|
| 620 |
+
matches = []
|
| 621 |
+
|
| 622 |
+
if not matches:
|
| 623 |
+
out.append(arg)
|
| 624 |
+
else:
|
| 625 |
+
out.extend(matches)
|
| 626 |
+
|
| 627 |
+
return out
|
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230),
|
| 2 |
+
# containing no networking code at all, loosely modelled on hyper-h2's generic
|
| 3 |
+
# implementation of HTTP/2 (and in particular the h2.connection.H2Connection
|
| 4 |
+
# class). There's still a bunch of subtle details you need to get right if you
|
| 5 |
+
# want to make this actually useful, because it doesn't implement all the
|
| 6 |
+
# semantics to check that what you're asking to write to the wire is sensible,
|
| 7 |
+
# but at least it gets you out of dealing with the wire itself.
|
| 8 |
+
|
| 9 |
+
from h11._connection import Connection, NEED_DATA, PAUSED
|
| 10 |
+
from h11._events import (
|
| 11 |
+
ConnectionClosed,
|
| 12 |
+
Data,
|
| 13 |
+
EndOfMessage,
|
| 14 |
+
Event,
|
| 15 |
+
InformationalResponse,
|
| 16 |
+
Request,
|
| 17 |
+
Response,
|
| 18 |
+
)
|
| 19 |
+
from h11._state import (
|
| 20 |
+
CLIENT,
|
| 21 |
+
CLOSED,
|
| 22 |
+
DONE,
|
| 23 |
+
ERROR,
|
| 24 |
+
IDLE,
|
| 25 |
+
MIGHT_SWITCH_PROTOCOL,
|
| 26 |
+
MUST_CLOSE,
|
| 27 |
+
SEND_BODY,
|
| 28 |
+
SEND_RESPONSE,
|
| 29 |
+
SERVER,
|
| 30 |
+
SWITCHED_PROTOCOL,
|
| 31 |
+
)
|
| 32 |
+
from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolError
|
| 33 |
+
from h11._version import __version__
|
| 34 |
+
|
| 35 |
+
PRODUCT_ID = "python-h11/" + __version__
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
__all__ = (
|
| 39 |
+
"Connection",
|
| 40 |
+
"NEED_DATA",
|
| 41 |
+
"PAUSED",
|
| 42 |
+
"ConnectionClosed",
|
| 43 |
+
"Data",
|
| 44 |
+
"EndOfMessage",
|
| 45 |
+
"Event",
|
| 46 |
+
"InformationalResponse",
|
| 47 |
+
"Request",
|
| 48 |
+
"Response",
|
| 49 |
+
"CLIENT",
|
| 50 |
+
"CLOSED",
|
| 51 |
+
"DONE",
|
| 52 |
+
"ERROR",
|
| 53 |
+
"IDLE",
|
| 54 |
+
"MUST_CLOSE",
|
| 55 |
+
"SEND_BODY",
|
| 56 |
+
"SEND_RESPONSE",
|
| 57 |
+
"SERVER",
|
| 58 |
+
"SWITCHED_PROTOCOL",
|
| 59 |
+
"ProtocolError",
|
| 60 |
+
"LocalProtocolError",
|
| 61 |
+
"RemoteProtocolError",
|
| 62 |
+
)
|
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_abnf.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# We use native strings for all the re patterns, to take advantage of string
|
| 2 |
+
# formatting, and then convert to bytestrings when compiling the final re
|
| 3 |
+
# objects.
|
| 4 |
+
|
| 5 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace
|
| 6 |
+
# OWS = *( SP / HTAB )
|
| 7 |
+
# ; optional whitespace
|
| 8 |
+
OWS = r"[ \t]*"
|
| 9 |
+
|
| 10 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators
|
| 11 |
+
# token = 1*tchar
|
| 12 |
+
#
|
| 13 |
+
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
|
| 14 |
+
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
|
| 15 |
+
# / DIGIT / ALPHA
|
| 16 |
+
# ; any VCHAR, except delimiters
|
| 17 |
+
token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+"
|
| 18 |
+
|
| 19 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields
|
| 20 |
+
# field-name = token
|
| 21 |
+
field_name = token
|
| 22 |
+
|
| 23 |
+
# The standard says:
|
| 24 |
+
#
|
| 25 |
+
# field-value = *( field-content / obs-fold )
|
| 26 |
+
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
|
| 27 |
+
# field-vchar = VCHAR / obs-text
|
| 28 |
+
# obs-fold = CRLF 1*( SP / HTAB )
|
| 29 |
+
# ; obsolete line folding
|
| 30 |
+
# ; see Section 3.2.4
|
| 31 |
+
#
|
| 32 |
+
# https://tools.ietf.org/html/rfc5234#appendix-B.1
|
| 33 |
+
#
|
| 34 |
+
# VCHAR = %x21-7E
|
| 35 |
+
# ; visible (printing) characters
|
| 36 |
+
#
|
| 37 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string
|
| 38 |
+
# obs-text = %x80-FF
|
| 39 |
+
#
|
| 40 |
+
# However, the standard definition of field-content is WRONG! It disallows
|
| 41 |
+
# fields containing a single visible character surrounded by whitespace,
|
| 42 |
+
# e.g. "foo a bar".
|
| 43 |
+
#
|
| 44 |
+
# See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189
|
| 45 |
+
#
|
| 46 |
+
# So our definition of field_content attempts to fix it up...
|
| 47 |
+
#
|
| 48 |
+
# Also, we allow lots of control characters, because apparently people assume
|
| 49 |
+
# that they're legal in practice (e.g., google analytics makes cookies with
|
| 50 |
+
# \x01 in them!):
|
| 51 |
+
# https://github.com/python-hyper/h11/issues/57
|
| 52 |
+
# We still don't allow NUL or whitespace, because those are often treated as
|
| 53 |
+
# meta-characters and letting them through can lead to nasty issues like SSRF.
|
| 54 |
+
vchar = r"[\x21-\x7e]"
|
| 55 |
+
vchar_or_obs_text = r"[^\x00\s]"
|
| 56 |
+
field_vchar = vchar_or_obs_text
|
| 57 |
+
field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals())
|
| 58 |
+
|
| 59 |
+
# We handle obs-fold at a different level, and our fixed-up field_content
|
| 60 |
+
# already grows to swallow the whole value, so ? instead of *
|
| 61 |
+
field_value = r"({field_content})?".format(**globals())
|
| 62 |
+
|
| 63 |
+
# header-field = field-name ":" OWS field-value OWS
|
| 64 |
+
header_field = (
|
| 65 |
+
r"(?P<field_name>{field_name})"
|
| 66 |
+
r":"
|
| 67 |
+
r"{OWS}"
|
| 68 |
+
r"(?P<field_value>{field_value})"
|
| 69 |
+
r"{OWS}".format(**globals())
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line
|
| 73 |
+
#
|
| 74 |
+
# request-line = method SP request-target SP HTTP-version CRLF
|
| 75 |
+
# method = token
|
| 76 |
+
# HTTP-version = HTTP-name "/" DIGIT "." DIGIT
|
| 77 |
+
# HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive
|
| 78 |
+
#
|
| 79 |
+
# request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full
|
| 80 |
+
# URL, host+port (for connect), or even "*", but in any case we are guaranteed
|
| 81 |
+
# that it contists of the visible printing characters.
|
| 82 |
+
method = token
|
| 83 |
+
request_target = r"{vchar}+".format(**globals())
|
| 84 |
+
http_version = r"HTTP/(?P<http_version>[0-9]\.[0-9])"
|
| 85 |
+
request_line = (
|
| 86 |
+
r"(?P<method>{method})"
|
| 87 |
+
r" "
|
| 88 |
+
r"(?P<target>{request_target})"
|
| 89 |
+
r" "
|
| 90 |
+
r"{http_version}".format(**globals())
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line
|
| 94 |
+
#
|
| 95 |
+
# status-line = HTTP-version SP status-code SP reason-phrase CRLF
|
| 96 |
+
# status-code = 3DIGIT
|
| 97 |
+
# reason-phrase = *( HTAB / SP / VCHAR / obs-text )
|
| 98 |
+
status_code = r"[0-9]{3}"
|
| 99 |
+
reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals())
|
| 100 |
+
status_line = (
|
| 101 |
+
r"{http_version}"
|
| 102 |
+
r" "
|
| 103 |
+
r"(?P<status_code>{status_code})"
|
| 104 |
+
# However, there are apparently a few too many servers out there that just
|
| 105 |
+
# leave out the reason phrase:
|
| 106 |
+
# https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036
|
| 107 |
+
# https://github.com/seanmonstar/httparse/issues/29
|
| 108 |
+
# so make it optional. ?: is a non-capturing group.
|
| 109 |
+
r"(?: (?P<reason>{reason_phrase}))?".format(**globals())
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
HEXDIG = r"[0-9A-Fa-f]"
|
| 113 |
+
# Actually
|
| 114 |
+
#
|
| 115 |
+
# chunk-size = 1*HEXDIG
|
| 116 |
+
#
|
| 117 |
+
# but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20
|
| 118 |
+
chunk_size = r"({HEXDIG}){{1,20}}".format(**globals())
|
| 119 |
+
# Actually
|
| 120 |
+
#
|
| 121 |
+
# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
|
| 122 |
+
#
|
| 123 |
+
# but we aren't parsing the things so we don't really care.
|
| 124 |
+
chunk_ext = r";.*"
|
| 125 |
+
chunk_header = (
|
| 126 |
+
r"(?P<chunk_size>{chunk_size})"
|
| 127 |
+
r"(?P<chunk_ext>{chunk_ext})?"
|
| 128 |
+
r"{OWS}\r\n".format(
|
| 129 |
+
**globals()
|
| 130 |
+
) # Even though the specification does not allow for extra whitespaces,
|
| 131 |
+
# we are lenient with trailing whitespaces because some servers on the wild use it.
|
| 132 |
+
)
|
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_connection.py
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This contains the main Connection class. Everything in h11 revolves around
|
| 2 |
+
# this.
|
| 3 |
+
from typing import (
|
| 4 |
+
Any,
|
| 5 |
+
Callable,
|
| 6 |
+
cast,
|
| 7 |
+
Dict,
|
| 8 |
+
List,
|
| 9 |
+
Optional,
|
| 10 |
+
overload,
|
| 11 |
+
Tuple,
|
| 12 |
+
Type,
|
| 13 |
+
Union,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from ._events import (
|
| 17 |
+
ConnectionClosed,
|
| 18 |
+
Data,
|
| 19 |
+
EndOfMessage,
|
| 20 |
+
Event,
|
| 21 |
+
InformationalResponse,
|
| 22 |
+
Request,
|
| 23 |
+
Response,
|
| 24 |
+
)
|
| 25 |
+
from ._headers import get_comma_header, has_expect_100_continue, set_comma_header
|
| 26 |
+
from ._readers import READERS, ReadersType
|
| 27 |
+
from ._receivebuffer import ReceiveBuffer
|
| 28 |
+
from ._state import (
|
| 29 |
+
_SWITCH_CONNECT,
|
| 30 |
+
_SWITCH_UPGRADE,
|
| 31 |
+
CLIENT,
|
| 32 |
+
ConnectionState,
|
| 33 |
+
DONE,
|
| 34 |
+
ERROR,
|
| 35 |
+
MIGHT_SWITCH_PROTOCOL,
|
| 36 |
+
SEND_BODY,
|
| 37 |
+
SERVER,
|
| 38 |
+
SWITCHED_PROTOCOL,
|
| 39 |
+
)
|
| 40 |
+
from ._util import ( # Import the internal things we need
|
| 41 |
+
LocalProtocolError,
|
| 42 |
+
RemoteProtocolError,
|
| 43 |
+
Sentinel,
|
| 44 |
+
)
|
| 45 |
+
from ._writers import WRITERS, WritersType
|
| 46 |
+
|
| 47 |
+
# Everything in __all__ gets re-exported as part of the h11 public API.
|
| 48 |
+
__all__ = ["Connection", "NEED_DATA", "PAUSED"]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class NEED_DATA(Sentinel, metaclass=Sentinel):
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class PAUSED(Sentinel, metaclass=Sentinel):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# If we ever have this much buffered without it making a complete parseable
|
| 60 |
+
# event, we error out. The only time we really buffer is when reading the
|
| 61 |
+
# request/response line + headers together, so this is effectively the limit on
|
| 62 |
+
# the size of that.
|
| 63 |
+
#
|
| 64 |
+
# Some precedents for defaults:
|
| 65 |
+
# - node.js: 80 * 1024
|
| 66 |
+
# - tomcat: 8 * 1024
|
| 67 |
+
# - IIS: 16 * 1024
|
| 68 |
+
# - Apache: <8 KiB per line>
|
| 69 |
+
DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# RFC 7230's rules for connection lifecycles:
|
| 73 |
+
# - If either side says they want to close the connection, then the connection
|
| 74 |
+
# must close.
|
| 75 |
+
# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close
|
| 76 |
+
# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive
|
| 77 |
+
# (and even this is a mess -- e.g. if you're implementing a proxy then
|
| 78 |
+
# sending Connection: keep-alive is forbidden).
|
| 79 |
+
#
|
| 80 |
+
# We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So
|
| 81 |
+
# our rule is:
|
| 82 |
+
# - If someone says Connection: close, we will close
|
| 83 |
+
# - If someone uses HTTP/1.0, we will close.
|
| 84 |
+
def _keep_alive(event: Union[Request, Response]) -> bool:
|
| 85 |
+
connection = get_comma_header(event.headers, b"connection")
|
| 86 |
+
if b"close" in connection:
|
| 87 |
+
return False
|
| 88 |
+
if getattr(event, "http_version", b"1.1") < b"1.1":
|
| 89 |
+
return False
|
| 90 |
+
return True
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _body_framing(
|
| 94 |
+
request_method: bytes, event: Union[Request, Response]
|
| 95 |
+
) -> Tuple[str, Union[Tuple[()], Tuple[int]]]:
|
| 96 |
+
# Called when we enter SEND_BODY to figure out framing information for
|
| 97 |
+
# this body.
|
| 98 |
+
#
|
| 99 |
+
# These are the only two events that can trigger a SEND_BODY state:
|
| 100 |
+
assert type(event) in (Request, Response)
|
| 101 |
+
# Returns one of:
|
| 102 |
+
#
|
| 103 |
+
# ("content-length", count)
|
| 104 |
+
# ("chunked", ())
|
| 105 |
+
# ("http/1.0", ())
|
| 106 |
+
#
|
| 107 |
+
# which are (lookup key, *args) for constructing body reader/writer
|
| 108 |
+
# objects.
|
| 109 |
+
#
|
| 110 |
+
# Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3
|
| 111 |
+
#
|
| 112 |
+
# Step 1: some responses always have an empty body, regardless of what the
|
| 113 |
+
# headers say.
|
| 114 |
+
if type(event) is Response:
|
| 115 |
+
if (
|
| 116 |
+
event.status_code in (204, 304)
|
| 117 |
+
or request_method == b"HEAD"
|
| 118 |
+
or (request_method == b"CONNECT" and 200 <= event.status_code < 300)
|
| 119 |
+
):
|
| 120 |
+
return ("content-length", (0,))
|
| 121 |
+
# Section 3.3.3 also lists another case -- responses with status_code
|
| 122 |
+
# < 200. For us these are InformationalResponses, not Responses, so
|
| 123 |
+
# they can't get into this function in the first place.
|
| 124 |
+
assert event.status_code >= 200
|
| 125 |
+
|
| 126 |
+
# Step 2: check for Transfer-Encoding (T-E beats C-L):
|
| 127 |
+
transfer_encodings = get_comma_header(event.headers, b"transfer-encoding")
|
| 128 |
+
if transfer_encodings:
|
| 129 |
+
assert transfer_encodings == [b"chunked"]
|
| 130 |
+
return ("chunked", ())
|
| 131 |
+
|
| 132 |
+
# Step 3: check for Content-Length
|
| 133 |
+
content_lengths = get_comma_header(event.headers, b"content-length")
|
| 134 |
+
if content_lengths:
|
| 135 |
+
return ("content-length", (int(content_lengths[0]),))
|
| 136 |
+
|
| 137 |
+
# Step 4: no applicable headers; fallback/default depends on type
|
| 138 |
+
if type(event) is Request:
|
| 139 |
+
return ("content-length", (0,))
|
| 140 |
+
else:
|
| 141 |
+
return ("http/1.0", ())
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
################################################################
|
| 145 |
+
#
|
| 146 |
+
# The main Connection class
|
| 147 |
+
#
|
| 148 |
+
################################################################
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class Connection:
|
| 152 |
+
"""An object encapsulating the state of an HTTP connection.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If
|
| 156 |
+
you're implementing a server, pass :data:`h11.SERVER`.
|
| 157 |
+
|
| 158 |
+
max_incomplete_event_size (int):
|
| 159 |
+
The maximum number of bytes we're willing to buffer of an
|
| 160 |
+
incomplete event. In practice this mostly sets a limit on the
|
| 161 |
+
maximum size of the request/response line + headers. If this is
|
| 162 |
+
exceeded, then :meth:`next_event` will raise
|
| 163 |
+
:exc:`RemoteProtocolError`.
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
our_role: Type[Sentinel],
|
| 170 |
+
max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE,
|
| 171 |
+
) -> None:
|
| 172 |
+
self._max_incomplete_event_size = max_incomplete_event_size
|
| 173 |
+
# State and role tracking
|
| 174 |
+
if our_role not in (CLIENT, SERVER):
|
| 175 |
+
raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}")
|
| 176 |
+
self.our_role = our_role
|
| 177 |
+
self.their_role: Type[Sentinel]
|
| 178 |
+
if our_role is CLIENT:
|
| 179 |
+
self.their_role = SERVER
|
| 180 |
+
else:
|
| 181 |
+
self.their_role = CLIENT
|
| 182 |
+
self._cstate = ConnectionState()
|
| 183 |
+
|
| 184 |
+
# Callables for converting data->events or vice-versa given the
|
| 185 |
+
# current state
|
| 186 |
+
self._writer = self._get_io_object(self.our_role, None, WRITERS)
|
| 187 |
+
self._reader = self._get_io_object(self.their_role, None, READERS)
|
| 188 |
+
|
| 189 |
+
# Holds any unprocessed received data
|
| 190 |
+
self._receive_buffer = ReceiveBuffer()
|
| 191 |
+
# If this is true, then it indicates that the incoming connection was
|
| 192 |
+
# closed *after* the end of whatever's in self._receive_buffer:
|
| 193 |
+
self._receive_buffer_closed = False
|
| 194 |
+
|
| 195 |
+
# Extra bits of state that don't fit into the state machine.
|
| 196 |
+
#
|
| 197 |
+
# These two are only used to interpret framing headers for figuring
|
| 198 |
+
# out how to read/write response bodies. their_http_version is also
|
| 199 |
+
# made available as a convenient public API.
|
| 200 |
+
self.their_http_version: Optional[bytes] = None
|
| 201 |
+
self._request_method: Optional[bytes] = None
|
| 202 |
+
# This is pure flow-control and doesn't at all affect the set of legal
|
| 203 |
+
# transitions, so no need to bother ConnectionState with it:
|
| 204 |
+
self.client_is_waiting_for_100_continue = False
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]:
|
| 208 |
+
"""A dictionary like::
|
| 209 |
+
|
| 210 |
+
{CLIENT: <client state>, SERVER: <server state>}
|
| 211 |
+
|
| 212 |
+
See :ref:`state-machine` for details.
|
| 213 |
+
|
| 214 |
+
"""
|
| 215 |
+
return dict(self._cstate.states)
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def our_state(self) -> Type[Sentinel]:
|
| 219 |
+
"""The current state of whichever role we are playing. See
|
| 220 |
+
:ref:`state-machine` for details.
|
| 221 |
+
"""
|
| 222 |
+
return self._cstate.states[self.our_role]
|
| 223 |
+
|
| 224 |
+
@property
|
| 225 |
+
def their_state(self) -> Type[Sentinel]:
|
| 226 |
+
"""The current state of whichever role we are NOT playing. See
|
| 227 |
+
:ref:`state-machine` for details.
|
| 228 |
+
"""
|
| 229 |
+
return self._cstate.states[self.their_role]
|
| 230 |
+
|
| 231 |
+
@property
|
| 232 |
+
def they_are_waiting_for_100_continue(self) -> bool:
|
| 233 |
+
return self.their_role is CLIENT and self.client_is_waiting_for_100_continue
|
| 234 |
+
|
| 235 |
+
def start_next_cycle(self) -> None:
|
| 236 |
+
"""Attempt to reset our connection state for a new request/response
|
| 237 |
+
cycle.
|
| 238 |
+
|
| 239 |
+
If both client and server are in :data:`DONE` state, then resets them
|
| 240 |
+
both to :data:`IDLE` state in preparation for a new request/response
|
| 241 |
+
cycle on this same connection. Otherwise, raises a
|
| 242 |
+
:exc:`LocalProtocolError`.
|
| 243 |
+
|
| 244 |
+
See :ref:`keepalive-and-pipelining`.
|
| 245 |
+
|
| 246 |
+
"""
|
| 247 |
+
old_states = dict(self._cstate.states)
|
| 248 |
+
self._cstate.start_next_cycle()
|
| 249 |
+
self._request_method = None
|
| 250 |
+
# self.their_http_version gets left alone, since it presumably lasts
|
| 251 |
+
# beyond a single request/response cycle
|
| 252 |
+
assert not self.client_is_waiting_for_100_continue
|
| 253 |
+
self._respond_to_state_changes(old_states)
|
| 254 |
+
|
| 255 |
+
def _process_error(self, role: Type[Sentinel]) -> None:
|
| 256 |
+
old_states = dict(self._cstate.states)
|
| 257 |
+
self._cstate.process_error(role)
|
| 258 |
+
self._respond_to_state_changes(old_states)
|
| 259 |
+
|
| 260 |
+
def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]:
|
| 261 |
+
if type(event) is InformationalResponse and event.status_code == 101:
|
| 262 |
+
return _SWITCH_UPGRADE
|
| 263 |
+
if type(event) is Response:
|
| 264 |
+
if (
|
| 265 |
+
_SWITCH_CONNECT in self._cstate.pending_switch_proposals
|
| 266 |
+
and 200 <= event.status_code < 300
|
| 267 |
+
):
|
| 268 |
+
return _SWITCH_CONNECT
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
# All events go through here
|
| 272 |
+
def _process_event(self, role: Type[Sentinel], event: Event) -> None:
|
| 273 |
+
# First, pass the event through the state machine to make sure it
|
| 274 |
+
# succeeds.
|
| 275 |
+
old_states = dict(self._cstate.states)
|
| 276 |
+
if role is CLIENT and type(event) is Request:
|
| 277 |
+
if event.method == b"CONNECT":
|
| 278 |
+
self._cstate.process_client_switch_proposal(_SWITCH_CONNECT)
|
| 279 |
+
if get_comma_header(event.headers, b"upgrade"):
|
| 280 |
+
self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE)
|
| 281 |
+
server_switch_event = None
|
| 282 |
+
if role is SERVER:
|
| 283 |
+
server_switch_event = self._server_switch_event(event)
|
| 284 |
+
self._cstate.process_event(role, type(event), server_switch_event)
|
| 285 |
+
|
| 286 |
+
# Then perform the updates triggered by it.
|
| 287 |
+
|
| 288 |
+
if type(event) is Request:
|
| 289 |
+
self._request_method = event.method
|
| 290 |
+
|
| 291 |
+
if role is self.their_role and type(event) in (
|
| 292 |
+
Request,
|
| 293 |
+
Response,
|
| 294 |
+
InformationalResponse,
|
| 295 |
+
):
|
| 296 |
+
event = cast(Union[Request, Response, InformationalResponse], event)
|
| 297 |
+
self.their_http_version = event.http_version
|
| 298 |
+
|
| 299 |
+
# Keep alive handling
|
| 300 |
+
#
|
| 301 |
+
# RFC 7230 doesn't really say what one should do if Connection: close
|
| 302 |
+
# shows up on a 1xx InformationalResponse. I think the idea is that
|
| 303 |
+
# this is not supposed to happen. In any case, if it does happen, we
|
| 304 |
+
# ignore it.
|
| 305 |
+
if type(event) in (Request, Response) and not _keep_alive(
|
| 306 |
+
cast(Union[Request, Response], event)
|
| 307 |
+
):
|
| 308 |
+
self._cstate.process_keep_alive_disabled()
|
| 309 |
+
|
| 310 |
+
# 100-continue
|
| 311 |
+
if type(event) is Request and has_expect_100_continue(event):
|
| 312 |
+
self.client_is_waiting_for_100_continue = True
|
| 313 |
+
if type(event) in (InformationalResponse, Response):
|
| 314 |
+
self.client_is_waiting_for_100_continue = False
|
| 315 |
+
if role is CLIENT and type(event) in (Data, EndOfMessage):
|
| 316 |
+
self.client_is_waiting_for_100_continue = False
|
| 317 |
+
|
| 318 |
+
self._respond_to_state_changes(old_states, event)
|
| 319 |
+
|
| 320 |
+
def _get_io_object(
|
| 321 |
+
self,
|
| 322 |
+
role: Type[Sentinel],
|
| 323 |
+
event: Optional[Event],
|
| 324 |
+
io_dict: Union[ReadersType, WritersType],
|
| 325 |
+
) -> Optional[Callable[..., Any]]:
|
| 326 |
+
# event may be None; it's only used when entering SEND_BODY
|
| 327 |
+
state = self._cstate.states[role]
|
| 328 |
+
if state is SEND_BODY:
|
| 329 |
+
# Special case: the io_dict has a dict of reader/writer factories
|
| 330 |
+
# that depend on the request/response framing.
|
| 331 |
+
framing_type, args = _body_framing(
|
| 332 |
+
cast(bytes, self._request_method), cast(Union[Request, Response], event)
|
| 333 |
+
)
|
| 334 |
+
return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index]
|
| 335 |
+
else:
|
| 336 |
+
# General case: the io_dict just has the appropriate reader/writer
|
| 337 |
+
# for this state
|
| 338 |
+
return io_dict.get((role, state)) # type: ignore[return-value]
|
| 339 |
+
|
| 340 |
+
# This must be called after any action that might have caused
|
| 341 |
+
# self._cstate.states to change.
|
| 342 |
+
def _respond_to_state_changes(
|
| 343 |
+
self,
|
| 344 |
+
old_states: Dict[Type[Sentinel], Type[Sentinel]],
|
| 345 |
+
event: Optional[Event] = None,
|
| 346 |
+
) -> None:
|
| 347 |
+
# Update reader/writer
|
| 348 |
+
if self.our_state != old_states[self.our_role]:
|
| 349 |
+
self._writer = self._get_io_object(self.our_role, event, WRITERS)
|
| 350 |
+
if self.their_state != old_states[self.their_role]:
|
| 351 |
+
self._reader = self._get_io_object(self.their_role, event, READERS)
|
| 352 |
+
|
| 353 |
+
@property
|
| 354 |
+
def trailing_data(self) -> Tuple[bytes, bool]:
|
| 355 |
+
"""Data that has been received, but not yet processed, represented as
|
| 356 |
+
a tuple with two elements, where the first is a byte-string containing
|
| 357 |
+
the unprocessed data itself, and the second is a bool that is True if
|
| 358 |
+
the receive connection was closed.
|
| 359 |
+
|
| 360 |
+
See :ref:`switching-protocols` for discussion of why you'd want this.
|
| 361 |
+
"""
|
| 362 |
+
return (bytes(self._receive_buffer), self._receive_buffer_closed)
|
| 363 |
+
|
| 364 |
+
def receive_data(self, data: bytes) -> None:
|
| 365 |
+
"""Add data to our internal receive buffer.
|
| 366 |
+
|
| 367 |
+
This does not actually do any processing on the data, just stores
|
| 368 |
+
it. To trigger processing, you have to call :meth:`next_event`.
|
| 369 |
+
|
| 370 |
+
Args:
|
| 371 |
+
data (:term:`bytes-like object`):
|
| 372 |
+
The new data that was just received.
|
| 373 |
+
|
| 374 |
+
Special case: If *data* is an empty byte-string like ``b""``,
|
| 375 |
+
then this indicates that the remote side has closed the
|
| 376 |
+
connection (end of file). Normally this is convenient, because
|
| 377 |
+
standard Python APIs like :meth:`file.read` or
|
| 378 |
+
:meth:`socket.recv` use ``b""`` to indicate end-of-file, while
|
| 379 |
+
other failures to read are indicated using other mechanisms
|
| 380 |
+
like raising :exc:`TimeoutError`. When using such an API you
|
| 381 |
+
can just blindly pass through whatever you get from ``read``
|
| 382 |
+
to :meth:`receive_data`, and everything will work.
|
| 383 |
+
|
| 384 |
+
But, if you have an API where reading an empty string is a
|
| 385 |
+
valid non-EOF condition, then you need to be aware of this and
|
| 386 |
+
make sure to check for such strings and avoid passing them to
|
| 387 |
+
:meth:`receive_data`.
|
| 388 |
+
|
| 389 |
+
Returns:
|
| 390 |
+
Nothing, but after calling this you should call :meth:`next_event`
|
| 391 |
+
to parse the newly received data.
|
| 392 |
+
|
| 393 |
+
Raises:
|
| 394 |
+
RuntimeError:
|
| 395 |
+
Raised if you pass an empty *data*, indicating EOF, and then
|
| 396 |
+
pass a non-empty *data*, indicating more data that somehow
|
| 397 |
+
arrived after the EOF.
|
| 398 |
+
|
| 399 |
+
(Calling ``receive_data(b"")`` multiple times is fine,
|
| 400 |
+
and equivalent to calling it once.)
|
| 401 |
+
|
| 402 |
+
"""
|
| 403 |
+
if data:
|
| 404 |
+
if self._receive_buffer_closed:
|
| 405 |
+
raise RuntimeError("received close, then received more data?")
|
| 406 |
+
self._receive_buffer += data
|
| 407 |
+
else:
|
| 408 |
+
self._receive_buffer_closed = True
|
| 409 |
+
|
| 410 |
+
def _extract_next_receive_event(
|
| 411 |
+
self,
|
| 412 |
+
) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
|
| 413 |
+
state = self.their_state
|
| 414 |
+
# We don't pause immediately when they enter DONE, because even in
|
| 415 |
+
# DONE state we can still process a ConnectionClosed() event. But
|
| 416 |
+
# if we have data in our buffer, then we definitely aren't getting
|
| 417 |
+
# a ConnectionClosed() immediately and we need to pause.
|
| 418 |
+
if state is DONE and self._receive_buffer:
|
| 419 |
+
return PAUSED
|
| 420 |
+
if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL:
|
| 421 |
+
return PAUSED
|
| 422 |
+
assert self._reader is not None
|
| 423 |
+
event = self._reader(self._receive_buffer)
|
| 424 |
+
if event is None:
|
| 425 |
+
if not self._receive_buffer and self._receive_buffer_closed:
|
| 426 |
+
# In some unusual cases (basically just HTTP/1.0 bodies), EOF
|
| 427 |
+
# triggers an actual protocol event; in that case, we want to
|
| 428 |
+
# return that event, and then the state will change and we'll
|
| 429 |
+
# get called again to generate the actual ConnectionClosed().
|
| 430 |
+
if hasattr(self._reader, "read_eof"):
|
| 431 |
+
event = self._reader.read_eof()
|
| 432 |
+
else:
|
| 433 |
+
event = ConnectionClosed()
|
| 434 |
+
if event is None:
|
| 435 |
+
event = NEED_DATA
|
| 436 |
+
return event # type: ignore[no-any-return]
|
| 437 |
+
|
| 438 |
+
def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
|
| 439 |
+
"""Parse the next event out of our receive buffer, update our internal
|
| 440 |
+
state, and return it.
|
| 441 |
+
|
| 442 |
+
This is a mutating operation -- think of it like calling :func:`next`
|
| 443 |
+
on an iterator.
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
: One of three things:
|
| 447 |
+
|
| 448 |
+
1) An event object -- see :ref:`events`.
|
| 449 |
+
|
| 450 |
+
2) The special constant :data:`NEED_DATA`, which indicates that
|
| 451 |
+
you need to read more data from your socket and pass it to
|
| 452 |
+
:meth:`receive_data` before this method will be able to return
|
| 453 |
+
any more events.
|
| 454 |
+
|
| 455 |
+
3) The special constant :data:`PAUSED`, which indicates that we
|
| 456 |
+
are not in a state where we can process incoming data (usually
|
| 457 |
+
because the peer has finished their part of the current
|
| 458 |
+
request/response cycle, and you have not yet called
|
| 459 |
+
:meth:`start_next_cycle`). See :ref:`flow-control` for details.
|
| 460 |
+
|
| 461 |
+
Raises:
|
| 462 |
+
RemoteProtocolError:
|
| 463 |
+
The peer has misbehaved. You should close the connection
|
| 464 |
+
(possibly after sending some kind of 4xx response).
|
| 465 |
+
|
| 466 |
+
Once this method returns :class:`ConnectionClosed` once, then all
|
| 467 |
+
subsequent calls will also return :class:`ConnectionClosed`.
|
| 468 |
+
|
| 469 |
+
If this method raises any exception besides :exc:`RemoteProtocolError`
|
| 470 |
+
then that's a bug -- if it happens please file a bug report!
|
| 471 |
+
|
| 472 |
+
If this method raises any exception then it also sets
|
| 473 |
+
:attr:`Connection.their_state` to :data:`ERROR` -- see
|
| 474 |
+
:ref:`error-handling` for discussion.
|
| 475 |
+
|
| 476 |
+
"""
|
| 477 |
+
|
| 478 |
+
if self.their_state is ERROR:
|
| 479 |
+
raise RemoteProtocolError("Can't receive data when peer state is ERROR")
|
| 480 |
+
try:
|
| 481 |
+
event = self._extract_next_receive_event()
|
| 482 |
+
if event not in [NEED_DATA, PAUSED]:
|
| 483 |
+
self._process_event(self.their_role, cast(Event, event))
|
| 484 |
+
if event is NEED_DATA:
|
| 485 |
+
if len(self._receive_buffer) > self._max_incomplete_event_size:
|
| 486 |
+
# 431 is "Request header fields too large" which is pretty
|
| 487 |
+
# much the only situation where we can get here
|
| 488 |
+
raise RemoteProtocolError(
|
| 489 |
+
"Receive buffer too long", error_status_hint=431
|
| 490 |
+
)
|
| 491 |
+
if self._receive_buffer_closed:
|
| 492 |
+
# We're still trying to complete some event, but that's
|
| 493 |
+
# never going to happen because no more data is coming
|
| 494 |
+
raise RemoteProtocolError("peer unexpectedly closed connection")
|
| 495 |
+
return event
|
| 496 |
+
except BaseException as exc:
|
| 497 |
+
self._process_error(self.their_role)
|
| 498 |
+
if isinstance(exc, LocalProtocolError):
|
| 499 |
+
exc._reraise_as_remote_protocol_error()
|
| 500 |
+
else:
|
| 501 |
+
raise
|
| 502 |
+
|
| 503 |
+
@overload
|
| 504 |
+
def send(self, event: ConnectionClosed) -> None:
|
| 505 |
+
...
|
| 506 |
+
|
| 507 |
+
@overload
|
| 508 |
+
def send(
|
| 509 |
+
self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage]
|
| 510 |
+
) -> bytes:
|
| 511 |
+
...
|
| 512 |
+
|
| 513 |
+
@overload
|
| 514 |
+
def send(self, event: Event) -> Optional[bytes]:
|
| 515 |
+
...
|
| 516 |
+
|
| 517 |
+
def send(self, event: Event) -> Optional[bytes]:
|
| 518 |
+
"""Convert a high-level event into bytes that can be sent to the peer,
|
| 519 |
+
while updating our internal state machine.
|
| 520 |
+
|
| 521 |
+
Args:
|
| 522 |
+
event: The :ref:`event <events>` to send.
|
| 523 |
+
|
| 524 |
+
Returns:
|
| 525 |
+
If ``type(event) is ConnectionClosed``, then returns
|
| 526 |
+
``None``. Otherwise, returns a :term:`bytes-like object`.
|
| 527 |
+
|
| 528 |
+
Raises:
|
| 529 |
+
LocalProtocolError:
|
| 530 |
+
Sending this event at this time would violate our
|
| 531 |
+
understanding of the HTTP/1.1 protocol.
|
| 532 |
+
|
| 533 |
+
If this method raises any exception then it also sets
|
| 534 |
+
:attr:`Connection.our_state` to :data:`ERROR` -- see
|
| 535 |
+
:ref:`error-handling` for discussion.
|
| 536 |
+
|
| 537 |
+
"""
|
| 538 |
+
data_list = self.send_with_data_passthrough(event)
|
| 539 |
+
if data_list is None:
|
| 540 |
+
return None
|
| 541 |
+
else:
|
| 542 |
+
return b"".join(data_list)
|
| 543 |
+
|
| 544 |
+
def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]:
|
| 545 |
+
"""Identical to :meth:`send`, except that in situations where
|
| 546 |
+
:meth:`send` returns a single :term:`bytes-like object`, this instead
|
| 547 |
+
returns a list of them -- and when sending a :class:`Data` event, this
|
| 548 |
+
list is guaranteed to contain the exact object you passed in as
|
| 549 |
+
:attr:`Data.data`. See :ref:`sendfile` for discussion.
|
| 550 |
+
|
| 551 |
+
"""
|
| 552 |
+
if self.our_state is ERROR:
|
| 553 |
+
raise LocalProtocolError("Can't send data when our state is ERROR")
|
| 554 |
+
try:
|
| 555 |
+
if type(event) is Response:
|
| 556 |
+
event = self._clean_up_response_headers_for_sending(event)
|
| 557 |
+
# We want to call _process_event before calling the writer,
|
| 558 |
+
# because if someone tries to do something invalid then this will
|
| 559 |
+
# give a sensible error message, while our writers all just assume
|
| 560 |
+
# they will only receive valid events. But, _process_event might
|
| 561 |
+
# change self._writer. So we have to do a little dance:
|
| 562 |
+
writer = self._writer
|
| 563 |
+
self._process_event(self.our_role, event)
|
| 564 |
+
if type(event) is ConnectionClosed:
|
| 565 |
+
return None
|
| 566 |
+
else:
|
| 567 |
+
# In any situation where writer is None, process_event should
|
| 568 |
+
# have raised ProtocolError
|
| 569 |
+
assert writer is not None
|
| 570 |
+
data_list: List[bytes] = []
|
| 571 |
+
writer(event, data_list.append)
|
| 572 |
+
return data_list
|
| 573 |
+
except:
|
| 574 |
+
self._process_error(self.our_role)
|
| 575 |
+
raise
|
| 576 |
+
|
| 577 |
+
def send_failed(self) -> None:
|
| 578 |
+
"""Notify the state machine that we failed to send the data it gave
|
| 579 |
+
us.
|
| 580 |
+
|
| 581 |
+
This causes :attr:`Connection.our_state` to immediately become
|
| 582 |
+
:data:`ERROR` -- see :ref:`error-handling` for discussion.
|
| 583 |
+
|
| 584 |
+
"""
|
| 585 |
+
self._process_error(self.our_role)
|
| 586 |
+
|
| 587 |
+
# When sending a Response, we take responsibility for a few things:
|
| 588 |
+
#
|
| 589 |
+
# - Sometimes you MUST set Connection: close. We take care of those
|
| 590 |
+
# times. (You can also set it yourself if you want, and if you do then
|
| 591 |
+
# we'll respect that and close the connection at the right time. But you
|
| 592 |
+
# don't have to worry about that unless you want to.)
|
| 593 |
+
#
|
| 594 |
+
# - The user has to set Content-Length if they want it. Otherwise, for
|
| 595 |
+
# responses that have bodies (e.g. not HEAD), then we will automatically
|
| 596 |
+
# select the right mechanism for streaming a body of unknown length,
|
| 597 |
+
# which depends on depending on the peer's HTTP version.
|
| 598 |
+
#
|
| 599 |
+
# This function's *only* responsibility is making sure headers are set up
|
| 600 |
+
# right -- everything downstream just looks at the headers. There are no
|
| 601 |
+
# side channels.
|
| 602 |
+
def _clean_up_response_headers_for_sending(self, response: Response) -> Response:
|
| 603 |
+
assert type(response) is Response
|
| 604 |
+
|
| 605 |
+
headers = response.headers
|
| 606 |
+
need_close = False
|
| 607 |
+
|
| 608 |
+
# HEAD requests need some special handling: they always act like they
|
| 609 |
+
# have Content-Length: 0, and that's how _body_framing treats
|
| 610 |
+
# them. But their headers are supposed to match what we would send if
|
| 611 |
+
# the request was a GET. (Technically there is one deviation allowed:
|
| 612 |
+
# we're allowed to leave out the framing headers -- see
|
| 613 |
+
# https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as
|
| 614 |
+
# easy to get them right.)
|
| 615 |
+
method_for_choosing_headers = cast(bytes, self._request_method)
|
| 616 |
+
if method_for_choosing_headers == b"HEAD":
|
| 617 |
+
method_for_choosing_headers = b"GET"
|
| 618 |
+
framing_type, _ = _body_framing(method_for_choosing_headers, response)
|
| 619 |
+
if framing_type in ("chunked", "http/1.0"):
|
| 620 |
+
# This response has a body of unknown length.
|
| 621 |
+
# If our peer is HTTP/1.1, we use Transfer-Encoding: chunked
|
| 622 |
+
# If our peer is HTTP/1.0, we use no framing headers, and close the
|
| 623 |
+
# connection afterwards.
|
| 624 |
+
#
|
| 625 |
+
# Make sure to clear Content-Length (in principle user could have
|
| 626 |
+
# set both and then we ignored Content-Length b/c
|
| 627 |
+
# Transfer-Encoding overwrote it -- this would be naughty of them,
|
| 628 |
+
# but the HTTP spec says that if our peer does this then we have
|
| 629 |
+
# to fix it instead of erroring out, so we'll accord the user the
|
| 630 |
+
# same respect).
|
| 631 |
+
headers = set_comma_header(headers, b"content-length", [])
|
| 632 |
+
if self.their_http_version is None or self.their_http_version < b"1.1":
|
| 633 |
+
# Either we never got a valid request and are sending back an
|
| 634 |
+
# error (their_http_version is None), so we assume the worst;
|
| 635 |
+
# or else we did get a valid HTTP/1.0 request, so we know that
|
| 636 |
+
# they don't understand chunked encoding.
|
| 637 |
+
headers = set_comma_header(headers, b"transfer-encoding", [])
|
| 638 |
+
# This is actually redundant ATM, since currently we
|
| 639 |
+
# unconditionally disable keep-alive when talking to HTTP/1.0
|
| 640 |
+
# peers. But let's be defensive just in case we add
|
| 641 |
+
# Connection: keep-alive support later:
|
| 642 |
+
if self._request_method != b"HEAD":
|
| 643 |
+
need_close = True
|
| 644 |
+
else:
|
| 645 |
+
headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"])
|
| 646 |
+
|
| 647 |
+
if not self._cstate.keep_alive or need_close:
|
| 648 |
+
# Make sure Connection: close is set
|
| 649 |
+
connection = set(get_comma_header(headers, b"connection"))
|
| 650 |
+
connection.discard(b"keep-alive")
|
| 651 |
+
connection.add(b"close")
|
| 652 |
+
headers = set_comma_header(headers, b"connection", sorted(connection))
|
| 653 |
+
|
| 654 |
+
return Response(
|
| 655 |
+
headers=headers,
|
| 656 |
+
status_code=response.status_code,
|
| 657 |
+
http_version=response.http_version,
|
| 658 |
+
reason=response.reason,
|
| 659 |
+
)
|
.cache/uv/archive-v0/6utaviRiYOUSO0ES4zoot/h11/_events.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# High level events that make up HTTP/1.1 conversations. Loosely inspired by
|
| 2 |
+
# the corresponding events in hyper-h2:
|
| 3 |
+
#
|
| 4 |
+
# http://python-hyper.org/h2/en/stable/api.html#events
|
| 5 |
+
#
|
| 6 |
+
# Don't subclass these. Stuff will break.
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
from abc import ABC
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from typing import List, Tuple, Union
|
| 12 |
+
|
| 13 |
+
from ._abnf import method, request_target
|
| 14 |
+
from ._headers import Headers, normalize_and_validate
|
| 15 |
+
from ._util import bytesify, LocalProtocolError, validate
|
| 16 |
+
|
| 17 |
+
# Everything in __all__ gets re-exported as part of the h11 public API.
|
| 18 |
+
__all__ = [
|
| 19 |
+
"Event",
|
| 20 |
+
"Request",
|
| 21 |
+
"InformationalResponse",
|
| 22 |
+
"Response",
|
| 23 |
+
"Data",
|
| 24 |
+
"EndOfMessage",
|
| 25 |
+
"ConnectionClosed",
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
method_re = re.compile(method.encode("ascii"))
|
| 29 |
+
request_target_re = re.compile(request_target.encode("ascii"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Event(ABC):
|
| 33 |
+
"""
|
| 34 |
+
Base class for h11 events.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
__slots__ = ()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass(init=False, frozen=True)
|
| 41 |
+
class Request(Event):
|
| 42 |
+
"""The beginning of an HTTP request.
|
| 43 |
+
|
| 44 |
+
Fields:
|
| 45 |
+
|
| 46 |
+
.. attribute:: method
|
| 47 |
+
|
| 48 |
+
An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte
|
| 49 |
+
string. :term:`Bytes-like objects <bytes-like object>` and native
|
| 50 |
+
strings containing only ascii characters will be automatically
|
| 51 |
+
converted to byte strings.
|
| 52 |
+
|
| 53 |
+
.. attribute:: target
|
| 54 |
+
|
| 55 |
+
The target of an HTTP request, e.g. ``b"/index.html"``, or one of the
|
| 56 |
+
more exotic formats described in `RFC 7320, section 5.3
|
| 57 |
+
<https://tools.ietf.org/html/rfc7230#section-5.3>`_. Always a byte
|
| 58 |
+
string. :term:`Bytes-like objects <bytes-like object>` and native
|
| 59 |
+
strings containing only ascii characters will be automatically
|
| 60 |
+
converted to byte strings.
|
| 61 |
+
|
| 62 |
+
.. attribute:: headers
|
| 63 |
+
|
| 64 |
+
Request headers, represented as a list of (name, value) pairs. See
|
| 65 |
+
:ref:`the header normalization rules <headers-format>` for details.
|
| 66 |
+
|
| 67 |
+
.. attribute:: http_version
|
| 68 |
+
|
| 69 |
+
The HTTP protocol version, represented as a byte string like
|
| 70 |
+
``b"1.1"``. See :ref:`the HTTP version normalization rules
|
| 71 |
+
<http_version-format>` for details.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
__slots__ = ("method", "headers", "target", "http_version")
|
| 76 |
+
|
| 77 |
+
method: bytes
|
| 78 |
+
headers: Headers
|
| 79 |
+
target: bytes
|
| 80 |
+
http_version: bytes
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
*,
|
| 85 |
+
method: Union[bytes, str],
|
| 86 |
+
headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
|
| 87 |
+
target: Union[bytes, str],
|
| 88 |
+
http_version: Union[bytes, str] = b"1.1",
|
| 89 |
+
_parsed: bool = False,
|
| 90 |
+
) -> None:
|
| 91 |
+
super().__init__()
|
| 92 |
+
if isinstance(headers, Headers):
|
| 93 |
+
object.__setattr__(self, "headers", headers)
|
| 94 |
+
else:
|
| 95 |
+
object.__setattr__(
|
| 96 |
+
self, "headers", normalize_and_validate(headers, _parsed=_parsed)
|
| 97 |
+
)
|
| 98 |
+
if not _parsed:
|
| 99 |
+
object.__setattr__(self, "method", bytesify(method))
|
| 100 |
+
object.__setattr__(self, "target", bytesify(target))
|
| 101 |
+
object.__setattr__(self, "http_version", bytesify(http_version))
|
| 102 |
+
else:
|
| 103 |
+
object.__setattr__(self, "method", method)
|
| 104 |
+
object.__setattr__(self, "target", target)
|
| 105 |
+
object.__setattr__(self, "http_version", http_version)
|
| 106 |
+
|
| 107 |
+
# "A server MUST respond with a 400 (Bad Request) status code to any
|
| 108 |
+
# HTTP/1.1 request message that lacks a Host header field and to any
|
| 109 |
+
# request message that contains more than one Host header field or a
|
| 110 |
+
# Host header field with an invalid field-value."
|
| 111 |
+
# -- https://tools.ietf.org/html/rfc7230#section-5.4
|
| 112 |
+
host_count = 0
|
| 113 |
+
for name, value in self.headers:
|
| 114 |
+
if name == b"host":
|
| 115 |
+
host_count += 1
|
| 116 |
+
if self.http_version == b"1.1" and host_count == 0:
|
| 117 |
+
raise LocalProtocolError("Missing mandatory Host: header")
|
| 118 |
+
if host_count > 1:
|
| 119 |
+
raise LocalProtocolError("Found multiple Host: headers")
|
| 120 |
+
|
| 121 |
+
validate(method_re, self.method, "Illegal method characters")
|
| 122 |
+
validate(request_target_re, self.target, "Illegal target characters")
|
| 123 |
+
|
| 124 |
+
# This is an unhashable type.
|
| 125 |
+
__hash__ = None # type: ignore
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@dataclass(init=False, frozen=True)
|
| 129 |
+
class _ResponseBase(Event):
|
| 130 |
+
__slots__ = ("headers", "http_version", "reason", "status_code")
|
| 131 |
+
|
| 132 |
+
headers: Headers
|
| 133 |
+
http_version: bytes
|
| 134 |
+
reason: bytes
|
| 135 |
+
status_code: int
|
| 136 |
+
|
| 137 |
+
def __init__(
|
| 138 |
+
self,
|
| 139 |
+
*,
|
| 140 |
+
headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
|
| 141 |
+
status_code: int,
|
| 142 |
+
http_version: Union[bytes, str] = b"1.1",
|
| 143 |
+
reason: Union[bytes, str] = b"",
|
| 144 |
+
_parsed: bool = False,
|
| 145 |
+
) -> None:
|
| 146 |
+
super().__init__()
|
| 147 |
+
if isinstance(headers, Headers):
|
| 148 |
+
object.__setattr__(self, "headers", headers)
|
| 149 |
+
else:
|
| 150 |
+
object.__setattr__(
|
| 151 |
+
self, "headers", normalize_and_validate(headers, _parsed=_parsed)
|
| 152 |
+
)
|
| 153 |
+
if not _parsed:
|
| 154 |
+
object.__setattr__(self, "reason", bytesify(reason))
|
| 155 |
+
object.__setattr__(self, "http_version", bytesify(http_version))
|
| 156 |
+
if not isinstance(status_code, int):
|
| 157 |
+
raise LocalProtocolError("status code must be integer")
|
| 158 |
+
# Because IntEnum objects are instances of int, but aren't
|
| 159 |
+
# duck-compatible (sigh), see gh-72.
|
| 160 |
+
object.__setattr__(self, "status_code", int(status_code))
|
| 161 |
+
else:
|
| 162 |
+
object.__setattr__(self, "reason", reason)
|
| 163 |
+
object.__setattr__(self, "http_version", http_version)
|
| 164 |
+
object.__setattr__(self, "status_code", status_code)
|
| 165 |
+
|
| 166 |
+
self.__post_init__()
|
| 167 |
+
|
| 168 |
+
def __post_init__(self) -> None:
|
| 169 |
+
pass
|
| 170 |
+
|
| 171 |
+
# This is an unhashable type.
|
| 172 |
+
__hash__ = None # type: ignore
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@dataclass(init=False, frozen=True)
|
| 176 |
+
class InformationalResponse(_ResponseBase):
|
| 177 |
+
"""An HTTP informational response.
|
| 178 |
+
|
| 179 |
+
Fields:
|
| 180 |
+
|
| 181 |
+
.. attribute:: status_code
|
| 182 |
+
|
| 183 |
+
The status code of this response, as an integer. For an
|
| 184 |
+
:class:`InformationalResponse`, this is always in the range [100,
|
| 185 |
+
200).
|
| 186 |
+
|
| 187 |
+
.. attribute:: headers
|
| 188 |
+
|
| 189 |
+
Request headers, represented as a list of (name, value) pairs. See
|
| 190 |
+
:ref:`the header normalization rules <headers-format>` for
|
| 191 |
+
details.
|
| 192 |
+
|
| 193 |
+
.. attribute:: http_version
|
| 194 |
+
|
| 195 |
+
The HTTP protocol version, represented as a byte string like
|
| 196 |
+
``b"1.1"``. See :ref:`the HTTP version normalization rules
|
| 197 |
+
<http_version-format>` for details.
|
| 198 |
+
|
| 199 |
+
.. attribute:: reason
|
| 200 |
+
|
| 201 |
+
The reason phrase of this response, as a byte string. For example:
|
| 202 |
+
``b"OK"``, or ``b"Not Found"``.
|
| 203 |
+
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
def __post_init__(self) -> None:
|
| 207 |
+
if not (100 <= self.status_code < 200):
|
| 208 |
+
raise LocalProtocolError(
|
| 209 |
+
"InformationalResponse status_code should be in range "
|
| 210 |
+
"[100, 200), not {}".format(self.status_code)
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# This is an unhashable type.
|
| 214 |
+
__hash__ = None # type: ignore
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@dataclass(init=False, frozen=True)
|
| 218 |
+
class Response(_ResponseBase):
|
| 219 |
+
"""The beginning of an HTTP response.
|
| 220 |
+
|
| 221 |
+
Fields:
|
| 222 |
+
|
| 223 |
+
.. attribute:: status_code
|
| 224 |
+
|
| 225 |
+
The status code of this response, as an integer. For an
|
| 226 |
+
:class:`Response`, this is always in the range [200,
|
| 227 |
+
1000).
|
| 228 |
+
|
| 229 |
+
.. attribute:: headers
|
| 230 |
+
|
| 231 |
+
Request headers, represented as a list of (name, value) pairs. See
|
| 232 |
+
:ref:`the header normalization rules <headers-format>` for details.
|
| 233 |
+
|
| 234 |
+
.. attribute:: http_version
|
| 235 |
+
|
| 236 |
+
The HTTP protocol version, represented as a byte string like
|
| 237 |
+
``b"1.1"``. See :ref:`the HTTP version normalization rules
|
| 238 |
+
<http_version-format>` for details.
|
| 239 |
+
|
| 240 |
+
.. attribute:: reason
|
| 241 |
+
|
| 242 |
+
The reason phrase of this response, as a byte string. For example:
|
| 243 |
+
``b"OK"``, or ``b"Not Found"``.
|
| 244 |
+
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
def __post_init__(self) -> None:
|
| 248 |
+
if not (200 <= self.status_code < 1000):
|
| 249 |
+
raise LocalProtocolError(
|
| 250 |
+
"Response status_code should be in range [200, 1000), not {}".format(
|
| 251 |
+
self.status_code
|
| 252 |
+
)
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# This is an unhashable type.
|
| 256 |
+
__hash__ = None # type: ignore
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@dataclass(init=False, frozen=True)
|
| 260 |
+
class Data(Event):
|
| 261 |
+
"""Part of an HTTP message body.
|
| 262 |
+
|
| 263 |
+
Fields:
|
| 264 |
+
|
| 265 |
+
.. attribute:: data
|
| 266 |
+
|
| 267 |
+
A :term:`bytes-like object` containing part of a message body. Or, if
|
| 268 |
+
using the ``combine=False`` argument to :meth:`Connection.send`, then
|
| 269 |
+
any object that your socket writing code knows what to do with, and for
|
| 270 |
+
which calling :func:`len` returns the number of bytes that will be
|
| 271 |
+
written -- see :ref:`sendfile` for details.
|
| 272 |
+
|
| 273 |
+
.. attribute:: chunk_start
|
| 274 |
+
|
| 275 |
+
A marker that indicates whether this data object is from the start of a
|
| 276 |
+
chunked transfer encoding chunk. This field is ignored when when a Data
|
| 277 |
+
event is provided to :meth:`Connection.send`: it is only valid on
|
| 278 |
+
events emitted from :meth:`Connection.next_event`. You probably
|
| 279 |
+
shouldn't use this attribute at all; see
|
| 280 |
+
:ref:`chunk-delimiters-are-bad` for details.
|
| 281 |
+
|
| 282 |
+
.. attribute:: chunk_end
|
| 283 |
+
|
| 284 |
+
A marker that indicates whether this data object is the last for a
|
| 285 |
+
given chunked transfer encoding chunk. This field is ignored when when
|
| 286 |
+
a Data event is provided to :meth:`Connection.send`: it is only valid
|
| 287 |
+
on events emitted from :meth:`Connection.next_event`. You probably
|
| 288 |
+
shouldn't use this attribute at all; see
|
| 289 |
+
:ref:`chunk-delimiters-are-bad` for details.
|
| 290 |
+
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
__slots__ = ("data", "chunk_start", "chunk_end")
|
| 294 |
+
|
| 295 |
+
data: bytes
|
| 296 |
+
chunk_start: bool
|
| 297 |
+
chunk_end: bool
|
| 298 |
+
|
| 299 |
+
def __init__(
|
| 300 |
+
self, data: bytes, chunk_start: bool = False, chunk_end: bool = False
|
| 301 |
+
) -> None:
|
| 302 |
+
object.__setattr__(self, "data", data)
|
| 303 |
+
object.__setattr__(self, "chunk_start", chunk_start)
|
| 304 |
+
object.__setattr__(self, "chunk_end", chunk_end)
|
| 305 |
+
|
| 306 |
+
# This is an unhashable type.
|
| 307 |
+
__hash__ = None # type: ignore
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that
|
| 311 |
+
# are forbidden to be sent in a trailer, since processing them as if they were
|
| 312 |
+
# present in the header section might bypass external security filters."
|
| 313 |
+
# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part
|
| 314 |
+
# Unfortunately, the list of forbidden fields is long and vague :-/
|
| 315 |
+
@dataclass(init=False, frozen=True)
|
| 316 |
+
class EndOfMessage(Event):
|
| 317 |
+
"""The end of an HTTP message.
|
| 318 |
+
|
| 319 |
+
Fields:
|
| 320 |
+
|
| 321 |
+
.. attribute:: headers
|
| 322 |
+
|
| 323 |
+
Default value: ``[]``
|
| 324 |
+
|
| 325 |
+
Any trailing headers attached to this message, represented as a list of
|
| 326 |
+
(name, value) pairs. See :ref:`the header normalization rules
|
| 327 |
+
<headers-format>` for details.
|
| 328 |
+
|
| 329 |
+
Must be empty unless ``Transfer-Encoding: chunked`` is in use.
|
| 330 |
+
|
| 331 |
+
"""
|
| 332 |
+
|
| 333 |
+
__slots__ = ("headers",)
|
| 334 |
+
|
| 335 |
+
headers: Headers
|
| 336 |
+
|
| 337 |
+
def __init__(
|
| 338 |
+
self,
|
| 339 |
+
*,
|
| 340 |
+
headers: Union[
|
| 341 |
+
Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None
|
| 342 |
+
] = None,
|
| 343 |
+
_parsed: bool = False,
|
| 344 |
+
) -> None:
|
| 345 |
+
super().__init__()
|
| 346 |
+
if headers is None:
|
| 347 |
+
headers = Headers([])
|
| 348 |
+
elif not isinstance(headers, Headers):
|
| 349 |
+
headers = normalize_and_validate(headers, _parsed=_parsed)
|
| 350 |
+
|
| 351 |
+
object.__setattr__(self, "headers", headers)
|
| 352 |
+
|
| 353 |
+
# This is an unhashable type.
|
| 354 |
+
__hash__ = None # type: ignore
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
@dataclass(frozen=True)
|
| 358 |
+
class ConnectionClosed(Event):
|
| 359 |
+
"""This event indicates that the sender has closed their outgoing
|
| 360 |
+
connection.
|
| 361 |
+
|
| 362 |
+
Note that this does not necessarily mean that they can't *receive* further
|
| 363 |
+
data, because TCP connections are composed to two one-way channels which
|
| 364 |
+
can be closed independently. See :ref:`closing` for details.
|
| 365 |
+
|
| 366 |
+
No fields.
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
pass
|
.cache/uv/archive-v0/6utaviRiYOUS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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
|
| 3 |
+
|
| 4 |
+
from ._abnf import field_name, field_value
|
| 5 |
+
from ._util import bytesify, LocalProtocolError, validate
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from ._events import Request
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from typing import Literal
|
| 12 |
+
except ImportError:
|
| 13 |
+
from typing_extensions import Literal # type: ignore
|
| 14 |
+
|
| 15 |
+
CONTENT_LENGTH_MAX_DIGITS = 20 # allow up to 1 billion TB - 1
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Facts
|
| 19 |
+
# -----
|
| 20 |
+
#
|
| 21 |
+
# Headers are:
|
| 22 |
+
# keys: case-insensitive ascii
|
| 23 |
+
# values: mixture of ascii and raw bytes
|
| 24 |
+
#
|
| 25 |
+
# "Historically, HTTP has allowed field content with text in the ISO-8859-1
|
| 26 |
+
# charset [ISO-8859-1], supporting other charsets only through use of
|
| 27 |
+
# [RFC2047] encoding. In practice, most HTTP header field values use only a
|
| 28 |
+
# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD
|
| 29 |
+
# limit their field values to US-ASCII octets. A recipient SHOULD treat other
|
| 30 |
+
# octets in field content (obs-text) as opaque data."
|
| 31 |
+
# And it deprecates all non-ascii values
|
| 32 |
+
#
|
| 33 |
+
# Leading/trailing whitespace in header names is forbidden
|
| 34 |
+
#
|
| 35 |
+
# Values get leading/trailing whitespace stripped
|
| 36 |
+
#
|
| 37 |
+
# Content-Disposition actually needs to contain unicode semantically; to
|
| 38 |
+
# accomplish this it has a terrifically weird way of encoding the filename
|
| 39 |
+
# itself as ascii (and even this still has lots of cross-browser
|
| 40 |
+
# incompatibilities)
|
| 41 |
+
#
|
| 42 |
+
# Order is important:
|
| 43 |
+
# "a proxy MUST NOT change the order of these field values when forwarding a
|
| 44 |
+
# message"
|
| 45 |
+
# (and there are several headers where the order indicates a preference)
|
| 46 |
+
#
|
| 47 |
+
# Multiple occurences of the same header:
|
| 48 |
+
# "A sender MUST NOT generate multiple header fields with the same field name
|
| 49 |
+
# in a message unless either the entire field value for that header field is
|
| 50 |
+
# defined as a comma-separated list [or the header is Set-Cookie which gets a
|
| 51 |
+
# special exception]" - RFC 7230. (cookies are in RFC 6265)
|
| 52 |
+
#
|
| 53 |
+
# So every header aside from Set-Cookie can be merged by b", ".join if it
|
| 54 |
+
# occurs repeatedly. But, of course, they can't necessarily be split by
|
| 55 |
+
# .split(b","), because quoting.
|
| 56 |
+
#
|
| 57 |
+
# Given all this mess (case insensitive, duplicates allowed, order is
|
| 58 |
+
# important, ...), there doesn't appear to be any standard way to handle
|
| 59 |
+
# headers in Python -- they're almost like dicts, but... actually just
|
| 60 |
+
# aren't. For now we punt and just use a super simple representation: headers
|
| 61 |
+
# are a list of pairs
|
| 62 |
+
#
|
| 63 |
+
# [(name1, value1), (name2, value2), ...]
|
| 64 |
+
#
|
| 65 |
+
# where all entries are bytestrings, names are lowercase and have no
|
| 66 |
+
# leading/trailing whitespace, and values are bytestrings with no
|
| 67 |
+
# leading/trailing whitespace. Searching and updating are done via naive O(n)
|
| 68 |
+
# methods.
|
| 69 |
+
#
|
| 70 |
+
# Maybe a dict-of-lists would be better?
|
| 71 |
+
|
| 72 |
+
_content_length_re = re.compile(rb"[0-9]+")
|
| 73 |
+
_field_name_re = re.compile(field_name.encode("ascii"))
|
| 74 |
+
_field_value_re = re.compile(field_value.encode("ascii"))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Headers(Sequence[Tuple[bytes, bytes]]):
|
| 78 |
+
"""
|
| 79 |
+
A list-like interface that allows iterating over headers as byte-pairs
|
| 80 |
+
of (lowercased-name, value).
|
| 81 |
+
|
| 82 |
+
Internally we actually store the representation as three-tuples,
|
| 83 |
+
including both the raw original casing, in order to preserve casing
|
| 84 |
+
over-the-wire, and the lowercased name, for case-insensitive comparisions.
|
| 85 |
+
|
| 86 |
+
r = Request(
|
| 87 |
+
method="GET",
|
| 88 |
+
target="/",
|
| 89 |
+
headers=[("Host", "example.org"), ("Connection", "keep-alive")],
|
| 90 |
+
http_version="1.1",
|
| 91 |
+
)
|
| 92 |
+
assert r.headers == [
|
| 93 |
+
(b"host", b"example.org"),
|
| 94 |
+
(b"connection", b"keep-alive")
|
| 95 |
+
]
|
| 96 |
+
assert r.headers.raw_items() == [
|
| 97 |
+
(b"Host", b"example.org"),
|
| 98 |
+
(b"Connection", b"keep-alive")
|
| 99 |
+
]
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
__slots__ = "_full_items"
|
| 103 |
+
|
| 104 |
+
def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None:
|
| 105 |
+
self._full_items = full_items
|
| 106 |
+
|
| 107 |
+
def __bool__(self) -> bool:
|
| 108 |
+
return bool(self._full_items)
|
| 109 |
+
|
| 110 |
+
def __eq__(self, other: object) -> bool:
|
| 111 |
+
return list(self) == list(other) # type: ignore
|
| 112 |
+
|
| 113 |
+
def __len__(self) -> int:
|
| 114 |
+
return len(self._full_items)
|
| 115 |
+
|
| 116 |
+
def __repr__(self) -> str:
|
| 117 |
+
return "<Headers(%s)>" % repr(list(self))
|
| 118 |
+
|
| 119 |
+
def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override]
|
| 120 |
+
_, name, value = self._full_items[idx]
|
| 121 |
+
return (name, value)
|
| 122 |
+
|
| 123 |
+
def raw_items(self) -> List[Tuple[bytes, bytes]]:
|
| 124 |
+
return [(raw_name, value) for raw_name, _, value in self._full_items]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
HeaderTypes = Union[
|
| 128 |
+
List[Tuple[bytes, bytes]],
|
| 129 |
+
List[Tuple[bytes, str]],
|
| 130 |
+
List[Tuple[str, bytes]],
|
| 131 |
+
List[Tuple[str, str]],
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@overload
|
| 136 |
+
def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers:
|
| 137 |
+
...
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@overload
|
| 141 |
+
def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers:
|
| 142 |
+
...
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@overload
|
| 146 |
+
def normalize_and_validate(
|
| 147 |
+
headers: Union[Headers, HeaderTypes], _parsed: bool = False
|
| 148 |
+
) -> Headers:
|
| 149 |
+
...
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def normalize_and_validate(
|
| 153 |
+
headers: Union[Headers, HeaderTypes], _parsed: bool = False
|
| 154 |
+
) -> Headers:
|
| 155 |
+
new_headers = []
|
| 156 |
+
seen_content_length = None
|
| 157 |
+
saw_transfer_encoding = False
|
| 158 |
+
for name, value in headers:
|
| 159 |
+
# For headers coming out of the parser, we can safely skip some steps,
|
| 160 |
+
# because it always returns bytes and has already run these regexes
|
| 161 |
+
# over the data:
|
| 162 |
+
if not _parsed:
|
| 163 |
+
name = bytesify(name)
|
| 164 |
+
value = bytesify(value)
|
| 165 |
+
validate(_field_name_re, name, "Illegal header name {!r}", name)
|
| 166 |
+
validate(_field_value_re, value, "Illegal header value {!r}", value)
|
| 167 |
+
assert isinstance(name, bytes)
|
| 168 |
+
assert isinstance(value, bytes)
|
| 169 |
+
|
| 170 |
+
raw_name = name
|
| 171 |
+
name = name.lower()
|
| 172 |
+
if name == b"content-length":
|
| 173 |
+
lengths = {length.strip() for length in value.split(b",")}
|
| 174 |
+
if len(lengths) != 1:
|
| 175 |
+
raise LocalProtocolError("conflicting Content-Length headers")
|
| 176 |
+
value = lengths.pop()
|
| 177 |
+
validate(_content_length_re, value, "bad Content-Length")
|
| 178 |
+
if len(value) > CONTENT_LENGTH_MAX_DIGITS:
|
| 179 |
+
raise LocalProtocolError("bad Content-Length")
|
| 180 |
+
if seen_content_length is None:
|
| 181 |
+
seen_content_length = value
|
| 182 |
+
new_headers.append((raw_name, name, value))
|
| 183 |
+
elif seen_content_length != value:
|
| 184 |
+
raise LocalProtocolError("conflicting Content-Length headers")
|
| 185 |
+
elif name == b"transfer-encoding":
|
| 186 |
+
# "A server that receives a request message with a transfer coding
|
| 187 |
+
# it does not understand SHOULD respond with 501 (Not
|
| 188 |
+
# Implemented)."
|
| 189 |
+
# https://tools.ietf.org/html/rfc7230#section-3.3.1
|
| 190 |
+
if saw_transfer_encoding:
|
| 191 |
+
raise LocalProtocolError(
|
| 192 |
+
"multiple Transfer-Encoding headers", error_status_hint=501
|
| 193 |
+
)
|
| 194 |
+
# "All transfer-coding names are case-insensitive"
|
| 195 |
+
# -- https://tools.ietf.org/html/rfc7230#section-4
|
| 196 |
+
value = value.lower()
|
| 197 |
+
if value != b"chunked":
|
| 198 |
+
raise LocalProtocolError(
|
| 199 |
+
"Only Transfer-Encoding: chunked is supported",
|
| 200 |
+
error_status_hint=501,
|
| 201 |
+
)
|
| 202 |
+
saw_transfer_encoding = True
|
| 203 |
+
new_headers.append((raw_name, name, value))
|
| 204 |
+
else:
|
| 205 |
+
new_headers.append((raw_name, name, value))
|
| 206 |
+
return Headers(new_headers)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def get_comma_header(headers: Headers, name: bytes) -> List[bytes]:
|
| 210 |
+
# Should only be used for headers whose value is a list of
|
| 211 |
+
# comma-separated, case-insensitive values.
|
| 212 |
+
#
|
| 213 |
+
# The header name `name` is expected to be lower-case bytes.
|
| 214 |
+
#
|
| 215 |
+
# Connection: meets these criteria (including cast insensitivity).
|
| 216 |
+
#
|
| 217 |
+
# Content-Length: technically is just a single value (1*DIGIT), but the
|
| 218 |
+
# standard makes reference to implementations that do multiple values, and
|
| 219 |
+
# using this doesn't hurt. Ditto, case insensitivity doesn't things either
|
| 220 |
+
# way.
|
| 221 |
+
#
|
| 222 |
+
# Transfer-Encoding: is more complex (allows for quoted strings), so
|
| 223 |
+
# splitting on , is actually wrong. For example, this is legal:
|
| 224 |
+
#
|
| 225 |
+
# Transfer-Encoding: foo; options="1,2", chunked
|
| 226 |
+
#
|
| 227 |
+
# and should be parsed as
|
| 228 |
+
#
|
| 229 |
+
# foo; options="1,2"
|
| 230 |
+
# chunked
|
| 231 |
+
#
|
| 232 |
+
# but this naive function will parse it as
|
| 233 |
+
#
|
| 234 |
+
# foo; options="1
|
| 235 |
+
# 2"
|
| 236 |
+
# chunked
|
| 237 |
+
#
|
| 238 |
+
# However, this is okay because the only thing we are going to do with
|
| 239 |
+
# any Transfer-Encoding is reject ones that aren't just "chunked", so
|
| 240 |
+
# both of these will be treated the same anyway.
|
| 241 |
+
#
|
| 242 |
+
# Expect: the only legal value is the literal string
|
| 243 |
+
# "100-continue". Splitting on commas is harmless. Case insensitive.
|
| 244 |
+
#
|
| 245 |
+
out: List[bytes] = []
|
| 246 |
+
for _, found_name, found_raw_value in headers._full_items:
|
| 247 |
+
if found_name == name:
|
| 248 |
+
found_raw_value = found_raw_value.lower()
|
| 249 |
+
for found_split_value in found_raw_value.split(b","):
|
| 250 |
+
found_split_value = found_split_value.strip()
|
| 251 |
+
if found_split_value:
|
| 252 |
+
out.append(found_split_value)
|
| 253 |
+
return out
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers:
|
| 257 |
+
# The header name `name` is expected to be lower-case bytes.
|
| 258 |
+
#
|
| 259 |
+
# Note that when we store the header we use title casing for the header
|
| 260 |
+
# names, in order to match the conventional HTTP header style.
|
| 261 |
+
#
|
| 262 |
+
# Simply calling `.title()` is a blunt approach, but it's correct
|
| 263 |
+
# here given the cases where we're using `set_comma_header`...
|
| 264 |
+
#
|
| 265 |
+
# Connection, Content-Length, Transfer-Encoding.
|
| 266 |
+
new_headers: List[Tuple[bytes, bytes]] = []
|
| 267 |
+
for found_raw_name, found_name, found_raw_value in headers._full_items:
|
| 268 |
+
if found_name != name:
|
| 269 |
+
new_headers.append((found_raw_name, found_raw_value))
|
| 270 |
+
for new_value in new_values:
|
| 271 |
+
new_headers.append((name.title(), new_value))
|
| 272 |
+
return normalize_and_validate(new_headers)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def has_expect_100_continue(request: "Request") -> bool:
|
| 276 |
+
# https://tools.ietf.org/html/rfc7231#section-5.1.1
|
| 277 |
+
# "A server that receives a 100-continue expectation in an HTTP/1.0 request
|
| 278 |
+
# MUST ignore that expectation."
|
| 279 |
+
if request.http_version < b"1.1":
|
| 280 |
+
return False
|
| 281 |
+
expect = get_comma_header(request.headers, b"expect")
|
| 282 |
+
return b"100-continue" in expect
|