codekingpro commited on
Commit
5debfc5
·
verified ·
1 Parent(s): 027078c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. python/Lib/site-packages/annotated_doc-0.0.4.dist-info/INSTALLER +1 -0
  2. python/Lib/site-packages/annotated_doc-0.0.4.dist-info/METADATA +145 -0
  3. python/Lib/site-packages/annotated_doc-0.0.4.dist-info/RECORD +11 -0
  4. python/Lib/site-packages/annotated_doc-0.0.4.dist-info/WHEEL +4 -0
  5. python/Lib/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txt +4 -0
  6. python/Lib/site-packages/annotated_doc/__init__.py +3 -0
  7. python/Lib/site-packages/annotated_doc/main.py +36 -0
  8. python/Lib/site-packages/annotated_doc/py.typed +0 -0
  9. python/Lib/site-packages/anyio-4.13.0.dist-info/INSTALLER +1 -0
  10. python/Lib/site-packages/anyio-4.13.0.dist-info/METADATA +105 -0
  11. python/Lib/site-packages/anyio-4.13.0.dist-info/RECORD +92 -0
  12. python/Lib/site-packages/anyio-4.13.0.dist-info/WHEEL +5 -0
  13. python/Lib/site-packages/anyio-4.13.0.dist-info/entry_points.txt +2 -0
  14. python/Lib/site-packages/anyio-4.13.0.dist-info/top_level.txt +1 -0
  15. python/Lib/site-packages/anyio/__init__.py +111 -0
  16. python/Lib/site-packages/anyio/from_thread.py +578 -0
  17. python/Lib/site-packages/anyio/functools.py +409 -0
  18. python/Lib/site-packages/anyio/lowlevel.py +196 -0
  19. python/Lib/site-packages/anyio/py.typed +0 -0
  20. python/Lib/site-packages/anyio/pytest_plugin.py +363 -0
  21. python/Lib/site-packages/anyio/to_interpreter.py +246 -0
  22. python/Lib/site-packages/anyio/to_process.py +266 -0
  23. python/Lib/site-packages/anyio/to_thread.py +78 -0
  24. python/Lib/site-packages/certifi-2026.4.22.dist-info/INSTALLER +1 -0
  25. python/Lib/site-packages/certifi-2026.4.22.dist-info/METADATA +78 -0
  26. python/Lib/site-packages/certifi-2026.4.22.dist-info/RECORD +14 -0
  27. python/Lib/site-packages/certifi-2026.4.22.dist-info/WHEEL +5 -0
  28. python/Lib/site-packages/certifi-2026.4.22.dist-info/top_level.txt +1 -0
  29. python/Lib/site-packages/certifi/__init__.py +4 -0
  30. python/Lib/site-packages/certifi/__main__.py +12 -0
  31. python/Lib/site-packages/certifi/cacert.pem +0 -0
  32. python/Lib/site-packages/certifi/core.py +83 -0
  33. python/Lib/site-packages/certifi/py.typed +0 -0
  34. python/Lib/site-packages/click-8.3.3.dist-info/INSTALLER +1 -0
  35. python/Lib/site-packages/click-8.3.3.dist-info/METADATA +84 -0
  36. python/Lib/site-packages/click-8.3.3.dist-info/RECORD +40 -0
  37. python/Lib/site-packages/click-8.3.3.dist-info/WHEEL +4 -0
  38. python/Lib/site-packages/click/__init__.py +124 -0
  39. python/Lib/site-packages/click/_compat.py +622 -0
  40. python/Lib/site-packages/click/_termui_impl.py +870 -0
  41. python/Lib/site-packages/click/_textwrap.py +51 -0
  42. python/Lib/site-packages/click/_utils.py +36 -0
  43. python/Lib/site-packages/click/_winconsole.py +296 -0
  44. python/Lib/site-packages/click/core.py +0 -0
  45. python/Lib/site-packages/click/decorators.py +551 -0
  46. python/Lib/site-packages/click/exceptions.py +308 -0
  47. python/Lib/site-packages/click/formatting.py +301 -0
  48. python/Lib/site-packages/click/globals.py +67 -0
  49. python/Lib/site-packages/click/parser.py +532 -0
  50. python/Lib/site-packages/click/py.typed +0 -0
python/Lib/site-packages/annotated_doc-0.0.4.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python/Lib/site-packages/annotated_doc-0.0.4.dist-info/METADATA ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: annotated-doc
3
+ Version: 0.0.4
4
+ Summary: Document parameters, class attributes, return types, and variables inline, with Annotated.
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 :: Internet
14
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
15
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Topic :: Software Development
18
+ Classifier: Typing :: Typed
19
+ Classifier: Development Status :: 4 - Beta
20
+ Classifier: Intended Audience :: Developers
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Programming Language :: Python :: 3.10
25
+ Classifier: Programming Language :: Python :: 3.11
26
+ Classifier: Programming Language :: Python :: 3.12
27
+ Classifier: Programming Language :: Python :: 3.13
28
+ Classifier: Programming Language :: Python :: 3.14
29
+ Project-URL: Homepage, https://github.com/fastapi/annotated-doc
30
+ Project-URL: Documentation, https://github.com/fastapi/annotated-doc
31
+ Project-URL: Repository, https://github.com/fastapi/annotated-doc
32
+ Project-URL: Issues, https://github.com/fastapi/annotated-doc/issues
33
+ Project-URL: Changelog, https://github.com/fastapi/annotated-doc/release-notes.md
34
+ Requires-Python: >=3.8
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Annotated Doc
38
+
39
+ Document parameters, class attributes, return types, and variables inline, with `Annotated`.
40
+
41
+ <a href="https://github.com/fastapi/annotated-doc/actions?query=workflow%3ATest+event%3Apush+branch%3Amain" target="_blank">
42
+ <img src="https://github.com/fastapi/annotated-doc/actions/workflows/test.yml/badge.svg?event=push&branch=main" alt="Test">
43
+ </a>
44
+ <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/annotated-doc" target="_blank">
45
+ <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/annotated-doc.svg" alt="Coverage">
46
+ </a>
47
+ <a href="https://pypi.org/project/annotated-doc" target="_blank">
48
+ <img src="https://img.shields.io/pypi/v/annotated-doc?color=%2334D058&label=pypi%20package" alt="Package version">
49
+ </a>
50
+ <a href="https://pypi.org/project/annotated-doc" target="_blank">
51
+ <img src="https://img.shields.io/pypi/pyversions/annotated-doc.svg?color=%2334D058" alt="Supported Python versions">
52
+ </a>
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pip install annotated-doc
58
+ ```
59
+
60
+ Or with `uv`:
61
+
62
+ ```Python
63
+ uv add annotated-doc
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ Import `Doc` and pass a single literal string with the documentation for the specific parameter, class attribute, return type, or variable.
69
+
70
+ For example, to document a parameter `name` in a function `hi` you could do:
71
+
72
+ ```Python
73
+ from typing import Annotated
74
+
75
+ from annotated_doc import Doc
76
+
77
+ def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None:
78
+ print(f"Hi, {name}!")
79
+ ```
80
+
81
+ You can also use it to document class attributes:
82
+
83
+ ```Python
84
+ from typing import Annotated
85
+
86
+ from annotated_doc import Doc
87
+
88
+ class User:
89
+ name: Annotated[str, Doc("The user's name")]
90
+ age: Annotated[int, Doc("The user's age")]
91
+ ```
92
+
93
+ The same way, you could document return types and variables, or anything that could have a type annotation with `Annotated`.
94
+
95
+ ## Who Uses This
96
+
97
+ `annotated-doc` was made for:
98
+
99
+ * [FastAPI](https://fastapi.tiangolo.com/)
100
+ * [Typer](https://typer.tiangolo.com/)
101
+ * [SQLModel](https://sqlmodel.tiangolo.com/)
102
+ * [Asyncer](https://asyncer.tiangolo.com/)
103
+
104
+ `annotated-doc` is supported by [griffe-typingdoc](https://github.com/mkdocstrings/griffe-typingdoc), which powers reference documentation like the one in the [FastAPI Reference](https://fastapi.tiangolo.com/reference/).
105
+
106
+ ## Reasons not to use `annotated-doc`
107
+
108
+ You are already comfortable with one of the existing docstring formats, like:
109
+
110
+ * Sphinx
111
+ * numpydoc
112
+ * Google
113
+ * Keras
114
+
115
+ Your team is already comfortable using them.
116
+
117
+ You prefer having the documentation about parameters all together in a docstring, separated from the code defining them.
118
+
119
+ You care about a specific set of users, using one specific editor, and that editor already has support for the specific docstring format you use.
120
+
121
+ ## Reasons to use `annotated-doc`
122
+
123
+ * No micro-syntax to learn for newcomers, it’s **just Python** syntax.
124
+ * **Editing** would be already fully supported by default by any editor (current or future) supporting Python syntax, including syntax errors, syntax highlighting, etc.
125
+ * **Rendering** would be relatively straightforward to implement by static tools (tools that don't need runtime execution), as the information can be extracted from the AST they normally already create.
126
+ * **Deduplication of information**: the name of a parameter would be defined in a single place, not duplicated inside of a docstring.
127
+ * **Elimination** of the possibility of having **inconsistencies** when removing a parameter or class variable and **forgetting to remove** its documentation.
128
+ * **Minimization** of the probability of adding a new parameter or class variable and **forgetting to add its documentation**.
129
+ * **Elimination** of the possibility of having **inconsistencies** between the **name** of a parameter in the **signature** and the name in the docstring when it is renamed.
130
+ * **Access** to the documentation string for each symbol at **runtime**, including existing (older) Python versions.
131
+ * A more formalized way to document other symbols, like type aliases, that could use Annotated.
132
+ * **Support** for apps using FastAPI, Typer and others.
133
+ * **AI Accessibility**: AI tools will have an easier way understanding each parameter as the distance from documentation to parameter is much closer.
134
+
135
+ ## History
136
+
137
+ I ([@tiangolo](https://github.com/tiangolo)) originally wanted for this to be part of the Python standard library (in [PEP 727](https://peps.python.org/pep-0727/)), but the proposal was withdrawn as there was a fair amount of negative feedback and opposition.
138
+
139
+ The conclusion was that this was better done as an external effort, in a third-party library.
140
+
141
+ So, here it is, with a simpler approach, as a third-party library, in a way that can be used by others, starting with FastAPI and friends.
142
+
143
+ ## License
144
+
145
+ This project is licensed under the terms of the MIT license.
python/Lib/site-packages/annotated_doc-0.0.4.dist-info/RECORD ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ annotated_doc-0.0.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ annotated_doc-0.0.4.dist-info/METADATA,sha256=Irm5KJua33dY2qKKAjJ-OhKaVBVIfwFGej_dSe3Z1TU,6566
3
+ annotated_doc-0.0.4.dist-info/RECORD,,
4
+ annotated_doc-0.0.4.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90
5
+ annotated_doc-0.0.4.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
6
+ annotated_doc-0.0.4.dist-info/licenses/LICENSE,sha256=__Fwd5pqy_ZavbQFwIfxzuF4ZpHkqWpANFF-SlBKDN8,1086
7
+ annotated_doc/__init__.py,sha256=VuyxxUe80kfEyWnOrCx_Bk8hybo3aKo6RYBlkBBYW8k,52
8
+ annotated_doc/__pycache__/__init__.cpython-313.pyc,,
9
+ annotated_doc/__pycache__/main.cpython-313.pyc,,
10
+ annotated_doc/main.py,sha256=5Zfvxv80SwwLqpRW73AZyZyiM4bWma9QWRbp_cgD20s,1075
11
+ annotated_doc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
python/Lib/site-packages/annotated_doc-0.0.4.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.5)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
python/Lib/site-packages/annotated_doc-0.0.4.dist-info/entry_points.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [console_scripts]
2
+
3
+ [gui_scripts]
4
+
python/Lib/site-packages/annotated_doc/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .main import Doc as Doc
2
+
3
+ __version__ = "0.0.4"
python/Lib/site-packages/annotated_doc/main.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Doc:
2
+ """Define the documentation of a type annotation using `Annotated`, to be
3
+ used in class attributes, function and method parameters, return values,
4
+ and variables.
5
+
6
+ The value should be a positional-only string literal to allow static tools
7
+ like editors and documentation generators to use it.
8
+
9
+ This complements docstrings.
10
+
11
+ The string value passed is available in the attribute `documentation`.
12
+
13
+ Example:
14
+
15
+ ```Python
16
+ from typing import Annotated
17
+ from annotated_doc import Doc
18
+
19
+ def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None:
20
+ print(f"Hi, {name}!")
21
+ ```
22
+ """
23
+
24
+ def __init__(self, documentation: str, /) -> None:
25
+ self.documentation = documentation
26
+
27
+ def __repr__(self) -> str:
28
+ return f"Doc({self.documentation!r})"
29
+
30
+ def __hash__(self) -> int:
31
+ return hash(self.documentation)
32
+
33
+ def __eq__(self, other: object) -> bool:
34
+ if not isinstance(other, Doc):
35
+ return NotImplemented
36
+ return self.documentation == other.documentation
python/Lib/site-packages/annotated_doc/py.typed ADDED
File without changes
python/Lib/site-packages/anyio-4.13.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python/Lib/site-packages/anyio-4.13.0.dist-info/METADATA ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: anyio
3
+ Version: 4.13.0
4
+ Summary: High-level concurrency and networking framework on top of asyncio or Trio
5
+ Author-email: Alex Grönholm <alex.gronholm@nextday.fi>
6
+ License-Expression: MIT
7
+ Project-URL: Documentation, https://anyio.readthedocs.io/en/latest/
8
+ Project-URL: Changelog, https://anyio.readthedocs.io/en/stable/versionhistory.html
9
+ Project-URL: Source code, https://github.com/agronholm/anyio
10
+ Project-URL: Issue tracker, https://github.com/agronholm/anyio/issues
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Framework :: AnyIO
14
+ Classifier: Typing :: Typed
15
+ Classifier: Programming Language :: Python
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/x-rst
24
+ License-File: LICENSE
25
+ Requires-Dist: exceptiongroup>=1.0.2; python_version < "3.11"
26
+ Requires-Dist: idna>=2.8
27
+ Requires-Dist: typing_extensions>=4.5; python_version < "3.13"
28
+ Provides-Extra: trio
29
+ Requires-Dist: trio>=0.32.0; extra == "trio"
30
+ Dynamic: license-file
31
+
32
+ .. image:: https://github.com/agronholm/anyio/actions/workflows/test.yml/badge.svg
33
+ :target: https://github.com/agronholm/anyio/actions/workflows/test.yml
34
+ :alt: Build Status
35
+ .. image:: https://coveralls.io/repos/github/agronholm/anyio/badge.svg?branch=master
36
+ :target: https://coveralls.io/github/agronholm/anyio?branch=master
37
+ :alt: Code Coverage
38
+ .. image:: https://readthedocs.org/projects/anyio/badge/?version=latest
39
+ :target: https://anyio.readthedocs.io/en/latest/?badge=latest
40
+ :alt: Documentation
41
+ .. image:: https://badges.gitter.im/gitterHQ/gitter.svg
42
+ :target: https://gitter.im/python-trio/AnyIO
43
+ :alt: Gitter chat
44
+ .. image:: https://tidelift.com/badges/package/pypi/anyio
45
+ :target: https://tidelift.com/subscription/pkg/pypi-anyio
46
+ :alt: Tidelift
47
+
48
+ AnyIO is an asynchronous networking and concurrency library that works on top of either asyncio_ or
49
+ Trio_. It implements Trio-like `structured concurrency`_ (SC) on top of asyncio and works in harmony
50
+ with the native SC of Trio itself.
51
+
52
+ Applications and libraries written against AnyIO's API will run unmodified on either asyncio_ or
53
+ Trio_. AnyIO can also be adopted into a library or application incrementally – bit by bit, no full
54
+ refactoring necessary. It will blend in with the native libraries of your chosen backend.
55
+
56
+ To find out why you might want to use AnyIO's APIs instead of asyncio's, you can read about it
57
+ `here <https://anyio.readthedocs.io/en/stable/why.html>`_.
58
+
59
+ Documentation
60
+ -------------
61
+
62
+ View full documentation at: https://anyio.readthedocs.io/
63
+
64
+ Features
65
+ --------
66
+
67
+ AnyIO offers the following functionality:
68
+
69
+ * Task groups (nurseries_ in trio terminology)
70
+ * High-level networking (TCP, UDP and UNIX sockets)
71
+
72
+ * `Happy eyeballs`_ algorithm for TCP connections (more robust than that of asyncio on Python
73
+ 3.8)
74
+ * async/await style UDP sockets (unlike asyncio where you still have to use Transports and
75
+ Protocols)
76
+
77
+ * A versatile API for byte streams and object streams
78
+ * Inter-task synchronization and communication (locks, conditions, events, semaphores, object
79
+ streams)
80
+ * Worker threads
81
+ * Subprocesses
82
+ * Subinterpreter support for code parallelization (on Python 3.13 and later)
83
+ * Asynchronous file I/O (using worker threads)
84
+ * Signal handling
85
+ * Asynchronous version of the functools_ module
86
+
87
+ AnyIO also comes with its own pytest_ plugin which also supports asynchronous fixtures.
88
+ It even works with the popular Hypothesis_ library.
89
+
90
+ .. _asyncio: https://docs.python.org/3/library/asyncio.html
91
+ .. _Trio: https://github.com/python-trio/trio
92
+ .. _structured concurrency: https://en.wikipedia.org/wiki/Structured_concurrency
93
+ .. _nurseries: https://trio.readthedocs.io/en/stable/reference-core.html#nurseries-and-spawning
94
+ .. _Happy eyeballs: https://en.wikipedia.org/wiki/Happy_Eyeballs
95
+ .. _pytest: https://docs.pytest.org/en/latest/
96
+ .. _functools: https://docs.python.org/3/library/functools.html
97
+ .. _Hypothesis: https://hypothesis.works/
98
+
99
+ Security contact information
100
+ ----------------------------
101
+
102
+ To report a security vulnerability, please use the `Tidelift security contact`_.
103
+ Tidelift will coordinate the fix and disclosure.
104
+
105
+ .. _Tidelift security contact: https://tidelift.com/security
python/Lib/site-packages/anyio-4.13.0.dist-info/RECORD ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ anyio-4.13.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ anyio-4.13.0.dist-info/METADATA,sha256=F0EYfiPlmTRwmJN2JktNxJg1GNnl0wHhzOWmz7pFvjM,4513
3
+ anyio-4.13.0.dist-info/RECORD,,
4
+ anyio-4.13.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
+ anyio-4.13.0.dist-info/entry_points.txt,sha256=_d6Yu6uiaZmNe0CydowirE9Cmg7zUL2g08tQpoS3Qvc,39
6
+ anyio-4.13.0.dist-info/licenses/LICENSE,sha256=U2GsncWPLvX9LpsJxoKXwX8ElQkJu8gCO9uC6s8iwrA,1081
7
+ anyio-4.13.0.dist-info/top_level.txt,sha256=QglSMiWX8_5dpoVAEIHdEYzvqFMdSYWmCj6tYw2ITkQ,6
8
+ anyio/__init__.py,sha256=7iDVqMUprUuKNY91FuoKqayAhR-OY136YDPI6P78HHk,6170
9
+ anyio/__pycache__/__init__.cpython-313.pyc,,
10
+ anyio/__pycache__/from_thread.cpython-313.pyc,,
11
+ anyio/__pycache__/functools.cpython-313.pyc,,
12
+ anyio/__pycache__/lowlevel.cpython-313.pyc,,
13
+ anyio/__pycache__/pytest_plugin.cpython-313.pyc,,
14
+ anyio/__pycache__/to_interpreter.cpython-313.pyc,,
15
+ anyio/__pycache__/to_process.cpython-313.pyc,,
16
+ anyio/__pycache__/to_thread.cpython-313.pyc,,
17
+ anyio/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ anyio/_backends/__pycache__/__init__.cpython-313.pyc,,
19
+ anyio/_backends/__pycache__/_asyncio.cpython-313.pyc,,
20
+ anyio/_backends/__pycache__/_trio.cpython-313.pyc,,
21
+ anyio/_backends/_asyncio.py,sha256=kuqlg2sBUsFdgY80xSDAw60Gx_4WNCl9iSL5XlY6lCU,99476
22
+ anyio/_backends/_trio.py,sha256=l9U-TsKRxzmTQxSMvOhn0bNeFn_iRx3Ho30jvR5Bdu0,41366
23
+ anyio/_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ anyio/_core/__pycache__/__init__.cpython-313.pyc,,
25
+ anyio/_core/__pycache__/_asyncio_selector_thread.cpython-313.pyc,,
26
+ anyio/_core/__pycache__/_contextmanagers.cpython-313.pyc,,
27
+ anyio/_core/__pycache__/_eventloop.cpython-313.pyc,,
28
+ anyio/_core/__pycache__/_exceptions.cpython-313.pyc,,
29
+ anyio/_core/__pycache__/_fileio.cpython-313.pyc,,
30
+ anyio/_core/__pycache__/_resources.cpython-313.pyc,,
31
+ anyio/_core/__pycache__/_signals.cpython-313.pyc,,
32
+ anyio/_core/__pycache__/_sockets.cpython-313.pyc,,
33
+ anyio/_core/__pycache__/_streams.cpython-313.pyc,,
34
+ anyio/_core/__pycache__/_subprocesses.cpython-313.pyc,,
35
+ anyio/_core/__pycache__/_synchronization.cpython-313.pyc,,
36
+ anyio/_core/__pycache__/_tasks.cpython-313.pyc,,
37
+ anyio/_core/__pycache__/_tempfile.cpython-313.pyc,,
38
+ anyio/_core/__pycache__/_testing.cpython-313.pyc,,
39
+ anyio/_core/__pycache__/_typedattr.cpython-313.pyc,,
40
+ anyio/_core/_asyncio_selector_thread.py,sha256=2PdxFM3cs02Kp6BSppbvmRT7q7asreTW5FgBxEsflBo,5626
41
+ anyio/_core/_contextmanagers.py,sha256=YInBCabiEeS-UaP_Jdxa1CaFC71ETPW8HZTHIM8Rsc8,7215
42
+ anyio/_core/_eventloop.py,sha256=c2EdcBX-xnKwxPcC4Pjn3_qG9I-x4IWFO2R9RqCGjM4,6448
43
+ anyio/_core/_exceptions.py,sha256=Y3aq-Wxd7Q2HqwSg7nZPvRsHEuGazv_qeet6gqEBdPk,4407
44
+ anyio/_core/_fileio.py,sha256=CKi1gFNiW2G4knWeBE7He7-rptQwgYjDUWfG8DSlvLs,25665
45
+ anyio/_core/_resources.py,sha256=NbmU5O5UX3xEyACnkmYX28Fmwdl-f-ny0tHym26e0w0,435
46
+ anyio/_core/_signals.py,sha256=mjTBB2hTKNPRlU0IhnijeQedpWOGERDiMjSlJQsFrug,1016
47
+ anyio/_core/_sockets.py,sha256=RBXHcUqZt5gg_-OOfgHVv8uq2FSKk1uVUzTdpjBoI1o,34977
48
+ anyio/_core/_streams.py,sha256=FczFwIgDpnkK0bODWJXMpsUJYdvAD04kaUaGzJU8DK0,1806
49
+ anyio/_core/_subprocesses.py,sha256=tkmkPKEkEaiMD8C9WRZBlmgjOYRDRbZdte6e-unay2E,7916
50
+ anyio/_core/_synchronization.py,sha256=9G3fvRsPNrrWJ_Z6gD_80wXq8I8qgAyhwM8PvHQnT2c,21061
51
+ anyio/_core/_tasks.py,sha256=pVB7K6AAulzUM8YgXAeqNZG44nSyZ1bYJjH8GznC00I,5435
52
+ anyio/_core/_tempfile.py,sha256=jE2w59FRF3yRo4vjkjfZF2YcqsBZvc66VWRwrJGDYGk,19624
53
+ anyio/_core/_testing.py,sha256=u7MPqGXwpTxqI7hclSdNA30z2GH1Nw258uwKvy_RfBg,2340
54
+ anyio/_core/_typedattr.py,sha256=P4ozZikn3-DbpoYcvyghS_FOYAgbmUxeoU8-L_07pZM,2508
55
+ anyio/abc/__init__.py,sha256=6mWhcl_pGXhrgZVHP_TCfMvIXIOp9mroEFM90fYCU_U,2869
56
+ anyio/abc/__pycache__/__init__.cpython-313.pyc,,
57
+ anyio/abc/__pycache__/_eventloop.cpython-313.pyc,,
58
+ anyio/abc/__pycache__/_resources.cpython-313.pyc,,
59
+ anyio/abc/__pycache__/_sockets.cpython-313.pyc,,
60
+ anyio/abc/__pycache__/_streams.cpython-313.pyc,,
61
+ anyio/abc/__pycache__/_subprocesses.cpython-313.pyc,,
62
+ anyio/abc/__pycache__/_tasks.cpython-313.pyc,,
63
+ anyio/abc/__pycache__/_testing.cpython-313.pyc,,
64
+ anyio/abc/_eventloop.py,sha256=39lYnmtvoHaZw22sWBKOTA_zv7bamOnr8O49PqgDXdw,10629
65
+ anyio/abc/_resources.py,sha256=DrYvkNN1hH6Uvv5_5uKySvDsnknGVDe8FCKfko0VtN8,783
66
+ anyio/abc/_sockets.py,sha256=OmVDrfemVvF9c5K1tpBgQyV6fn5v0XyCExLAqBOGz9o,13124
67
+ anyio/abc/_streams.py,sha256=HYvna1iZbWcwLROTO6IhLX79RTRLPShZMWe0sG1q54I,7481
68
+ anyio/abc/_subprocesses.py,sha256=cumAPJTktOQtw63IqG0lDpyZqu_l1EElvQHMiwJgL08,2067
69
+ anyio/abc/_tasks.py,sha256=KC7wrciE48AINOI-AhPutnFhe1ewfP7QnamFlDzqesQ,3721
70
+ anyio/abc/_testing.py,sha256=tBJUzkSfOXJw23fe8qSJ03kJlShOYjjaEyFB6k6MYT8,1821
71
+ anyio/from_thread.py,sha256=L-0w1HxJ6BSb-KuVi57k5Tkc3yzQrx3QK5tAxMPcY-0,19141
72
+ anyio/functools.py,sha256=5AWM1iYTKkTzptvUhQDdLSh5GvbBW-vcs-SAUfIfA9A,12076
73
+ anyio/lowlevel.py,sha256=AyKLVK3LaWSoK39LkCKxE4_GDMLKZBNqTrLUgk63y80,5158
74
+ anyio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
75
+ anyio/pytest_plugin.py,sha256=t6h4KJstqIxfxwTZ1YO8vpUVuB99nfCLltn0NHfatHo,12775
76
+ anyio/streams/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
77
+ anyio/streams/__pycache__/__init__.cpython-313.pyc,,
78
+ anyio/streams/__pycache__/buffered.cpython-313.pyc,,
79
+ anyio/streams/__pycache__/file.cpython-313.pyc,,
80
+ anyio/streams/__pycache__/memory.cpython-313.pyc,,
81
+ anyio/streams/__pycache__/stapled.cpython-313.pyc,,
82
+ anyio/streams/__pycache__/text.cpython-313.pyc,,
83
+ anyio/streams/__pycache__/tls.cpython-313.pyc,,
84
+ anyio/streams/buffered.py,sha256=2R3PeJhe4EXrdYqz44Y6-Eg9R6DrmlsYrP36Ir43-po,6263
85
+ anyio/streams/file.py,sha256=msnrotVKGMQomUu_Rj2qz9MvIdUp6d3JGr7MOEO8kV4,4428
86
+ anyio/streams/memory.py,sha256=F0zwzvFJKAhX_LRZGoKzzqDC2oMM-f-yyTBrEYEGOaU,10740
87
+ anyio/streams/stapled.py,sha256=T8Xqwf8K6EgURPxbt1N4i7A8BAk-gScv-GRhjLXIf_o,4390
88
+ anyio/streams/text.py,sha256=BcVAGJw1VRvtIqnv-o0Rb0pwH7p8vwlvl21xHq522ag,5765
89
+ anyio/streams/tls.py,sha256=DQVkXUvsTEYKkBO8dlVU7j_5H8QOtLy4sGi1Wrjqevo,15303
90
+ anyio/to_interpreter.py,sha256=_mLngrMy97TMR6VbW4Y6YzDUk9ZuPcQMPlkuyRh3C9k,7100
91
+ anyio/to_process.py,sha256=J7gAA_YOuoHqnpDAf5fm1Qu6kOmTzdFbiDNvnV755vk,9798
92
+ anyio/to_thread.py,sha256=f6h_k2d743GBv9FhAnhM_YpTvWgIrzBy9cOE0eJ1UJw,2693
python/Lib/site-packages/anyio-4.13.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
python/Lib/site-packages/anyio-4.13.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [pytest11]
2
+ anyio = anyio.pytest_plugin
python/Lib/site-packages/anyio-4.13.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ anyio
python/Lib/site-packages/anyio/__init__.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ._core._contextmanagers import AsyncContextManagerMixin as AsyncContextManagerMixin
4
+ from ._core._contextmanagers import ContextManagerMixin as ContextManagerMixin
5
+ from ._core._eventloop import current_time as current_time
6
+ from ._core._eventloop import get_all_backends as get_all_backends
7
+ from ._core._eventloop import get_available_backends as get_available_backends
8
+ from ._core._eventloop import get_cancelled_exc_class as get_cancelled_exc_class
9
+ from ._core._eventloop import run as run
10
+ from ._core._eventloop import sleep as sleep
11
+ from ._core._eventloop import sleep_forever as sleep_forever
12
+ from ._core._eventloop import sleep_until as sleep_until
13
+ from ._core._exceptions import BrokenResourceError as BrokenResourceError
14
+ from ._core._exceptions import BrokenWorkerInterpreter as BrokenWorkerInterpreter
15
+ from ._core._exceptions import BrokenWorkerProcess as BrokenWorkerProcess
16
+ from ._core._exceptions import BusyResourceError as BusyResourceError
17
+ from ._core._exceptions import ClosedResourceError as ClosedResourceError
18
+ from ._core._exceptions import ConnectionFailed as ConnectionFailed
19
+ from ._core._exceptions import DelimiterNotFound as DelimiterNotFound
20
+ from ._core._exceptions import EndOfStream as EndOfStream
21
+ from ._core._exceptions import IncompleteRead as IncompleteRead
22
+ from ._core._exceptions import NoEventLoopError as NoEventLoopError
23
+ from ._core._exceptions import RunFinishedError as RunFinishedError
24
+ from ._core._exceptions import TypedAttributeLookupError as TypedAttributeLookupError
25
+ from ._core._exceptions import WouldBlock as WouldBlock
26
+ from ._core._fileio import AsyncFile as AsyncFile
27
+ from ._core._fileio import Path as Path
28
+ from ._core._fileio import open_file as open_file
29
+ from ._core._fileio import wrap_file as wrap_file
30
+ from ._core._resources import aclose_forcefully as aclose_forcefully
31
+ from ._core._signals import open_signal_receiver as open_signal_receiver
32
+ from ._core._sockets import TCPConnectable as TCPConnectable
33
+ from ._core._sockets import UNIXConnectable as UNIXConnectable
34
+ from ._core._sockets import as_connectable as as_connectable
35
+ from ._core._sockets import connect_tcp as connect_tcp
36
+ from ._core._sockets import connect_unix as connect_unix
37
+ from ._core._sockets import create_connected_udp_socket as create_connected_udp_socket
38
+ from ._core._sockets import (
39
+ create_connected_unix_datagram_socket as create_connected_unix_datagram_socket,
40
+ )
41
+ from ._core._sockets import create_tcp_listener as create_tcp_listener
42
+ from ._core._sockets import create_udp_socket as create_udp_socket
43
+ from ._core._sockets import create_unix_datagram_socket as create_unix_datagram_socket
44
+ from ._core._sockets import create_unix_listener as create_unix_listener
45
+ from ._core._sockets import getaddrinfo as getaddrinfo
46
+ from ._core._sockets import getnameinfo as getnameinfo
47
+ from ._core._sockets import notify_closing as notify_closing
48
+ from ._core._sockets import wait_readable as wait_readable
49
+ from ._core._sockets import wait_socket_readable as wait_socket_readable
50
+ from ._core._sockets import wait_socket_writable as wait_socket_writable
51
+ from ._core._sockets import wait_writable as wait_writable
52
+ from ._core._streams import create_memory_object_stream as create_memory_object_stream
53
+ from ._core._subprocesses import open_process as open_process
54
+ from ._core._subprocesses import run_process as run_process
55
+ from ._core._synchronization import CapacityLimiter as CapacityLimiter
56
+ from ._core._synchronization import (
57
+ CapacityLimiterStatistics as CapacityLimiterStatistics,
58
+ )
59
+ from ._core._synchronization import Condition as Condition
60
+ from ._core._synchronization import ConditionStatistics as ConditionStatistics
61
+ from ._core._synchronization import Event as Event
62
+ from ._core._synchronization import EventStatistics as EventStatistics
63
+ from ._core._synchronization import Lock as Lock
64
+ from ._core._synchronization import LockStatistics as LockStatistics
65
+ from ._core._synchronization import ResourceGuard as ResourceGuard
66
+ from ._core._synchronization import Semaphore as Semaphore
67
+ from ._core._synchronization import SemaphoreStatistics as SemaphoreStatistics
68
+ from ._core._tasks import TASK_STATUS_IGNORED as TASK_STATUS_IGNORED
69
+ from ._core._tasks import CancelScope as CancelScope
70
+ from ._core._tasks import create_task_group as create_task_group
71
+ from ._core._tasks import current_effective_deadline as current_effective_deadline
72
+ from ._core._tasks import fail_after as fail_after
73
+ from ._core._tasks import move_on_after as move_on_after
74
+ from ._core._tempfile import NamedTemporaryFile as NamedTemporaryFile
75
+ from ._core._tempfile import SpooledTemporaryFile as SpooledTemporaryFile
76
+ from ._core._tempfile import TemporaryDirectory as TemporaryDirectory
77
+ from ._core._tempfile import TemporaryFile as TemporaryFile
78
+ from ._core._tempfile import gettempdir as gettempdir
79
+ from ._core._tempfile import gettempdirb as gettempdirb
80
+ from ._core._tempfile import mkdtemp as mkdtemp
81
+ from ._core._tempfile import mkstemp as mkstemp
82
+ from ._core._testing import TaskInfo as TaskInfo
83
+ from ._core._testing import get_current_task as get_current_task
84
+ from ._core._testing import get_running_tasks as get_running_tasks
85
+ from ._core._testing import wait_all_tasks_blocked as wait_all_tasks_blocked
86
+ from ._core._typedattr import TypedAttributeProvider as TypedAttributeProvider
87
+ from ._core._typedattr import TypedAttributeSet as TypedAttributeSet
88
+ from ._core._typedattr import typed_attribute as typed_attribute
89
+
90
+ # Re-export imports so they look like they live directly in this package
91
+ for __value in list(locals().values()):
92
+ if getattr(__value, "__module__", "").startswith("anyio."):
93
+ __value.__module__ = __name__
94
+
95
+
96
+ del __value
97
+
98
+
99
+ def __getattr__(attr: str) -> type[BrokenWorkerInterpreter]:
100
+ """Support deprecated aliases."""
101
+ if attr == "BrokenWorkerIntepreter":
102
+ import warnings
103
+
104
+ warnings.warn(
105
+ "The 'BrokenWorkerIntepreter' alias is deprecated, use 'BrokenWorkerInterpreter' instead.",
106
+ DeprecationWarning,
107
+ stacklevel=2,
108
+ )
109
+ return BrokenWorkerInterpreter
110
+
111
+ raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
python/Lib/site-packages/anyio/from_thread.py ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "BlockingPortal",
5
+ "BlockingPortalProvider",
6
+ "check_cancelled",
7
+ "run",
8
+ "run_sync",
9
+ "start_blocking_portal",
10
+ )
11
+
12
+ import sys
13
+ from collections.abc import Awaitable, Callable, Generator
14
+ from concurrent.futures import Future
15
+ from contextlib import (
16
+ AbstractAsyncContextManager,
17
+ AbstractContextManager,
18
+ contextmanager,
19
+ )
20
+ from dataclasses import dataclass, field
21
+ from functools import partial
22
+ from inspect import isawaitable
23
+ from threading import Lock, Thread, current_thread, get_ident
24
+ from types import TracebackType
25
+ from typing import (
26
+ Any,
27
+ Generic,
28
+ TypeVar,
29
+ cast,
30
+ overload,
31
+ )
32
+
33
+ from ._core._eventloop import (
34
+ get_cancelled_exc_class,
35
+ threadlocals,
36
+ )
37
+ from ._core._eventloop import run as run_eventloop
38
+ from ._core._exceptions import NoEventLoopError
39
+ from ._core._synchronization import Event
40
+ from ._core._tasks import CancelScope, create_task_group
41
+ from .abc._tasks import TaskStatus
42
+ from .lowlevel import EventLoopToken, current_token
43
+
44
+ if sys.version_info >= (3, 11):
45
+ from typing import TypeVarTuple, Unpack
46
+ else:
47
+ from typing_extensions import TypeVarTuple, Unpack
48
+
49
+ T_Retval = TypeVar("T_Retval")
50
+ T_co = TypeVar("T_co", covariant=True)
51
+ PosArgsT = TypeVarTuple("PosArgsT")
52
+
53
+
54
+ def _token_or_error(token: EventLoopToken | None) -> EventLoopToken:
55
+ if token is not None:
56
+ return token
57
+
58
+ try:
59
+ return threadlocals.current_token
60
+ except AttributeError:
61
+ raise NoEventLoopError(
62
+ "Not running inside an AnyIO worker thread, and no event loop token was "
63
+ "provided"
64
+ ) from None
65
+
66
+
67
+ def run(
68
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
69
+ *args: Unpack[PosArgsT],
70
+ token: EventLoopToken | None = None,
71
+ ) -> T_Retval:
72
+ """
73
+ Call a coroutine function from a worker thread.
74
+
75
+ :param func: a coroutine function
76
+ :param args: positional arguments for the callable
77
+ :param token: an event loop token to use to get back to the event loop thread
78
+ (required if calling this function from outside an AnyIO worker thread)
79
+ :return: the return value of the coroutine function
80
+ :raises MissingTokenError: if no token was provided and called from outside an
81
+ AnyIO worker thread
82
+ :raises RunFinishedError: if the event loop tied to ``token`` is no longer running
83
+
84
+ .. versionchanged:: 4.11.0
85
+ Added the ``token`` parameter.
86
+
87
+ """
88
+ explicit_token = token is not None
89
+ token = _token_or_error(token)
90
+ return token.backend_class.run_async_from_thread(
91
+ func, args, token=token.native_token if explicit_token else None
92
+ )
93
+
94
+
95
+ def run_sync(
96
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
97
+ *args: Unpack[PosArgsT],
98
+ token: EventLoopToken | None = None,
99
+ ) -> T_Retval:
100
+ """
101
+ Call a function in the event loop thread from a worker thread.
102
+
103
+ :param func: a callable
104
+ :param args: positional arguments for the callable
105
+ :param token: an event loop token to use to get back to the event loop thread
106
+ (required if calling this function from outside an AnyIO worker thread)
107
+ :return: the return value of the callable
108
+ :raises MissingTokenError: if no token was provided and called from outside an
109
+ AnyIO worker thread
110
+ :raises RunFinishedError: if the event loop tied to ``token`` is no longer running
111
+
112
+ .. versionchanged:: 4.11.0
113
+ Added the ``token`` parameter.
114
+
115
+ """
116
+ explicit_token = token is not None
117
+ token = _token_or_error(token)
118
+ return token.backend_class.run_sync_from_thread(
119
+ func, args, token=token.native_token if explicit_token else None
120
+ )
121
+
122
+
123
+ class _BlockingAsyncContextManager(Generic[T_co], AbstractContextManager):
124
+ _enter_future: Future[T_co]
125
+ _exit_future: Future[bool | None]
126
+ _exit_event: Event
127
+ _exit_exc_info: tuple[
128
+ type[BaseException] | None, BaseException | None, TracebackType | None
129
+ ] = (None, None, None)
130
+
131
+ def __init__(
132
+ self, async_cm: AbstractAsyncContextManager[T_co], portal: BlockingPortal
133
+ ):
134
+ self._async_cm = async_cm
135
+ self._portal = portal
136
+
137
+ async def run_async_cm(self) -> bool | None:
138
+ try:
139
+ self._exit_event = Event()
140
+ value = await self._async_cm.__aenter__()
141
+ except BaseException as exc:
142
+ self._enter_future.set_exception(exc)
143
+ raise
144
+ else:
145
+ self._enter_future.set_result(value)
146
+
147
+ try:
148
+ # Wait for the sync context manager to exit.
149
+ # This next statement can raise `get_cancelled_exc_class()` if
150
+ # something went wrong in a task group in this async context
151
+ # manager.
152
+ await self._exit_event.wait()
153
+ finally:
154
+ # In case of cancellation, it could be that we end up here before
155
+ # `_BlockingAsyncContextManager.__exit__` is called, and an
156
+ # `_exit_exc_info` has been set.
157
+ result = await self._async_cm.__aexit__(*self._exit_exc_info)
158
+
159
+ return result
160
+
161
+ def __enter__(self) -> T_co:
162
+ self._enter_future = Future()
163
+ self._exit_future = self._portal.start_task_soon(self.run_async_cm)
164
+ return self._enter_future.result()
165
+
166
+ def __exit__(
167
+ self,
168
+ __exc_type: type[BaseException] | None,
169
+ __exc_value: BaseException | None,
170
+ __traceback: TracebackType | None,
171
+ ) -> bool | None:
172
+ self._exit_exc_info = __exc_type, __exc_value, __traceback
173
+ self._portal.call(self._exit_event.set)
174
+ return self._exit_future.result()
175
+
176
+
177
+ class _BlockingPortalTaskStatus(TaskStatus):
178
+ def __init__(self, future: Future):
179
+ self._future = future
180
+
181
+ def started(self, value: object = None) -> None:
182
+ self._future.set_result(value)
183
+
184
+
185
+ class BlockingPortal:
186
+ """
187
+ An object that lets external threads run code in an asynchronous event loop.
188
+
189
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
190
+ current thread
191
+ """
192
+
193
+ def __init__(self) -> None:
194
+ self._token = current_token()
195
+ self._event_loop_thread_id: int | None = get_ident()
196
+ self._stop_event = Event()
197
+ self._task_group = create_task_group()
198
+
199
+ async def __aenter__(self) -> BlockingPortal:
200
+ await self._task_group.__aenter__()
201
+ return self
202
+
203
+ async def __aexit__(
204
+ self,
205
+ exc_type: type[BaseException] | None,
206
+ exc_val: BaseException | None,
207
+ exc_tb: TracebackType | None,
208
+ ) -> bool:
209
+ await self.stop()
210
+ return await self._task_group.__aexit__(exc_type, exc_val, exc_tb)
211
+
212
+ def _check_running(self) -> None:
213
+ if self._event_loop_thread_id is None:
214
+ raise RuntimeError("This portal is not running")
215
+ if self._event_loop_thread_id == get_ident():
216
+ raise RuntimeError(
217
+ "This method cannot be called from the event loop thread"
218
+ )
219
+
220
+ async def sleep_until_stopped(self) -> None:
221
+ """Sleep until :meth:`stop` is called."""
222
+ await self._stop_event.wait()
223
+
224
+ async def stop(self, cancel_remaining: bool = False) -> None:
225
+ """
226
+ Signal the portal to shut down.
227
+
228
+ This marks the portal as no longer accepting new calls and exits from
229
+ :meth:`sleep_until_stopped`.
230
+
231
+ :param cancel_remaining: ``True`` to cancel all the remaining tasks, ``False``
232
+ to let them finish before returning
233
+
234
+ """
235
+ self._event_loop_thread_id = None
236
+ self._stop_event.set()
237
+ if cancel_remaining:
238
+ self._task_group.cancel_scope.cancel("the blocking portal is shutting down")
239
+
240
+ async def _call_func(
241
+ self,
242
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
243
+ args: tuple[Unpack[PosArgsT]],
244
+ kwargs: dict[str, Any],
245
+ future: Future[T_Retval],
246
+ ) -> None:
247
+ def callback(f: Future[T_Retval]) -> None:
248
+ if f.cancelled():
249
+ if self._event_loop_thread_id == get_ident():
250
+ scope.cancel("the future was cancelled")
251
+ elif self._event_loop_thread_id is not None:
252
+ self.call(scope.cancel, "the future was cancelled")
253
+
254
+ try:
255
+ retval_or_awaitable = func(*args, **kwargs)
256
+ if isawaitable(retval_or_awaitable):
257
+ with CancelScope() as scope:
258
+ future.add_done_callback(callback)
259
+ retval = await retval_or_awaitable
260
+ else:
261
+ retval = retval_or_awaitable
262
+ except get_cancelled_exc_class():
263
+ future.cancel()
264
+ future.set_running_or_notify_cancel()
265
+ except BaseException as exc:
266
+ if not future.cancelled():
267
+ future.set_exception(exc)
268
+
269
+ # Let base exceptions fall through
270
+ if not isinstance(exc, Exception):
271
+ raise
272
+ else:
273
+ if not future.cancelled():
274
+ future.set_result(retval)
275
+ finally:
276
+ scope = None # type: ignore[assignment]
277
+
278
+ def _spawn_task_from_thread(
279
+ self,
280
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
281
+ args: tuple[Unpack[PosArgsT]],
282
+ kwargs: dict[str, Any],
283
+ name: object,
284
+ future: Future[T_Retval],
285
+ ) -> None:
286
+ """
287
+ Spawn a new task using the given callable.
288
+
289
+ :param func: a callable
290
+ :param args: positional arguments to be passed to the callable
291
+ :param kwargs: keyword arguments to be passed to the callable
292
+ :param name: name of the task (will be coerced to a string if not ``None``)
293
+ :param future: a future that will resolve to the return value of the callable,
294
+ or the exception raised during its execution
295
+
296
+ """
297
+ run_sync(
298
+ partial(self._task_group.start_soon, name=name),
299
+ self._call_func,
300
+ func,
301
+ args,
302
+ kwargs,
303
+ future,
304
+ token=self._token,
305
+ )
306
+
307
+ @overload
308
+ def call(
309
+ self,
310
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
311
+ *args: Unpack[PosArgsT],
312
+ ) -> T_Retval: ...
313
+
314
+ @overload
315
+ def call(
316
+ self, func: Callable[[Unpack[PosArgsT]], T_Retval], *args: Unpack[PosArgsT]
317
+ ) -> T_Retval: ...
318
+
319
+ def call(
320
+ self,
321
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
322
+ *args: Unpack[PosArgsT],
323
+ ) -> T_Retval:
324
+ """
325
+ Call the given function in the event loop thread.
326
+
327
+ If the callable returns a coroutine object, it is awaited on.
328
+
329
+ :param func: any callable
330
+ :raises RuntimeError: if the portal is not running or if this method is called
331
+ from within the event loop thread
332
+
333
+ """
334
+ return cast(T_Retval, self.start_task_soon(func, *args).result())
335
+
336
+ @overload
337
+ def start_task_soon(
338
+ self,
339
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval]],
340
+ *args: Unpack[PosArgsT],
341
+ name: object = None,
342
+ ) -> Future[T_Retval]: ...
343
+
344
+ @overload
345
+ def start_task_soon(
346
+ self,
347
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
348
+ *args: Unpack[PosArgsT],
349
+ name: object = None,
350
+ ) -> Future[T_Retval]: ...
351
+
352
+ def start_task_soon(
353
+ self,
354
+ func: Callable[[Unpack[PosArgsT]], Awaitable[T_Retval] | T_Retval],
355
+ *args: Unpack[PosArgsT],
356
+ name: object = None,
357
+ ) -> Future[T_Retval]:
358
+ """
359
+ Start a task in the portal's task group.
360
+
361
+ The task will be run inside a cancel scope which can be cancelled by cancelling
362
+ the returned future.
363
+
364
+ :param func: the target function
365
+ :param args: positional arguments passed to ``func``
366
+ :param name: name of the task (will be coerced to a string if not ``None``)
367
+ :return: a future that resolves with the return value of the callable if the
368
+ task completes successfully, or with the exception raised in the task
369
+ :raises RuntimeError: if the portal is not running or if this method is called
370
+ from within the event loop thread
371
+ :rtype: concurrent.futures.Future[T_Retval]
372
+
373
+ .. versionadded:: 3.0
374
+
375
+ """
376
+ self._check_running()
377
+ f: Future[T_Retval] = Future()
378
+ self._spawn_task_from_thread(func, args, {}, name, f)
379
+ return f
380
+
381
+ def start_task(
382
+ self,
383
+ func: Callable[..., Awaitable[T_Retval]],
384
+ *args: object,
385
+ name: object = None,
386
+ ) -> tuple[Future[T_Retval], Any]:
387
+ """
388
+ Start a task in the portal's task group and wait until it signals for readiness.
389
+
390
+ This method works the same way as :meth:`.abc.TaskGroup.start`.
391
+
392
+ :param func: the target function
393
+ :param args: positional arguments passed to ``func``
394
+ :param name: name of the task (will be coerced to a string if not ``None``)
395
+ :return: a tuple of (future, task_status_value) where the ``task_status_value``
396
+ is the value passed to ``task_status.started()`` from within the target
397
+ function
398
+ :rtype: tuple[concurrent.futures.Future[T_Retval], Any]
399
+
400
+ .. versionadded:: 3.0
401
+
402
+ """
403
+
404
+ def task_done(future: Future[T_Retval]) -> None:
405
+ if not task_status_future.done():
406
+ if future.cancelled():
407
+ task_status_future.cancel()
408
+ elif future.exception():
409
+ task_status_future.set_exception(future.exception())
410
+ else:
411
+ exc = RuntimeError(
412
+ "Task exited without calling task_status.started()"
413
+ )
414
+ task_status_future.set_exception(exc)
415
+
416
+ self._check_running()
417
+ task_status_future: Future = Future()
418
+ task_status = _BlockingPortalTaskStatus(task_status_future)
419
+ f: Future = Future()
420
+ f.add_done_callback(task_done)
421
+ self._spawn_task_from_thread(func, args, {"task_status": task_status}, name, f)
422
+ return f, task_status_future.result()
423
+
424
+ def wrap_async_context_manager(
425
+ self, cm: AbstractAsyncContextManager[T_co]
426
+ ) -> AbstractContextManager[T_co]:
427
+ """
428
+ Wrap an async context manager as a synchronous context manager via this portal.
429
+
430
+ Spawns a task that will call both ``__aenter__()`` and ``__aexit__()``, stopping
431
+ in the middle until the synchronous context manager exits.
432
+
433
+ :param cm: an asynchronous context manager
434
+ :return: a synchronous context manager
435
+
436
+ .. versionadded:: 2.1
437
+
438
+ """
439
+ return _BlockingAsyncContextManager(cm, self)
440
+
441
+
442
+ @dataclass
443
+ class BlockingPortalProvider:
444
+ """
445
+ A manager for a blocking portal. Used as a context manager. The first thread to
446
+ enter this context manager causes a blocking portal to be started with the specific
447
+ parameters, and the last thread to exit causes the portal to be shut down. Thus,
448
+ there will be exactly one blocking portal running in this context as long as at
449
+ least one thread has entered this context manager.
450
+
451
+ The parameters are the same as for :func:`~anyio.run`.
452
+
453
+ :param backend: name of the backend
454
+ :param backend_options: backend options
455
+
456
+ .. versionadded:: 4.4
457
+ """
458
+
459
+ backend: str = "asyncio"
460
+ backend_options: dict[str, Any] | None = None
461
+ _lock: Lock = field(init=False, default_factory=Lock)
462
+ _leases: int = field(init=False, default=0)
463
+ _portal: BlockingPortal = field(init=False)
464
+ _portal_cm: AbstractContextManager[BlockingPortal] | None = field(
465
+ init=False, default=None
466
+ )
467
+
468
+ def __enter__(self) -> BlockingPortal:
469
+ with self._lock:
470
+ if self._portal_cm is None:
471
+ self._portal_cm = start_blocking_portal(
472
+ self.backend, self.backend_options
473
+ )
474
+ self._portal = self._portal_cm.__enter__()
475
+
476
+ self._leases += 1
477
+ return self._portal
478
+
479
+ def __exit__(
480
+ self,
481
+ exc_type: type[BaseException] | None,
482
+ exc_val: BaseException | None,
483
+ exc_tb: TracebackType | None,
484
+ ) -> None:
485
+ portal_cm: AbstractContextManager[BlockingPortal] | None = None
486
+ with self._lock:
487
+ assert self._portal_cm
488
+ assert self._leases > 0
489
+ self._leases -= 1
490
+ if not self._leases:
491
+ portal_cm = self._portal_cm
492
+ self._portal_cm = None
493
+ del self._portal
494
+
495
+ if portal_cm:
496
+ portal_cm.__exit__(None, None, None)
497
+
498
+
499
+ @contextmanager
500
+ def start_blocking_portal(
501
+ backend: str = "asyncio",
502
+ backend_options: dict[str, Any] | None = None,
503
+ *,
504
+ name: str | None = None,
505
+ ) -> Generator[BlockingPortal, Any, None]:
506
+ """
507
+ Start a new event loop in a new thread and run a blocking portal in its main task.
508
+
509
+ The parameters are the same as for :func:`~anyio.run`.
510
+
511
+ :param backend: name of the backend
512
+ :param backend_options: backend options
513
+ :param name: name of the thread
514
+ :return: a context manager that yields a blocking portal
515
+
516
+ .. versionchanged:: 3.0
517
+ Usage as a context manager is now required.
518
+
519
+ """
520
+
521
+ async def run_portal() -> None:
522
+ async with BlockingPortal() as portal_:
523
+ if name is None:
524
+ current_thread().name = f"{backend}-portal-{id(portal_):x}"
525
+
526
+ future.set_result(portal_)
527
+ await portal_.sleep_until_stopped()
528
+
529
+ def run_blocking_portal() -> None:
530
+ if future.set_running_or_notify_cancel():
531
+ try:
532
+ run_eventloop(
533
+ run_portal, backend=backend, backend_options=backend_options
534
+ )
535
+ except BaseException as exc:
536
+ if not future.done():
537
+ future.set_exception(exc)
538
+
539
+ future: Future[BlockingPortal] = Future()
540
+ thread = Thread(target=run_blocking_portal, daemon=True, name=name)
541
+ thread.start()
542
+ try:
543
+ cancel_remaining_tasks = False
544
+ portal = future.result()
545
+ try:
546
+ yield portal
547
+ except BaseException:
548
+ cancel_remaining_tasks = True
549
+ raise
550
+ finally:
551
+ try:
552
+ portal.call(portal.stop, cancel_remaining_tasks)
553
+ except RuntimeError:
554
+ pass
555
+ finally:
556
+ thread.join()
557
+
558
+
559
+ def check_cancelled() -> None:
560
+ """
561
+ Check if the cancel scope of the host task's running the current worker thread has
562
+ been cancelled.
563
+
564
+ If the host task's current cancel scope has indeed been cancelled, the
565
+ backend-specific cancellation exception will be raised.
566
+
567
+ :raises RuntimeError: if the current thread was not spawned by
568
+ :func:`.to_thread.run_sync`
569
+
570
+ """
571
+ try:
572
+ token: EventLoopToken = threadlocals.current_token
573
+ except AttributeError:
574
+ raise NoEventLoopError(
575
+ "This function can only be called inside an AnyIO worker thread"
576
+ ) from None
577
+
578
+ token.backend_class.check_cancelled()
python/Lib/site-packages/anyio/functools.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "AsyncCacheInfo",
5
+ "AsyncCacheParameters",
6
+ "AsyncLRUCacheWrapper",
7
+ "cache",
8
+ "lru_cache",
9
+ "reduce",
10
+ )
11
+
12
+ import functools
13
+ import sys
14
+ from collections import OrderedDict
15
+ from collections.abc import (
16
+ AsyncIterable,
17
+ Awaitable,
18
+ Callable,
19
+ Coroutine,
20
+ Hashable,
21
+ Iterable,
22
+ )
23
+ from functools import update_wrapper
24
+ from inspect import iscoroutinefunction
25
+ from typing import (
26
+ Any,
27
+ Generic,
28
+ NamedTuple,
29
+ TypedDict,
30
+ TypeVar,
31
+ cast,
32
+ final,
33
+ overload,
34
+ )
35
+ from weakref import WeakKeyDictionary
36
+
37
+ from ._core._eventloop import current_time
38
+ from ._core._synchronization import Lock
39
+ from .lowlevel import RunVar, checkpoint
40
+
41
+ if sys.version_info >= (3, 11):
42
+ from typing import ParamSpec
43
+ else:
44
+ from typing_extensions import ParamSpec
45
+
46
+ T = TypeVar("T")
47
+ S = TypeVar("S")
48
+ P = ParamSpec("P")
49
+ lru_cache_items: RunVar[
50
+ WeakKeyDictionary[
51
+ AsyncLRUCacheWrapper[Any, Any],
52
+ OrderedDict[
53
+ Hashable,
54
+ tuple[_InitialMissingType, Lock, float | None]
55
+ | tuple[Any, None, float | None],
56
+ ],
57
+ ]
58
+ ] = RunVar("lru_cache_items")
59
+
60
+
61
+ class _InitialMissingType:
62
+ pass
63
+
64
+
65
+ initial_missing: _InitialMissingType = _InitialMissingType()
66
+
67
+
68
+ class AsyncCacheInfo(NamedTuple):
69
+ hits: int
70
+ misses: int
71
+ maxsize: int | None
72
+ currsize: int
73
+ ttl: int | None
74
+
75
+
76
+ class AsyncCacheParameters(TypedDict):
77
+ maxsize: int | None
78
+ typed: bool
79
+ always_checkpoint: bool
80
+ ttl: int | None
81
+
82
+
83
+ class _LRUMethodWrapper(Generic[T]):
84
+ def __init__(self, wrapper: AsyncLRUCacheWrapper[..., T], instance: object):
85
+ self.__wrapper = wrapper
86
+ self.__instance = instance
87
+
88
+ def cache_info(self) -> AsyncCacheInfo:
89
+ return self.__wrapper.cache_info()
90
+
91
+ def cache_parameters(self) -> AsyncCacheParameters:
92
+ return self.__wrapper.cache_parameters()
93
+
94
+ def cache_clear(self) -> None:
95
+ self.__wrapper.cache_clear()
96
+
97
+ async def __call__(self, *args: Any, **kwargs: Any) -> T:
98
+ if self.__instance is None:
99
+ return await self.__wrapper(*args, **kwargs)
100
+
101
+ return await self.__wrapper(self.__instance, *args, **kwargs)
102
+
103
+
104
+ @final
105
+ class AsyncLRUCacheWrapper(Generic[P, T]):
106
+ def __init__(
107
+ self,
108
+ func: Callable[P, Awaitable[T]],
109
+ maxsize: int | None,
110
+ typed: bool,
111
+ always_checkpoint: bool,
112
+ ttl: int | None,
113
+ ):
114
+ self.__wrapped__ = func
115
+ self._hits: int = 0
116
+ self._misses: int = 0
117
+ self._maxsize = max(maxsize, 0) if maxsize is not None else None
118
+ self._currsize: int = 0
119
+ self._typed = typed
120
+ self._always_checkpoint = always_checkpoint
121
+ self._ttl = ttl
122
+ update_wrapper(self, func)
123
+
124
+ def cache_info(self) -> AsyncCacheInfo:
125
+ return AsyncCacheInfo(
126
+ self._hits, self._misses, self._maxsize, self._currsize, self._ttl
127
+ )
128
+
129
+ def cache_parameters(self) -> AsyncCacheParameters:
130
+ return {
131
+ "maxsize": self._maxsize,
132
+ "typed": self._typed,
133
+ "always_checkpoint": self._always_checkpoint,
134
+ "ttl": self._ttl,
135
+ }
136
+
137
+ def cache_clear(self) -> None:
138
+ if cache := lru_cache_items.get(None):
139
+ cache.pop(self, None)
140
+ self._hits = self._misses = self._currsize = 0
141
+
142
+ async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
143
+ # Easy case first: if maxsize == 0, no caching is done
144
+ if self._maxsize == 0:
145
+ value = await self.__wrapped__(*args, **kwargs)
146
+ self._misses += 1
147
+ return value
148
+
149
+ # The key is constructed as a flat tuple to avoid memory overhead
150
+ key: tuple[Any, ...] = args
151
+ if kwargs:
152
+ # initial_missing is used as a separator
153
+ key += (initial_missing,) + sum(kwargs.items(), ())
154
+
155
+ if self._typed:
156
+ key += tuple(type(arg) for arg in args)
157
+ if kwargs:
158
+ key += (initial_missing,) + tuple(type(val) for val in kwargs.values())
159
+
160
+ try:
161
+ cache = lru_cache_items.get()
162
+ except LookupError:
163
+ cache = WeakKeyDictionary()
164
+ lru_cache_items.set(cache)
165
+
166
+ try:
167
+ cache_entry = cache[self]
168
+ except KeyError:
169
+ cache_entry = cache[self] = OrderedDict()
170
+
171
+ cached_value: T | _InitialMissingType
172
+ try:
173
+ cached_value, lock, expires_at = cache_entry[key]
174
+ except KeyError:
175
+ # We're the first task to call this function
176
+ cached_value, lock, expires_at = (
177
+ initial_missing,
178
+ Lock(fast_acquire=not self._always_checkpoint),
179
+ None,
180
+ )
181
+ cache_entry[key] = cached_value, lock, expires_at
182
+
183
+ if lock is None:
184
+ if expires_at is not None and current_time() >= expires_at:
185
+ self._currsize -= 1
186
+ cached_value, lock, expires_at = (
187
+ initial_missing,
188
+ Lock(fast_acquire=not self._always_checkpoint),
189
+ None,
190
+ )
191
+ cache_entry[key] = cached_value, lock, expires_at
192
+ else:
193
+ # The value was already cached
194
+ self._hits += 1
195
+ cache_entry.move_to_end(key)
196
+ if self._always_checkpoint:
197
+ await checkpoint()
198
+
199
+ return cast(T, cached_value)
200
+
201
+ async with lock:
202
+ # Check if another task filled the cache while we acquired the lock
203
+ if (cached_value := cache_entry[key][0]) is initial_missing:
204
+ self._misses += 1
205
+ if self._maxsize is not None and self._currsize >= self._maxsize:
206
+ cache_entry.popitem(last=False)
207
+ else:
208
+ self._currsize += 1
209
+
210
+ value = await self.__wrapped__(*args, **kwargs)
211
+ expires_at = (
212
+ current_time() + self._ttl if self._ttl is not None else None
213
+ )
214
+ cache_entry[key] = value, None, expires_at
215
+ else:
216
+ # Another task filled the cache while we were waiting for the lock
217
+ self._hits += 1
218
+ cache_entry.move_to_end(key)
219
+ value = cast(T, cached_value)
220
+
221
+ return value
222
+
223
+ def __get__(
224
+ self, instance: object, owner: type | None = None
225
+ ) -> _LRUMethodWrapper[T]:
226
+ wrapper = _LRUMethodWrapper(self, instance)
227
+ update_wrapper(wrapper, self.__wrapped__)
228
+ return wrapper
229
+
230
+
231
+ class _LRUCacheWrapper(Generic[T]):
232
+ def __init__(
233
+ self, maxsize: int | None, typed: bool, always_checkpoint: bool, ttl: int | None
234
+ ):
235
+ self._maxsize = maxsize
236
+ self._typed = typed
237
+ self._always_checkpoint = always_checkpoint
238
+ self._ttl = ttl
239
+
240
+ @overload
241
+ def __call__( # type: ignore[overload-overlap]
242
+ self, func: Callable[P, Coroutine[Any, Any, T]], /
243
+ ) -> AsyncLRUCacheWrapper[P, T]: ...
244
+
245
+ @overload
246
+ def __call__(
247
+ self, func: Callable[..., T], /
248
+ ) -> functools._lru_cache_wrapper[T]: ...
249
+
250
+ def __call__(
251
+ self, f: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T], /
252
+ ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]:
253
+ if iscoroutinefunction(f):
254
+ return AsyncLRUCacheWrapper(
255
+ f, self._maxsize, self._typed, self._always_checkpoint, self._ttl
256
+ )
257
+
258
+ return functools.lru_cache(maxsize=self._maxsize, typed=self._typed)(f) # type: ignore[arg-type]
259
+
260
+
261
+ @overload
262
+ def cache( # type: ignore[overload-overlap]
263
+ func: Callable[P, Coroutine[Any, Any, T]], /
264
+ ) -> AsyncLRUCacheWrapper[P, T]: ...
265
+
266
+
267
+ @overload
268
+ def cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ...
269
+
270
+
271
+ def cache(
272
+ func: Callable[..., T] | Callable[P, Coroutine[Any, Any, T]], /
273
+ ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]:
274
+ """
275
+ A convenient shortcut for :func:`lru_cache` with ``maxsize=None``.
276
+
277
+ This is the asynchronous equivalent to :func:`functools.cache`.
278
+
279
+ """
280
+ return lru_cache(maxsize=None)(func)
281
+
282
+
283
+ @overload
284
+ def lru_cache(
285
+ *,
286
+ maxsize: int | None = ...,
287
+ typed: bool = ...,
288
+ always_checkpoint: bool = ...,
289
+ ttl: int | None = ...,
290
+ ) -> _LRUCacheWrapper[Any]: ...
291
+
292
+
293
+ @overload
294
+ def lru_cache( # type: ignore[overload-overlap]
295
+ func: Callable[P, Coroutine[Any, Any, T]], /
296
+ ) -> AsyncLRUCacheWrapper[P, T]: ...
297
+
298
+
299
+ @overload
300
+ def lru_cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ...
301
+
302
+
303
+ def lru_cache(
304
+ func: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T] | None = None,
305
+ /,
306
+ *,
307
+ maxsize: int | None = 128,
308
+ typed: bool = False,
309
+ always_checkpoint: bool = False,
310
+ ttl: int | None = None,
311
+ ) -> (
312
+ AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T] | _LRUCacheWrapper[Any]
313
+ ):
314
+ """
315
+ An asynchronous version of :func:`functools.lru_cache`.
316
+
317
+ If a synchronous function is passed, the standard library
318
+ :func:`functools.lru_cache` is applied instead.
319
+
320
+ :param always_checkpoint: if ``True``, every call to the cached function will be
321
+ guaranteed to yield control to the event loop at least once
322
+ :param ttl: time in seconds after which to invalidate cache entries
323
+
324
+ .. note:: Caches and locks are managed on a per-event loop basis.
325
+
326
+ """
327
+ if func is None:
328
+ return _LRUCacheWrapper[Any](maxsize, typed, always_checkpoint, ttl)
329
+
330
+ if not callable(func):
331
+ raise TypeError("the first argument must be callable")
332
+
333
+ return _LRUCacheWrapper[T](maxsize, typed, always_checkpoint, ttl)(func)
334
+
335
+
336
+ @overload
337
+ async def reduce(
338
+ function: Callable[[T, S], Awaitable[T]],
339
+ iterable: Iterable[S] | AsyncIterable[S],
340
+ /,
341
+ initial: T,
342
+ ) -> T: ...
343
+
344
+
345
+ @overload
346
+ async def reduce(
347
+ function: Callable[[T, T], Awaitable[T]],
348
+ iterable: Iterable[T] | AsyncIterable[T],
349
+ /,
350
+ ) -> T: ...
351
+
352
+
353
+ async def reduce( # type: ignore[misc]
354
+ function: Callable[[T, T], Awaitable[T]] | Callable[[T, S], Awaitable[T]],
355
+ iterable: Iterable[T] | Iterable[S] | AsyncIterable[T] | AsyncIterable[S],
356
+ /,
357
+ initial: T | _InitialMissingType = initial_missing,
358
+ ) -> T:
359
+ """
360
+ Asynchronous version of :func:`functools.reduce`.
361
+
362
+ :param function: a coroutine function that takes two arguments: the accumulated
363
+ value and the next element from the iterable
364
+ :param iterable: an iterable or async iterable
365
+ :param initial: the initial value (if missing, the first element of the iterable is
366
+ used as the initial value)
367
+
368
+ """
369
+ element: Any
370
+ function_called = False
371
+ if isinstance(iterable, AsyncIterable):
372
+ async_it = iterable.__aiter__()
373
+ if initial is initial_missing:
374
+ try:
375
+ value = cast(T, await async_it.__anext__())
376
+ except StopAsyncIteration:
377
+ raise TypeError(
378
+ "reduce() of empty sequence with no initial value"
379
+ ) from None
380
+ else:
381
+ value = cast(T, initial)
382
+
383
+ async for element in async_it:
384
+ value = await function(value, element)
385
+ function_called = True
386
+ elif isinstance(iterable, Iterable):
387
+ it = iter(iterable)
388
+ if initial is initial_missing:
389
+ try:
390
+ value = cast(T, next(it))
391
+ except StopIteration:
392
+ raise TypeError(
393
+ "reduce() of empty sequence with no initial value"
394
+ ) from None
395
+ else:
396
+ value = cast(T, initial)
397
+
398
+ for element in it:
399
+ value = await function(value, element)
400
+ function_called = True
401
+ else:
402
+ raise TypeError("reduce() argument 2 must be an iterable or async iterable")
403
+
404
+ # Make sure there is at least one checkpoint, even if an empty iterable and an
405
+ # initial value were given
406
+ if not function_called:
407
+ await checkpoint()
408
+
409
+ return value
python/Lib/site-packages/anyio/lowlevel.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "EventLoopToken",
5
+ "RunvarToken",
6
+ "RunVar",
7
+ "checkpoint",
8
+ "checkpoint_if_cancelled",
9
+ "cancel_shielded_checkpoint",
10
+ "current_token",
11
+ )
12
+
13
+ import enum
14
+ from dataclasses import dataclass
15
+ from types import TracebackType
16
+ from typing import Any, Generic, Literal, TypeVar, final, overload
17
+ from weakref import WeakKeyDictionary
18
+
19
+ from ._core._eventloop import get_async_backend
20
+ from .abc import AsyncBackend
21
+
22
+ T = TypeVar("T")
23
+ D = TypeVar("D")
24
+
25
+
26
+ async def checkpoint() -> None:
27
+ """
28
+ Check for cancellation and allow the scheduler to switch to another task.
29
+
30
+ Equivalent to (but more efficient than)::
31
+
32
+ await checkpoint_if_cancelled()
33
+ await cancel_shielded_checkpoint()
34
+
35
+ .. versionadded:: 3.0
36
+
37
+ """
38
+ await get_async_backend().checkpoint()
39
+
40
+
41
+ async def checkpoint_if_cancelled() -> None:
42
+ """
43
+ Enter a checkpoint if the enclosing cancel scope has been cancelled.
44
+
45
+ This does not allow the scheduler to switch to a different task.
46
+
47
+ .. versionadded:: 3.0
48
+
49
+ """
50
+ await get_async_backend().checkpoint_if_cancelled()
51
+
52
+
53
+ async def cancel_shielded_checkpoint() -> None:
54
+ """
55
+ Allow the scheduler to switch to another task but without checking for cancellation.
56
+
57
+ Equivalent to (but potentially more efficient than)::
58
+
59
+ with CancelScope(shield=True):
60
+ await checkpoint()
61
+
62
+ .. versionadded:: 3.0
63
+
64
+ """
65
+ await get_async_backend().cancel_shielded_checkpoint()
66
+
67
+
68
+ @final
69
+ @dataclass(frozen=True, repr=False)
70
+ class EventLoopToken:
71
+ """
72
+ An opaque object that holds a reference to an event loop.
73
+
74
+ .. versionadded:: 4.11.0
75
+ """
76
+
77
+ backend_class: type[AsyncBackend]
78
+ native_token: object
79
+
80
+
81
+ def current_token() -> EventLoopToken:
82
+ """
83
+ Return a token object that can be used to call code in the current event loop from
84
+ another thread.
85
+
86
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
87
+ current thread
88
+
89
+ .. versionadded:: 4.11.0
90
+
91
+ """
92
+ backend_class = get_async_backend()
93
+ raw_token = backend_class.current_token()
94
+ return EventLoopToken(backend_class, raw_token)
95
+
96
+
97
+ _run_vars: WeakKeyDictionary[object, dict[RunVar[Any], Any]] = WeakKeyDictionary()
98
+
99
+
100
+ class _NoValueSet(enum.Enum):
101
+ NO_VALUE_SET = enum.auto()
102
+
103
+
104
+ class RunvarToken(Generic[T]):
105
+ __slots__ = "_var", "_value", "_redeemed"
106
+
107
+ def __init__(self, var: RunVar[T], value: T | Literal[_NoValueSet.NO_VALUE_SET]):
108
+ self._var = var
109
+ self._value: T | Literal[_NoValueSet.NO_VALUE_SET] = value
110
+ self._redeemed = False
111
+
112
+ def __enter__(self) -> RunvarToken[T]:
113
+ return self
114
+
115
+ def __exit__(
116
+ self,
117
+ exc_type: type[BaseException] | None,
118
+ exc_val: BaseException | None,
119
+ exc_tb: TracebackType | None,
120
+ ) -> None:
121
+ self._var.reset(self)
122
+
123
+
124
+ class RunVar(Generic[T]):
125
+ """
126
+ Like a :class:`~contextvars.ContextVar`, except scoped to the running event loop.
127
+
128
+ Can be used as a context manager, Just like :class:`~contextvars.ContextVar`, that
129
+ will reset the variable to its previous value when the context block is exited.
130
+ """
131
+
132
+ __slots__ = "_name", "_default"
133
+
134
+ NO_VALUE_SET: Literal[_NoValueSet.NO_VALUE_SET] = _NoValueSet.NO_VALUE_SET
135
+
136
+ def __init__(
137
+ self, name: str, default: T | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET
138
+ ):
139
+ self._name = name
140
+ self._default = default
141
+
142
+ @property
143
+ def _current_vars(self) -> dict[RunVar[T], T]:
144
+ native_token = current_token().native_token
145
+ try:
146
+ return _run_vars[native_token]
147
+ except KeyError:
148
+ run_vars = _run_vars[native_token] = {}
149
+ return run_vars
150
+
151
+ @overload
152
+ def get(self, default: D) -> T | D: ...
153
+
154
+ @overload
155
+ def get(self) -> T: ...
156
+
157
+ def get(
158
+ self, default: D | Literal[_NoValueSet.NO_VALUE_SET] = NO_VALUE_SET
159
+ ) -> T | D:
160
+ try:
161
+ return self._current_vars[self]
162
+ except KeyError:
163
+ if default is not RunVar.NO_VALUE_SET:
164
+ return default
165
+ elif self._default is not RunVar.NO_VALUE_SET:
166
+ return self._default
167
+
168
+ raise LookupError(
169
+ f'Run variable "{self._name}" has no value and no default set'
170
+ )
171
+
172
+ def set(self, value: T) -> RunvarToken[T]:
173
+ current_vars = self._current_vars
174
+ token = RunvarToken(self, current_vars.get(self, RunVar.NO_VALUE_SET))
175
+ current_vars[self] = value
176
+ return token
177
+
178
+ def reset(self, token: RunvarToken[T]) -> None:
179
+ if token._var is not self:
180
+ raise ValueError("This token does not belong to this RunVar")
181
+
182
+ if token._redeemed:
183
+ raise ValueError("This token has already been used")
184
+
185
+ if token._value is _NoValueSet.NO_VALUE_SET:
186
+ try:
187
+ del self._current_vars[self]
188
+ except KeyError:
189
+ pass
190
+ else:
191
+ self._current_vars[self] = token._value
192
+
193
+ token._redeemed = True
194
+
195
+ def __repr__(self) -> str:
196
+ return f"<RunVar name={self._name!r}>"
python/Lib/site-packages/anyio/py.typed ADDED
File without changes
python/Lib/site-packages/anyio/pytest_plugin.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import socket
5
+ import sys
6
+ from collections.abc import Callable, Generator, Iterator
7
+ from contextlib import ExitStack, contextmanager
8
+ from inspect import isasyncgenfunction, iscoroutinefunction, ismethod
9
+ from typing import Any, cast
10
+
11
+ import pytest
12
+ from _pytest.fixtures import FuncFixtureInfo, SubRequest
13
+ from _pytest.outcomes import Exit
14
+ from _pytest.python import CallSpec2
15
+ from _pytest.scope import Scope
16
+
17
+ from . import get_available_backends
18
+ from ._core._eventloop import (
19
+ current_async_library,
20
+ get_async_backend,
21
+ reset_current_async_library,
22
+ set_current_async_library,
23
+ )
24
+ from ._core._exceptions import iterate_exceptions
25
+ from .abc import TestRunner
26
+
27
+ if sys.version_info < (3, 11):
28
+ from exceptiongroup import ExceptionGroup
29
+
30
+ _current_runner: TestRunner | None = None
31
+ _runner_stack: ExitStack | None = None
32
+ _runner_leases = 0
33
+
34
+
35
+ def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]:
36
+ if isinstance(backend, str):
37
+ return backend, {}
38
+ elif isinstance(backend, tuple) and len(backend) == 2:
39
+ if isinstance(backend[0], str) and isinstance(backend[1], dict):
40
+ return cast(tuple[str, dict[str, Any]], backend)
41
+
42
+ raise TypeError("anyio_backend must be either a string or tuple of (string, dict)")
43
+
44
+
45
+ @contextmanager
46
+ def get_runner(
47
+ backend_name: str, backend_options: dict[str, Any]
48
+ ) -> Iterator[TestRunner]:
49
+ global _current_runner, _runner_leases, _runner_stack
50
+ if _current_runner is None:
51
+ asynclib = get_async_backend(backend_name)
52
+ _runner_stack = ExitStack()
53
+ if current_async_library() is None:
54
+ # Since we're in control of the event loop, we can cache the name of the
55
+ # async library
56
+ token = set_current_async_library(backend_name)
57
+ _runner_stack.callback(reset_current_async_library, token)
58
+
59
+ backend_options = backend_options or {}
60
+ _current_runner = _runner_stack.enter_context(
61
+ asynclib.create_test_runner(backend_options)
62
+ )
63
+
64
+ _runner_leases += 1
65
+ try:
66
+ yield _current_runner
67
+ finally:
68
+ _runner_leases -= 1
69
+ if not _runner_leases:
70
+ assert _runner_stack is not None
71
+ _runner_stack.close()
72
+ _runner_stack = _current_runner = None
73
+
74
+
75
+ def pytest_addoption(parser: pytest.Parser) -> None:
76
+ parser.addini(
77
+ "anyio_mode",
78
+ default="strict",
79
+ help='AnyIO plugin mode (either "strict" or "auto")',
80
+ )
81
+
82
+
83
+ def pytest_configure(config: pytest.Config) -> None:
84
+ config.addinivalue_line(
85
+ "markers",
86
+ "anyio: mark the (coroutine function) test to be run asynchronously via anyio.",
87
+ )
88
+ if (
89
+ config.getini("anyio_mode") == "auto"
90
+ and config.pluginmanager.has_plugin("asyncio")
91
+ and config.getini("asyncio_mode") == "auto"
92
+ ):
93
+ config.issue_config_time_warning(
94
+ pytest.PytestConfigWarning(
95
+ "AnyIO auto mode has been enabled together with pytest-asyncio auto "
96
+ "mode. This may cause unexpected behavior."
97
+ ),
98
+ 1,
99
+ )
100
+
101
+
102
+ @pytest.hookimpl(hookwrapper=True)
103
+ def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]:
104
+ def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any:
105
+ # Rebind any fixture methods to the request instance
106
+ if (
107
+ request.instance
108
+ and ismethod(func)
109
+ and type(func.__self__) is type(request.instance)
110
+ ):
111
+ local_func = func.__func__.__get__(request.instance)
112
+ else:
113
+ local_func = func
114
+
115
+ backend_name, backend_options = extract_backend_and_options(anyio_backend)
116
+ if has_backend_arg:
117
+ kwargs["anyio_backend"] = anyio_backend
118
+
119
+ if has_request_arg:
120
+ kwargs["request"] = request
121
+
122
+ with get_runner(backend_name, backend_options) as runner:
123
+ if isasyncgenfunction(local_func):
124
+ yield from runner.run_asyncgen_fixture(local_func, kwargs)
125
+ else:
126
+ yield runner.run_fixture(local_func, kwargs)
127
+
128
+ # Only apply this to coroutine functions and async generator functions in requests
129
+ # that involve the anyio_backend fixture
130
+ func = fixturedef.func
131
+ if isasyncgenfunction(func) or iscoroutinefunction(func):
132
+ if "anyio_backend" in request.fixturenames:
133
+ fixturedef.func = wrapper
134
+ original_argname = fixturedef.argnames
135
+
136
+ if not (has_backend_arg := "anyio_backend" in fixturedef.argnames):
137
+ fixturedef.argnames += ("anyio_backend",)
138
+
139
+ if not (has_request_arg := "request" in fixturedef.argnames):
140
+ fixturedef.argnames += ("request",)
141
+
142
+ try:
143
+ return (yield)
144
+ finally:
145
+ fixturedef.func = func
146
+ fixturedef.argnames = original_argname
147
+
148
+ return (yield)
149
+
150
+
151
+ @pytest.hookimpl(tryfirst=True)
152
+ def pytest_pycollect_makeitem(
153
+ collector: pytest.Module | pytest.Class, name: str, obj: object
154
+ ) -> None:
155
+ if collector.istestfunction(obj, name):
156
+ inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj
157
+ if iscoroutinefunction(inner_func):
158
+ anyio_auto_mode = collector.config.getini("anyio_mode") == "auto"
159
+ marker = collector.get_closest_marker("anyio")
160
+ own_markers = getattr(obj, "pytestmark", ())
161
+ if (
162
+ anyio_auto_mode
163
+ or marker
164
+ or any(marker.name == "anyio" for marker in own_markers)
165
+ ):
166
+ pytest.mark.usefixtures("anyio_backend")(obj)
167
+
168
+
169
+ def pytest_collection_finish(session: pytest.Session) -> None:
170
+ for i, item in reversed(list(enumerate(session.items))):
171
+ if (
172
+ isinstance(item, pytest.Function)
173
+ and iscoroutinefunction(item.function)
174
+ and item.get_closest_marker("anyio") is not None
175
+ and "anyio_backend" not in item.fixturenames
176
+ ):
177
+ new_items = []
178
+ try:
179
+ cs_fields = {f.name for f in dataclasses.fields(CallSpec2)}
180
+ except TypeError:
181
+ cs_fields = set()
182
+
183
+ for param_index, backend in enumerate(get_available_backends()):
184
+ if "_arg2scope" in cs_fields: # pytest >= 8
185
+ callspec = CallSpec2(
186
+ params={"anyio_backend": backend},
187
+ indices={"anyio_backend": param_index},
188
+ _arg2scope={"anyio_backend": Scope.Module},
189
+ _idlist=[backend],
190
+ marks=[],
191
+ )
192
+ else: # pytest 7.x
193
+ callspec = CallSpec2( # type: ignore[call-arg]
194
+ funcargs={},
195
+ params={"anyio_backend": backend},
196
+ indices={"anyio_backend": param_index},
197
+ arg2scope={"anyio_backend": Scope.Module},
198
+ idlist=[backend],
199
+ marks=[],
200
+ )
201
+
202
+ fi = item._fixtureinfo
203
+ new_names_closure = list(fi.names_closure)
204
+ if "anyio_backend" not in new_names_closure:
205
+ new_names_closure.append("anyio_backend")
206
+
207
+ new_fixtureinfo = FuncFixtureInfo(
208
+ argnames=fi.argnames,
209
+ initialnames=fi.initialnames,
210
+ names_closure=new_names_closure,
211
+ name2fixturedefs=fi.name2fixturedefs,
212
+ )
213
+ new_item = pytest.Function.from_parent(
214
+ item.parent,
215
+ name=f"{item.originalname}[{backend}]",
216
+ callspec=callspec,
217
+ callobj=item.obj,
218
+ fixtureinfo=new_fixtureinfo,
219
+ keywords=item.keywords,
220
+ originalname=item.originalname,
221
+ )
222
+ new_items.append(new_item)
223
+
224
+ session.items[i : i + 1] = new_items
225
+
226
+
227
+ @pytest.hookimpl(tryfirst=True)
228
+ def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None:
229
+ def run_with_hypothesis(**kwargs: Any) -> None:
230
+ with get_runner(backend_name, backend_options) as runner:
231
+ runner.run_test(original_func, kwargs)
232
+
233
+ backend = pyfuncitem.funcargs.get("anyio_backend")
234
+ if backend:
235
+ backend_name, backend_options = extract_backend_and_options(backend)
236
+
237
+ if hasattr(pyfuncitem.obj, "hypothesis"):
238
+ # Wrap the inner test function unless it's already wrapped
239
+ original_func = pyfuncitem.obj.hypothesis.inner_test
240
+ if original_func.__qualname__ != run_with_hypothesis.__qualname__:
241
+ if iscoroutinefunction(original_func):
242
+ pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis
243
+
244
+ return None
245
+
246
+ if iscoroutinefunction(pyfuncitem.obj):
247
+ funcargs = pyfuncitem.funcargs
248
+ testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
249
+ with get_runner(backend_name, backend_options) as runner:
250
+ try:
251
+ runner.run_test(pyfuncitem.obj, testargs)
252
+ except ExceptionGroup as excgrp:
253
+ for exc in iterate_exceptions(excgrp):
254
+ if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)):
255
+ raise exc from excgrp
256
+
257
+ raise
258
+
259
+ return True
260
+
261
+ return None
262
+
263
+
264
+ @pytest.fixture(scope="module", params=get_available_backends())
265
+ def anyio_backend(request: Any) -> Any:
266
+ return request.param
267
+
268
+
269
+ @pytest.fixture
270
+ def anyio_backend_name(anyio_backend: Any) -> str:
271
+ if isinstance(anyio_backend, str):
272
+ return anyio_backend
273
+ else:
274
+ return anyio_backend[0]
275
+
276
+
277
+ @pytest.fixture
278
+ def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]:
279
+ if isinstance(anyio_backend, str):
280
+ return {}
281
+ else:
282
+ return anyio_backend[1]
283
+
284
+
285
+ class FreePortFactory:
286
+ """
287
+ Manages port generation based on specified socket kind, ensuring no duplicate
288
+ ports are generated.
289
+
290
+ This class provides functionality for generating available free ports on the
291
+ system. It is initialized with a specific socket kind and can generate ports
292
+ for given address families while avoiding reuse of previously generated ports.
293
+
294
+ Users should not instantiate this class directly, but use the
295
+ ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple
296
+ uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead.
297
+ """
298
+
299
+ def __init__(self, kind: socket.SocketKind) -> None:
300
+ self._kind = kind
301
+ self._generated = set[int]()
302
+
303
+ @property
304
+ def kind(self) -> socket.SocketKind:
305
+ """
306
+ The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or
307
+ :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability
308
+
309
+ """
310
+ return self._kind
311
+
312
+ def __call__(self, family: socket.AddressFamily | None = None) -> int:
313
+ """
314
+ Return an unbound port for the given address family.
315
+
316
+ :param family: if omitted, both IPv4 and IPv6 addresses will be tried
317
+ :return: a port number
318
+
319
+ """
320
+ if family is not None:
321
+ families = [family]
322
+ else:
323
+ families = [socket.AF_INET]
324
+ if socket.has_ipv6:
325
+ families.append(socket.AF_INET6)
326
+
327
+ while True:
328
+ port = 0
329
+ with ExitStack() as stack:
330
+ for family in families:
331
+ sock = stack.enter_context(socket.socket(family, self._kind))
332
+ addr = "::1" if family == socket.AF_INET6 else "127.0.0.1"
333
+ try:
334
+ sock.bind((addr, port))
335
+ except OSError:
336
+ break
337
+
338
+ if not port:
339
+ port = sock.getsockname()[1]
340
+ else:
341
+ if port not in self._generated:
342
+ self._generated.add(port)
343
+ return port
344
+
345
+
346
+ @pytest.fixture(scope="session")
347
+ def free_tcp_port_factory() -> FreePortFactory:
348
+ return FreePortFactory(socket.SOCK_STREAM)
349
+
350
+
351
+ @pytest.fixture(scope="session")
352
+ def free_udp_port_factory() -> FreePortFactory:
353
+ return FreePortFactory(socket.SOCK_DGRAM)
354
+
355
+
356
+ @pytest.fixture
357
+ def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int:
358
+ return free_tcp_port_factory()
359
+
360
+
361
+ @pytest.fixture
362
+ def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int:
363
+ return free_udp_port_factory()
python/Lib/site-packages/anyio/to_interpreter.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "run_sync",
5
+ "current_default_interpreter_limiter",
6
+ )
7
+
8
+ import atexit
9
+ import os
10
+ import sys
11
+ from collections import deque
12
+ from collections.abc import Callable
13
+ from typing import Any, Final, TypeVar
14
+
15
+ from . import current_time, to_thread
16
+ from ._core._exceptions import BrokenWorkerInterpreter
17
+ from ._core._synchronization import CapacityLimiter
18
+ from .lowlevel import RunVar
19
+
20
+ if sys.version_info >= (3, 11):
21
+ from typing import TypeVarTuple, Unpack
22
+ else:
23
+ from typing_extensions import TypeVarTuple, Unpack
24
+
25
+ if sys.version_info >= (3, 14):
26
+ from concurrent.interpreters import ExecutionFailed, create
27
+
28
+ def _interp_call(
29
+ func: Callable[..., Any], args: tuple[Any, ...]
30
+ ) -> tuple[Any, bool]:
31
+ try:
32
+ retval = func(*args)
33
+ except BaseException as exc:
34
+ return exc, True
35
+ else:
36
+ return retval, False
37
+
38
+ class _Worker:
39
+ last_used: float = 0
40
+
41
+ def __init__(self) -> None:
42
+ self._interpreter = create()
43
+
44
+ def destroy(self) -> None:
45
+ self._interpreter.close()
46
+
47
+ def call(
48
+ self,
49
+ func: Callable[..., T_Retval],
50
+ args: tuple[Any, ...],
51
+ ) -> T_Retval:
52
+ try:
53
+ res, is_exception = self._interpreter.call(_interp_call, func, args)
54
+ except ExecutionFailed as exc:
55
+ raise BrokenWorkerInterpreter(exc.excinfo) from exc
56
+
57
+ if is_exception:
58
+ raise res
59
+
60
+ return res
61
+ elif sys.version_info >= (3, 13):
62
+ import _interpqueues
63
+ import _interpreters
64
+
65
+ UNBOUND: Final = 2 # I have no clue how this works, but it was used in the stdlib
66
+ FMT_UNPICKLED: Final = 0
67
+ FMT_PICKLED: Final = 1
68
+ QUEUE_PICKLE_ARGS: Final = (FMT_PICKLED, UNBOUND)
69
+ QUEUE_UNPICKLE_ARGS: Final = (FMT_UNPICKLED, UNBOUND)
70
+
71
+ _run_func = compile(
72
+ """
73
+ import _interpqueues
74
+ from _interpreters import NotShareableError
75
+ from pickle import loads, dumps, HIGHEST_PROTOCOL
76
+
77
+ QUEUE_PICKLE_ARGS = (1, 2)
78
+ QUEUE_UNPICKLE_ARGS = (0, 2)
79
+
80
+ item = _interpqueues.get(queue_id)[0]
81
+ try:
82
+ func, args = loads(item)
83
+ retval = func(*args)
84
+ except BaseException as exc:
85
+ is_exception = True
86
+ retval = exc
87
+ else:
88
+ is_exception = False
89
+
90
+ try:
91
+ _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_UNPICKLE_ARGS)
92
+ except NotShareableError:
93
+ retval = dumps(retval, HIGHEST_PROTOCOL)
94
+ _interpqueues.put(queue_id, (retval, is_exception), *QUEUE_PICKLE_ARGS)
95
+ """,
96
+ "<string>",
97
+ "exec",
98
+ )
99
+
100
+ class _Worker:
101
+ last_used: float = 0
102
+
103
+ def __init__(self) -> None:
104
+ self._interpreter_id = _interpreters.create()
105
+ self._queue_id = _interpqueues.create(1, *QUEUE_UNPICKLE_ARGS)
106
+ _interpreters.set___main___attrs(
107
+ self._interpreter_id, {"queue_id": self._queue_id}
108
+ )
109
+
110
+ def destroy(self) -> None:
111
+ _interpqueues.destroy(self._queue_id)
112
+ _interpreters.destroy(self._interpreter_id)
113
+
114
+ def call(
115
+ self,
116
+ func: Callable[..., T_Retval],
117
+ args: tuple[Any, ...],
118
+ ) -> T_Retval:
119
+ import pickle
120
+
121
+ item = pickle.dumps((func, args), pickle.HIGHEST_PROTOCOL)
122
+ _interpqueues.put(self._queue_id, item, *QUEUE_PICKLE_ARGS)
123
+ exc_info = _interpreters.exec(self._interpreter_id, _run_func)
124
+ if exc_info:
125
+ raise BrokenWorkerInterpreter(exc_info)
126
+
127
+ res = _interpqueues.get(self._queue_id)
128
+ (res, is_exception), fmt = res[:2]
129
+ if fmt == FMT_PICKLED:
130
+ res = pickle.loads(res)
131
+
132
+ if is_exception:
133
+ raise res
134
+
135
+ return res
136
+ else:
137
+
138
+ class _Worker:
139
+ last_used: float = 0
140
+
141
+ def __init__(self) -> None:
142
+ raise RuntimeError("subinterpreters require at least Python 3.13")
143
+
144
+ def call(
145
+ self,
146
+ func: Callable[..., T_Retval],
147
+ args: tuple[Any, ...],
148
+ ) -> T_Retval:
149
+ raise NotImplementedError
150
+
151
+ def destroy(self) -> None:
152
+ pass
153
+
154
+
155
+ DEFAULT_CPU_COUNT: Final = 8 # this is just an arbitrarily selected value
156
+ MAX_WORKER_IDLE_TIME = (
157
+ 30 # seconds a subinterpreter can be idle before becoming eligible for pruning
158
+ )
159
+
160
+ T_Retval = TypeVar("T_Retval")
161
+ PosArgsT = TypeVarTuple("PosArgsT")
162
+
163
+ _idle_workers = RunVar[deque[_Worker]]("_available_workers")
164
+ _default_interpreter_limiter = RunVar[CapacityLimiter]("_default_interpreter_limiter")
165
+
166
+
167
+ def _stop_workers(workers: deque[_Worker]) -> None:
168
+ for worker in workers:
169
+ worker.destroy()
170
+
171
+ workers.clear()
172
+
173
+
174
+ async def run_sync(
175
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
176
+ *args: Unpack[PosArgsT],
177
+ limiter: CapacityLimiter | None = None,
178
+ ) -> T_Retval:
179
+ """
180
+ Call the given function with the given arguments in a subinterpreter.
181
+
182
+ .. warning:: On Python 3.13, the :mod:`concurrent.interpreters` module was not yet
183
+ available, so the code path for that Python version relies on an undocumented,
184
+ private API. As such, it is recommended to not rely on this function for anything
185
+ mission-critical on Python 3.13.
186
+
187
+ :param func: a callable
188
+ :param args: the positional arguments for the callable
189
+ :param limiter: capacity limiter to use to limit the total number of subinterpreters
190
+ running (if omitted, the default limiter is used)
191
+ :return: the result of the call
192
+ :raises BrokenWorkerInterpreter: if there's an internal error in a subinterpreter
193
+
194
+ """
195
+ if limiter is None:
196
+ limiter = current_default_interpreter_limiter()
197
+
198
+ try:
199
+ idle_workers = _idle_workers.get()
200
+ except LookupError:
201
+ idle_workers = deque()
202
+ _idle_workers.set(idle_workers)
203
+ atexit.register(_stop_workers, idle_workers)
204
+
205
+ async with limiter:
206
+ try:
207
+ worker = idle_workers.pop()
208
+ except IndexError:
209
+ worker = _Worker()
210
+
211
+ try:
212
+ return await to_thread.run_sync(
213
+ worker.call,
214
+ func,
215
+ args,
216
+ limiter=limiter,
217
+ )
218
+ finally:
219
+ # Prune workers that have been idle for too long
220
+ now = current_time()
221
+ while idle_workers:
222
+ if now - idle_workers[0].last_used <= MAX_WORKER_IDLE_TIME:
223
+ break
224
+
225
+ await to_thread.run_sync(idle_workers.popleft().destroy, limiter=limiter)
226
+
227
+ worker.last_used = current_time()
228
+ idle_workers.append(worker)
229
+
230
+
231
+ def current_default_interpreter_limiter() -> CapacityLimiter:
232
+ """
233
+ Return the capacity limiter used by default to limit the number of concurrently
234
+ running subinterpreters.
235
+
236
+ Defaults to the number of CPU cores.
237
+
238
+ :return: a capacity limiter object
239
+
240
+ """
241
+ try:
242
+ return _default_interpreter_limiter.get()
243
+ except LookupError:
244
+ limiter = CapacityLimiter(os.cpu_count() or DEFAULT_CPU_COUNT)
245
+ _default_interpreter_limiter.set(limiter)
246
+ return limiter
python/Lib/site-packages/anyio/to_process.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "current_default_process_limiter",
5
+ "process_worker",
6
+ "run_sync",
7
+ )
8
+
9
+ import os
10
+ import pickle
11
+ import subprocess
12
+ import sys
13
+ from collections import deque
14
+ from collections.abc import Callable
15
+ from importlib.util import module_from_spec, spec_from_file_location
16
+ from typing import TypeVar, cast
17
+
18
+ from ._core._eventloop import current_time, get_async_backend, get_cancelled_exc_class
19
+ from ._core._exceptions import BrokenWorkerProcess
20
+ from ._core._subprocesses import open_process
21
+ from ._core._synchronization import CapacityLimiter
22
+ from ._core._tasks import CancelScope, fail_after
23
+ from .abc import ByteReceiveStream, ByteSendStream, Process
24
+ from .lowlevel import RunVar, checkpoint_if_cancelled
25
+ from .streams.buffered import BufferedByteReceiveStream
26
+
27
+ if sys.version_info >= (3, 11):
28
+ from typing import TypeVarTuple, Unpack
29
+ else:
30
+ from typing_extensions import TypeVarTuple, Unpack
31
+
32
+ WORKER_MAX_IDLE_TIME = 300 # 5 minutes
33
+
34
+ T_Retval = TypeVar("T_Retval")
35
+ PosArgsT = TypeVarTuple("PosArgsT")
36
+
37
+ _process_pool_workers: RunVar[set[Process]] = RunVar("_process_pool_workers")
38
+ _process_pool_idle_workers: RunVar[deque[tuple[Process, float]]] = RunVar(
39
+ "_process_pool_idle_workers"
40
+ )
41
+ _default_process_limiter: RunVar[CapacityLimiter] = RunVar("_default_process_limiter")
42
+
43
+
44
+ async def run_sync( # type: ignore[return]
45
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
46
+ *args: Unpack[PosArgsT],
47
+ cancellable: bool = False,
48
+ limiter: CapacityLimiter | None = None,
49
+ ) -> T_Retval:
50
+ """
51
+ Call the given function with the given arguments in a worker process.
52
+
53
+ If the ``cancellable`` option is enabled and the task waiting for its completion is
54
+ cancelled, the worker process running it will be abruptly terminated using SIGKILL
55
+ (or ``terminateProcess()`` on Windows).
56
+
57
+ :param func: a callable
58
+ :param args: positional arguments for the callable
59
+ :param cancellable: ``True`` to allow cancellation of the operation while it's
60
+ running
61
+ :param limiter: capacity limiter to use to limit the total amount of processes
62
+ running (if omitted, the default limiter is used)
63
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
64
+ current thread
65
+ :return: an awaitable that yields the return value of the function.
66
+
67
+ """
68
+
69
+ async def send_raw_command(pickled_cmd: bytes) -> object:
70
+ try:
71
+ await stdin.send(pickled_cmd)
72
+ response = await buffered.receive_until(b"\n", 50)
73
+ status, length = response.split(b" ")
74
+ if status not in (b"RETURN", b"EXCEPTION"):
75
+ raise RuntimeError(
76
+ f"Worker process returned unexpected response: {response!r}"
77
+ )
78
+
79
+ pickled_response = await buffered.receive_exactly(int(length))
80
+ except BaseException as exc:
81
+ workers.discard(process)
82
+ try:
83
+ process.kill()
84
+ with CancelScope(shield=True):
85
+ await process.aclose()
86
+ except ProcessLookupError:
87
+ pass
88
+
89
+ if isinstance(exc, get_cancelled_exc_class()):
90
+ raise
91
+ else:
92
+ raise BrokenWorkerProcess from exc
93
+
94
+ retval = pickle.loads(pickled_response)
95
+ if status == b"EXCEPTION":
96
+ assert isinstance(retval, BaseException)
97
+ raise retval
98
+ else:
99
+ return retval
100
+
101
+ # First pickle the request before trying to reserve a worker process
102
+ await checkpoint_if_cancelled()
103
+ request = pickle.dumps(("run", func, args), protocol=pickle.HIGHEST_PROTOCOL)
104
+
105
+ # If this is the first run in this event loop thread, set up the necessary variables
106
+ try:
107
+ workers = _process_pool_workers.get()
108
+ idle_workers = _process_pool_idle_workers.get()
109
+ except LookupError:
110
+ workers = set()
111
+ idle_workers = deque()
112
+ _process_pool_workers.set(workers)
113
+ _process_pool_idle_workers.set(idle_workers)
114
+ get_async_backend().setup_process_pool_exit_at_shutdown(workers)
115
+
116
+ async with limiter or current_default_process_limiter():
117
+ # Pop processes from the pool (starting from the most recently used) until we
118
+ # find one that hasn't exited yet
119
+ process: Process
120
+ while idle_workers:
121
+ process, idle_since = idle_workers.pop()
122
+ if process.returncode is None:
123
+ stdin = cast(ByteSendStream, process.stdin)
124
+ buffered = BufferedByteReceiveStream(
125
+ cast(ByteReceiveStream, process.stdout)
126
+ )
127
+
128
+ # Prune any other workers that have been idle for WORKER_MAX_IDLE_TIME
129
+ # seconds or longer
130
+ now = current_time()
131
+ killed_processes: list[Process] = []
132
+ while idle_workers:
133
+ if now - idle_workers[0][1] < WORKER_MAX_IDLE_TIME:
134
+ break
135
+
136
+ process_to_kill, idle_since = idle_workers.popleft()
137
+ process_to_kill.kill()
138
+ workers.remove(process_to_kill)
139
+ killed_processes.append(process_to_kill)
140
+
141
+ with CancelScope(shield=True):
142
+ for killed_process in killed_processes:
143
+ await killed_process.aclose()
144
+
145
+ break
146
+
147
+ workers.remove(process)
148
+ else:
149
+ command = [sys.executable, "-u", "-m", __name__]
150
+ process = await open_process(
151
+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE
152
+ )
153
+ try:
154
+ stdin = cast(ByteSendStream, process.stdin)
155
+ buffered = BufferedByteReceiveStream(
156
+ cast(ByteReceiveStream, process.stdout)
157
+ )
158
+ with fail_after(20):
159
+ message = await buffered.receive(6)
160
+
161
+ if message != b"READY\n":
162
+ raise BrokenWorkerProcess(
163
+ f"Worker process returned unexpected response: {message!r}"
164
+ )
165
+
166
+ main_module_path = getattr(sys.modules["__main__"], "__file__", None)
167
+ pickled = pickle.dumps(
168
+ ("init", sys.path, main_module_path),
169
+ protocol=pickle.HIGHEST_PROTOCOL,
170
+ )
171
+ await send_raw_command(pickled)
172
+ except (BrokenWorkerProcess, get_cancelled_exc_class()):
173
+ raise
174
+ except BaseException as exc:
175
+ process.kill()
176
+ raise BrokenWorkerProcess(
177
+ "Error during worker process initialization"
178
+ ) from exc
179
+
180
+ workers.add(process)
181
+
182
+ with CancelScope(shield=not cancellable):
183
+ try:
184
+ return cast(T_Retval, await send_raw_command(request))
185
+ finally:
186
+ if process in workers:
187
+ idle_workers.append((process, current_time()))
188
+
189
+
190
+ def current_default_process_limiter() -> CapacityLimiter:
191
+ """
192
+ Return the capacity limiter that is used by default to limit the number of worker
193
+ processes.
194
+
195
+ :return: a capacity limiter object
196
+
197
+ """
198
+ try:
199
+ return _default_process_limiter.get()
200
+ except LookupError:
201
+ limiter = CapacityLimiter(os.cpu_count() or 2)
202
+ _default_process_limiter.set(limiter)
203
+ return limiter
204
+
205
+
206
+ def process_worker() -> None:
207
+ # Redirect standard streams to os.devnull so that user code won't interfere with the
208
+ # parent-worker communication
209
+ stdin = sys.stdin
210
+ stdout = sys.stdout
211
+ sys.stdin = open(os.devnull)
212
+ sys.stdout = open(os.devnull, "w")
213
+
214
+ stdout.buffer.write(b"READY\n")
215
+ while True:
216
+ retval = exception = None
217
+ try:
218
+ command, *args = pickle.load(stdin.buffer)
219
+ except EOFError:
220
+ return
221
+ except BaseException as exc:
222
+ exception = exc
223
+ else:
224
+ if command == "run":
225
+ func, args = args
226
+ try:
227
+ retval = func(*args)
228
+ except BaseException as exc:
229
+ exception = exc
230
+ elif command == "init":
231
+ main_module_path: str | None
232
+ sys.path, main_module_path = args
233
+ del sys.modules["__main__"]
234
+ if main_module_path and os.path.isfile(main_module_path):
235
+ # Load the parent's main module but as __mp_main__ instead of
236
+ # __main__ (like multiprocessing does) to avoid infinite recursion
237
+ try:
238
+ spec = spec_from_file_location("__mp_main__", main_module_path)
239
+ if spec and spec.loader:
240
+ main = module_from_spec(spec)
241
+ spec.loader.exec_module(main)
242
+ sys.modules["__main__"] = main
243
+ except BaseException as exc:
244
+ exception = exc
245
+ try:
246
+ if exception is not None:
247
+ status = b"EXCEPTION"
248
+ pickled = pickle.dumps(exception, pickle.HIGHEST_PROTOCOL)
249
+ else:
250
+ status = b"RETURN"
251
+ pickled = pickle.dumps(retval, pickle.HIGHEST_PROTOCOL)
252
+ except BaseException as exc:
253
+ exception = exc
254
+ status = b"EXCEPTION"
255
+ pickled = pickle.dumps(exc, pickle.HIGHEST_PROTOCOL)
256
+
257
+ stdout.buffer.write(b"%s %d\n" % (status, len(pickled)))
258
+ stdout.buffer.write(pickled)
259
+
260
+ # Respect SIGTERM
261
+ if isinstance(exception, SystemExit):
262
+ raise exception
263
+
264
+
265
+ if __name__ == "__main__":
266
+ process_worker()
python/Lib/site-packages/anyio/to_thread.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ __all__ = (
4
+ "run_sync",
5
+ "current_default_thread_limiter",
6
+ )
7
+
8
+ import sys
9
+ from collections.abc import Callable
10
+ from typing import TypeVar
11
+ from warnings import warn
12
+
13
+ from ._core._eventloop import get_async_backend
14
+ from .abc import CapacityLimiter
15
+
16
+ if sys.version_info >= (3, 11):
17
+ from typing import TypeVarTuple, Unpack
18
+ else:
19
+ from typing_extensions import TypeVarTuple, Unpack
20
+
21
+ T_Retval = TypeVar("T_Retval")
22
+ PosArgsT = TypeVarTuple("PosArgsT")
23
+
24
+
25
+ async def run_sync(
26
+ func: Callable[[Unpack[PosArgsT]], T_Retval],
27
+ *args: Unpack[PosArgsT],
28
+ abandon_on_cancel: bool = False,
29
+ cancellable: bool | None = None,
30
+ limiter: CapacityLimiter | None = None,
31
+ ) -> T_Retval:
32
+ """
33
+ Call the given function with the given arguments in a worker thread.
34
+
35
+ If the ``abandon_on_cancel`` option is enabled and the task waiting for its
36
+ completion is cancelled, the thread will still run its course but its
37
+ return value (or any raised exception) will be ignored.
38
+
39
+ :param func: a callable
40
+ :param args: positional arguments for the callable
41
+ :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run
42
+ unchecked on own) if the host task is cancelled, ``False`` to ignore
43
+ cancellations in the host task until the operation has completed in the worker
44
+ thread
45
+ :param cancellable: deprecated alias of ``abandon_on_cancel``; will override
46
+ ``abandon_on_cancel`` if both parameters are passed
47
+ :param limiter: capacity limiter to use to limit the total amount of threads running
48
+ (if omitted, the default limiter is used)
49
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
50
+ current thread
51
+ :return: an awaitable that yields the return value of the function.
52
+
53
+ """
54
+ if cancellable is not None:
55
+ abandon_on_cancel = cancellable
56
+ warn(
57
+ "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is "
58
+ "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead",
59
+ DeprecationWarning,
60
+ stacklevel=2,
61
+ )
62
+
63
+ return await get_async_backend().run_sync_in_worker_thread(
64
+ func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter
65
+ )
66
+
67
+
68
+ def current_default_thread_limiter() -> CapacityLimiter:
69
+ """
70
+ Return the capacity limiter that is used by default to limit the number of
71
+ concurrent threads.
72
+
73
+ :return: a capacity limiter object
74
+ :raises NoEventLoopError: if no supported asynchronous event loop is running in the
75
+ current thread
76
+
77
+ """
78
+ return get_async_backend().current_default_thread_limiter()
python/Lib/site-packages/certifi-2026.4.22.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python/Lib/site-packages/certifi-2026.4.22.dist-info/METADATA ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: certifi
3
+ Version: 2026.4.22
4
+ Summary: Python package for providing Mozilla's CA Bundle.
5
+ Home-page: https://github.com/certifi/python-certifi
6
+ Author: Kenneth Reitz
7
+ Author-email: me@kennethreitz.com
8
+ License: MPL-2.0
9
+ Project-URL: Source, https://github.com/certifi/python-certifi
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Requires-Python: >=3.7
26
+ License-File: LICENSE
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: description
31
+ Dynamic: home-page
32
+ Dynamic: license
33
+ Dynamic: license-file
34
+ Dynamic: project-url
35
+ Dynamic: requires-python
36
+ Dynamic: summary
37
+
38
+ Certifi: Python SSL Certificates
39
+ ================================
40
+
41
+ Certifi provides Mozilla's carefully curated collection of Root Certificates for
42
+ validating the trustworthiness of SSL certificates while verifying the identity
43
+ of TLS hosts. It has been extracted from the `Requests`_ project.
44
+
45
+ Installation
46
+ ------------
47
+
48
+ ``certifi`` is available on PyPI. Simply install it with ``pip``::
49
+
50
+ $ pip install certifi
51
+
52
+ Usage
53
+ -----
54
+
55
+ To reference the installed certificate authority (CA) bundle, you can use the
56
+ built-in function::
57
+
58
+ >>> import certifi
59
+
60
+ >>> certifi.where()
61
+ '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
62
+
63
+ Or from the command line::
64
+
65
+ $ python -m certifi
66
+ /usr/local/lib/python3.7/site-packages/certifi/cacert.pem
67
+
68
+ Enjoy!
69
+
70
+ .. _`Requests`: https://requests.readthedocs.io/en/master/
71
+
72
+ Addition/Removal of Certificates
73
+ --------------------------------
74
+
75
+ Certifi does not support any addition/removal or other modification of the
76
+ CA trust store content. This project is intended to provide a reliable and
77
+ highly portable root of trust to python deployments. Look to upstream projects
78
+ for methods to use alternate trust.
python/Lib/site-packages/certifi-2026.4.22.dist-info/RECORD ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ certifi-2026.4.22.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ certifi-2026.4.22.dist-info/METADATA,sha256=Ttb_6cy-0FBGq3v_ICTNPKcXKVs2i-0f4gpz42W8QVo,2474
3
+ certifi-2026.4.22.dist-info/RECORD,,
4
+ certifi-2026.4.22.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
+ certifi-2026.4.22.dist-info/licenses/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
6
+ certifi-2026.4.22.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
7
+ certifi/__init__.py,sha256=iBJYWtxRGHMaO1S73pWYpFn962WQ4ldof2GkfMSREJM,94
8
+ certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
9
+ certifi/__pycache__/__init__.cpython-313.pyc,,
10
+ certifi/__pycache__/__main__.cpython-313.pyc,,
11
+ certifi/__pycache__/core.cpython-313.pyc,,
12
+ certifi/cacert.pem,sha256=Fr4_b-sVQIGV3P46oade-dty9ka5brvv3Gj1YlX3mfg,238641
13
+ certifi/core.py,sha256=XFXycndG5pf37ayeF8N32HUuDafsyhkVMbO4BAPWHa0,3394
14
+ certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
python/Lib/site-packages/certifi-2026.4.22.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
python/Lib/site-packages/certifi-2026.4.22.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ certifi
python/Lib/site-packages/certifi/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .core import contents, where
2
+
3
+ __all__ = ["contents", "where"]
4
+ __version__ = "2026.04.22"
python/Lib/site-packages/certifi/__main__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from certifi import contents, where
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("-c", "--contents", action="store_true")
7
+ args = parser.parse_args()
8
+
9
+ if args.contents:
10
+ print(contents())
11
+ else:
12
+ print(where())
python/Lib/site-packages/certifi/cacert.pem ADDED
The diff for this file is too large to render. See raw diff
 
python/Lib/site-packages/certifi/core.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ certifi.py
3
+ ~~~~~~~~~~
4
+
5
+ This module returns the installation location of cacert.pem or its contents.
6
+ """
7
+ import sys
8
+ import atexit
9
+
10
+ def exit_cacert_ctx() -> None:
11
+ _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr]
12
+
13
+
14
+ if sys.version_info >= (3, 11):
15
+
16
+ from importlib.resources import as_file, files
17
+
18
+ _CACERT_CTX = None
19
+ _CACERT_PATH = None
20
+
21
+ def where() -> str:
22
+ # This is slightly terrible, but we want to delay extracting the file
23
+ # in cases where we're inside of a zipimport situation until someone
24
+ # actually calls where(), but we don't want to re-extract the file
25
+ # on every call of where(), so we'll do it once then store it in a
26
+ # global variable.
27
+ global _CACERT_CTX
28
+ global _CACERT_PATH
29
+ if _CACERT_PATH is None:
30
+ # This is slightly janky, the importlib.resources API wants you to
31
+ # manage the cleanup of this file, so it doesn't actually return a
32
+ # path, it returns a context manager that will give you the path
33
+ # when you enter it and will do any cleanup when you leave it. In
34
+ # the common case of not needing a temporary file, it will just
35
+ # return the file system location and the __exit__() is a no-op.
36
+ #
37
+ # We also have to hold onto the actual context manager, because
38
+ # it will do the cleanup whenever it gets garbage collected, so
39
+ # we will also store that at the global level as well.
40
+ _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem"))
41
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
42
+ atexit.register(exit_cacert_ctx)
43
+
44
+ return _CACERT_PATH
45
+
46
+ def contents() -> str:
47
+ return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii")
48
+
49
+ else:
50
+
51
+ from importlib.resources import path as get_path, read_text
52
+
53
+ _CACERT_CTX = None
54
+ _CACERT_PATH = None
55
+
56
+ def where() -> str:
57
+ # This is slightly terrible, but we want to delay extracting the
58
+ # file in cases where we're inside of a zipimport situation until
59
+ # someone actually calls where(), but we don't want to re-extract
60
+ # the file on every call of where(), so we'll do it once then store
61
+ # it in a global variable.
62
+ global _CACERT_CTX
63
+ global _CACERT_PATH
64
+ if _CACERT_PATH is None:
65
+ # This is slightly janky, the importlib.resources API wants you
66
+ # to manage the cleanup of this file, so it doesn't actually
67
+ # return a path, it returns a context manager that will give
68
+ # you the path when you enter it and will do any cleanup when
69
+ # you leave it. In the common case of not needing a temporary
70
+ # file, it will just return the file system location and the
71
+ # __exit__() is a no-op.
72
+ #
73
+ # We also have to hold onto the actual context manager, because
74
+ # it will do the cleanup whenever it gets garbage collected, so
75
+ # we will also store that at the global level as well.
76
+ _CACERT_CTX = get_path("certifi", "cacert.pem")
77
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
78
+ atexit.register(exit_cacert_ctx)
79
+
80
+ return _CACERT_PATH
81
+
82
+ def contents() -> str:
83
+ return read_text("certifi", "cacert.pem", encoding="ascii")
python/Lib/site-packages/certifi/py.typed ADDED
File without changes
python/Lib/site-packages/click-8.3.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
python/Lib/site-packages/click-8.3.3.dist-info/METADATA ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: click
3
+ Version: 8.3.3
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
+
python/Lib/site-packages/click-8.3.3.dist-info/RECORD ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ click-8.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ click-8.3.3.dist-info/METADATA,sha256=_sjhT7_ZKYkyseqbWJtQA8eAcV2CeDJdcNrX_92pSCY,2621
3
+ click-8.3.3.dist-info/RECORD,,
4
+ click-8.3.3.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
5
+ click-8.3.3.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475
6
+ click/__init__.py,sha256=tq5olp0lVuUNbwOj0p5nMVdqhOyYz4aZzF8S5T0aFMU,4526
7
+ click/__pycache__/__init__.cpython-313.pyc,,
8
+ click/__pycache__/_compat.cpython-313.pyc,,
9
+ click/__pycache__/_termui_impl.cpython-313.pyc,,
10
+ click/__pycache__/_textwrap.cpython-313.pyc,,
11
+ click/__pycache__/_utils.cpython-313.pyc,,
12
+ click/__pycache__/_winconsole.cpython-313.pyc,,
13
+ click/__pycache__/core.cpython-313.pyc,,
14
+ click/__pycache__/decorators.cpython-313.pyc,,
15
+ click/__pycache__/exceptions.cpython-313.pyc,,
16
+ click/__pycache__/formatting.cpython-313.pyc,,
17
+ click/__pycache__/globals.cpython-313.pyc,,
18
+ click/__pycache__/parser.cpython-313.pyc,,
19
+ click/__pycache__/shell_completion.cpython-313.pyc,,
20
+ click/__pycache__/termui.cpython-313.pyc,,
21
+ click/__pycache__/testing.cpython-313.pyc,,
22
+ click/__pycache__/types.cpython-313.pyc,,
23
+ click/__pycache__/utils.cpython-313.pyc,,
24
+ click/_compat.py,sha256=v3xBZkFbvA1BXPRkFfBJc6-pIwPI7345m-kQEnpVAs4,18693
25
+ click/_termui_impl.py,sha256=R3aYjPD2x1xgNXiXEqHSR-jAVhbXKkLKeqgr-4eDOkA,28066
26
+ click/_textwrap.py,sha256=BOae0RQ6vg3FkNgSJyOoGzG1meGMxJ_ukWVZKx_v-0o,1400
27
+ click/_utils.py,sha256=kZwtTf5gMuCilJJceS2iTCvRvCY-0aN5rJq8gKw7p8g,943
28
+ click/_winconsole.py,sha256=_vxUuUaxwBhoR0vUWCNuHY8VUefiMdCIyU2SXPqoF-A,8465
29
+ click/core.py,sha256=wzDpH4Wh45hBfsdw3BHqn_095457WRrb92dyaeIGkHk,134478
30
+ click/decorators.py,sha256=5P7abhJtAQYp_KHgjUvhMv464ERwOzrv2enNknlwHyQ,18461
31
+ click/exceptions.py,sha256=8utf8w6V5hJXMnO_ic1FNrtbwuEn1NUu1aDwV8UqnG4,9954
32
+ click/formatting.py,sha256=RVfwwr0rwWNpgGr8NaHodPzkIr7_tUyVh_nDdanLMNc,9730
33
+ click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923
34
+ click/parser.py,sha256=Q31pH0FlQZEq-UXE_ABRzlygEfvxPTuZbWNh4xfXmzw,19010
35
+ click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
36
+ click/shell_completion.py,sha256=Cc4GQUFuWpfQBa9sF5qXeeYI7n3tI_1k6ZdSn4BZbT0,20994
37
+ click/termui.py,sha256=0xjUaEZJz1_1y8eqon2kOe2OXrmHzZCJoVohFb43yTs,31434
38
+ click/testing.py,sha256=PYLYW4ZjCAP6HRWtNhFpr3imJxQVEPFq3EW3JL0LTfA,22714
39
+ click/types.py,sha256=ek54BNSFwPKsqtfT7jsqcc4WHui8AIFVMKM4oVZIXhc,39927
40
+ click/utils.py,sha256=vep6qqMkv3WkzA9OCu7f6Ku-3beZHNpo8qJqL-uzUk8,20282
python/Lib/site-packages/click-8.3.3.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
python/Lib/site-packages/click/__init__.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .core import ParameterSource as ParameterSource
18
+ from .decorators import argument as argument
19
+ from .decorators import command as command
20
+ from .decorators import confirmation_option as confirmation_option
21
+ from .decorators import group as group
22
+ from .decorators import help_option as help_option
23
+ from .decorators import make_pass_decorator as make_pass_decorator
24
+ from .decorators import option as option
25
+ from .decorators import pass_context as pass_context
26
+ from .decorators import pass_obj as pass_obj
27
+ from .decorators import password_option as password_option
28
+ from .decorators import version_option as version_option
29
+ from .exceptions import Abort as Abort
30
+ from .exceptions import BadArgumentUsage as BadArgumentUsage
31
+ from .exceptions import BadOptionUsage as BadOptionUsage
32
+ from .exceptions import BadParameter as BadParameter
33
+ from .exceptions import ClickException as ClickException
34
+ from .exceptions import FileError as FileError
35
+ from .exceptions import MissingParameter as MissingParameter
36
+ from .exceptions import NoSuchOption as NoSuchOption
37
+ from .exceptions import UsageError as UsageError
38
+ from .formatting import HelpFormatter as HelpFormatter
39
+ from .formatting import wrap_text as wrap_text
40
+ from .globals import get_current_context as get_current_context
41
+ from .termui import clear as clear
42
+ from .termui import confirm as confirm
43
+ from .termui import echo_via_pager as echo_via_pager
44
+ from .termui import edit as edit
45
+ from .termui import getchar as getchar
46
+ from .termui import launch as launch
47
+ from .termui import pause as pause
48
+ from .termui import progressbar as progressbar
49
+ from .termui import prompt as prompt
50
+ from .termui import secho as secho
51
+ from .termui import style as style
52
+ from .termui import unstyle as unstyle
53
+ from .types import BOOL as BOOL
54
+ from .types import Choice as Choice
55
+ from .types import DateTime as DateTime
56
+ from .types import File as File
57
+ from .types import FLOAT as FLOAT
58
+ from .types import FloatRange as FloatRange
59
+ from .types import INT as INT
60
+ from .types import IntRange as IntRange
61
+ from .types import ParamType as ParamType
62
+ from .types import Path as Path
63
+ from .types import STRING as STRING
64
+ from .types import Tuple as Tuple
65
+ from .types import UNPROCESSED as UNPROCESSED
66
+ from .types import UUID as UUID
67
+ from .utils import echo as echo
68
+ from .utils import format_filename as format_filename
69
+ from .utils import get_app_dir as get_app_dir
70
+ from .utils import get_binary_stream as get_binary_stream
71
+ from .utils import get_text_stream as get_text_stream
72
+ from .utils import open_file as open_file
73
+
74
+
75
+ def __getattr__(name: str) -> object:
76
+ import warnings
77
+
78
+ if name == "BaseCommand":
79
+ from .core import _BaseCommand
80
+
81
+ warnings.warn(
82
+ "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
83
+ " 'Command' instead.",
84
+ DeprecationWarning,
85
+ stacklevel=2,
86
+ )
87
+ return _BaseCommand
88
+
89
+ if name == "MultiCommand":
90
+ from .core import _MultiCommand
91
+
92
+ warnings.warn(
93
+ "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
94
+ " 'Group' instead.",
95
+ DeprecationWarning,
96
+ stacklevel=2,
97
+ )
98
+ return _MultiCommand
99
+
100
+ if name == "OptionParser":
101
+ from .parser import _OptionParser
102
+
103
+ warnings.warn(
104
+ "'OptionParser' is deprecated and will be removed in Click 9.0. The"
105
+ " old parser is available in 'optparse'.",
106
+ DeprecationWarning,
107
+ stacklevel=2,
108
+ )
109
+ return _OptionParser
110
+
111
+ if name == "__version__":
112
+ import importlib.metadata
113
+ import warnings
114
+
115
+ warnings.warn(
116
+ "The '__version__' attribute is deprecated and will be removed in"
117
+ " Click 9.1. Use feature detection or"
118
+ " 'importlib.metadata.version(\"click\")' instead.",
119
+ DeprecationWarning,
120
+ stacklevel=2,
121
+ )
122
+ return importlib.metadata.version("click")
123
+
124
+ raise AttributeError(name)
python/Lib/site-packages/click/_compat.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
python/Lib/site-packages/click/_termui_impl.py ADDED
@@ -0,0 +1,870 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 using POSIX mode (the default) so that quote characters are
382
+ # stripped from tokens and quoted Windows paths are preserved.
383
+ # Non-POSIX mode retains quotes in tokens, and wrapping tokens
384
+ # with shlex.quote re-introduces quoting issues on Windows.
385
+ pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))
386
+ if pager_cmd_parts:
387
+ if WIN:
388
+ if _tempfilepager(generator, pager_cmd_parts, color):
389
+ return
390
+ elif _pipepager(generator, pager_cmd_parts, color):
391
+ return
392
+
393
+ if os.environ.get("TERM") in ("dumb", "emacs"):
394
+ return _nullpager(stdout, generator, color)
395
+ if (WIN or sys.platform.startswith("os2")) and _tempfilepager(
396
+ generator, ["more"], color
397
+ ):
398
+ return
399
+ if _pipepager(generator, ["less"], color):
400
+ return
401
+
402
+ import tempfile
403
+
404
+ fd, filename = tempfile.mkstemp()
405
+ os.close(fd)
406
+ try:
407
+ if _pipepager(generator, ["more"], color):
408
+ return
409
+ return _nullpager(stdout, generator, color)
410
+ finally:
411
+ os.unlink(filename)
412
+
413
+
414
+ def _pipepager(
415
+ generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None
416
+ ) -> bool:
417
+ """Page through text by feeding it to another program.
418
+
419
+ Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list
420
+ produced by :func:`shlex.split`. The command is resolved to an absolute
421
+ path with :func:`shutil.which` as recommended by the
422
+ :mod:`subprocess` docs for Windows compatibility.
423
+
424
+ Invoking a pager through this might support colors: if piping to
425
+ ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set
426
+ automatically.
427
+
428
+ Returns ``True`` if the command was found and executed, ``False``
429
+ otherwise so another pager can be attempted.
430
+ """
431
+ # Split the command into the invoked CLI and its parameters.
432
+ if not cmd_parts:
433
+ return False
434
+
435
+ import shutil
436
+
437
+ cmd = cmd_parts[0]
438
+ cmd_params = cmd_parts[1:]
439
+
440
+ cmd_filepath = shutil.which(cmd)
441
+ if not cmd_filepath:
442
+ return False
443
+
444
+ # Produces a normalized absolute path string.
445
+ # multi-call binaries such as busybox derive their identity from the symlink
446
+ # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
447
+ cmd_path = Path(cmd_filepath).absolute()
448
+ cmd_name = cmd_path.name
449
+
450
+ import subprocess
451
+
452
+ # Make a local copy of the environment to not affect the global one.
453
+ env = dict(os.environ)
454
+
455
+ # If we're piping to less and the user hasn't decided on colors, we enable
456
+ # them by default we find the -R flag in the command line arguments.
457
+ if color is None and cmd_name == "less":
458
+ less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"
459
+ if not less_flags:
460
+ env["LESS"] = "-R"
461
+ color = True
462
+ elif "r" in less_flags or "R" in less_flags:
463
+ color = True
464
+
465
+ c = subprocess.Popen(
466
+ [str(cmd_path)] + cmd_params,
467
+ shell=False,
468
+ stdin=subprocess.PIPE,
469
+ env=env,
470
+ errors="replace",
471
+ text=True,
472
+ )
473
+ assert c.stdin is not None
474
+ try:
475
+ for text in generator:
476
+ if not color:
477
+ text = strip_ansi(text)
478
+
479
+ c.stdin.write(text)
480
+ except BrokenPipeError:
481
+ # In case the pager exited unexpectedly, ignore the broken pipe error.
482
+ pass
483
+ except Exception as e:
484
+ # In case there is an exception we want to close the pager immediately
485
+ # and let the caller handle it.
486
+ # Otherwise the pager will keep running, and the user may not notice
487
+ # the error message, or worse yet it may leave the terminal in a broken state.
488
+ c.terminate()
489
+ raise e
490
+ finally:
491
+ # We must close stdin and wait for the pager to exit before we continue
492
+ try:
493
+ c.stdin.close()
494
+ # Close implies flush, so it might throw a BrokenPipeError if the pager
495
+ # process exited already.
496
+ except BrokenPipeError:
497
+ pass
498
+
499
+ # Less doesn't respect ^C, but catches it for its own UI purposes (aborting
500
+ # search or other commands inside less).
501
+ #
502
+ # That means when the user hits ^C, the parent process (click) terminates,
503
+ # but less is still alive, paging the output and messing up the terminal.
504
+ #
505
+ # If the user wants to make the pager exit on ^C, they should set
506
+ # `LESS='-K'`. It's not our decision to make.
507
+ while True:
508
+ try:
509
+ c.wait()
510
+ except KeyboardInterrupt:
511
+ pass
512
+ else:
513
+ break
514
+
515
+ return True
516
+
517
+
518
+ def _tempfilepager(
519
+ generator: cabc.Iterable[str], cmd_parts: list[str], color: bool | None
520
+ ) -> bool:
521
+ """Page through text by invoking a program on a temporary file.
522
+
523
+ Used as the primary pager strategy on Windows (where piping to
524
+ ``more`` adds spurious ``\\r\\n``), and as a fallback on other
525
+ platforms. The command is resolved to an absolute path with
526
+ :func:`shutil.which`.
527
+
528
+ Returns ``True`` if the command was found and executed, ``False``
529
+ otherwise so another pager can be attempted.
530
+ """
531
+ # Split the command into the invoked CLI and its parameters.
532
+ if not cmd_parts:
533
+ return False
534
+
535
+ import shutil
536
+
537
+ cmd = cmd_parts[0]
538
+
539
+ cmd_filepath = shutil.which(cmd)
540
+ if not cmd_filepath:
541
+ return False
542
+ # Produces a normalized absolute path string.
543
+ # multi-call binaries such as busybox derive their identity from the symlink
544
+ # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
545
+ cmd_path = Path(cmd_filepath).absolute()
546
+
547
+ import subprocess
548
+ import tempfile
549
+
550
+ fd, filename = tempfile.mkstemp()
551
+ # TODO: This never terminates if the passed generator never terminates.
552
+ text = "".join(generator)
553
+ if not color:
554
+ text = strip_ansi(text)
555
+ encoding = get_best_encoding(sys.stdout)
556
+ with open_stream(filename, "wb")[0] as f:
557
+ f.write(text.encode(encoding))
558
+ try:
559
+ subprocess.call([str(cmd_path), filename])
560
+ except OSError:
561
+ # Command not found
562
+ pass
563
+ finally:
564
+ os.close(fd)
565
+ os.unlink(filename)
566
+
567
+ return True
568
+
569
+
570
+ def _nullpager(
571
+ stream: t.TextIO, generator: cabc.Iterable[str], color: bool | None
572
+ ) -> None:
573
+ """Simply print unformatted text. This is the ultimate fallback."""
574
+ for text in generator:
575
+ if not color:
576
+ text = strip_ansi(text)
577
+ stream.write(text)
578
+
579
+
580
+ class Editor:
581
+ def __init__(
582
+ self,
583
+ editor: str | None = None,
584
+ env: cabc.Mapping[str, str] | None = None,
585
+ require_save: bool = True,
586
+ extension: str = ".txt",
587
+ ) -> None:
588
+ self.editor = editor
589
+ self.env = env
590
+ self.require_save = require_save
591
+ self.extension = extension
592
+
593
+ def get_editor(self) -> str:
594
+ if self.editor is not None:
595
+ return self.editor
596
+ for key in "VISUAL", "EDITOR":
597
+ rv = os.environ.get(key)
598
+ if rv:
599
+ return rv
600
+ if WIN:
601
+ return "notepad"
602
+
603
+ from shutil import which
604
+
605
+ for editor in "sensible-editor", "vim", "nano":
606
+ if which(editor) is not None:
607
+ return editor
608
+ return "vi"
609
+
610
+ def edit_files(self, filenames: cabc.Iterable[str]) -> None:
611
+ """Open files in the user's editor."""
612
+ import shlex
613
+ import subprocess
614
+
615
+ editor = self.get_editor()
616
+ environ: dict[str, str] | None = None
617
+
618
+ if self.env:
619
+ environ = os.environ.copy()
620
+ environ.update(self.env)
621
+
622
+ try:
623
+ # Split in POSIX mode (the default) for the same reasons as
624
+ # in pager(): strips quotes from tokens and preserves quoted
625
+ # Windows paths.
626
+ c = subprocess.Popen(
627
+ args=shlex.split(editor) + list(filenames),
628
+ env=environ,
629
+ )
630
+ exit_code = c.wait()
631
+ if exit_code != 0:
632
+ raise ClickException(
633
+ _("{editor}: Editing failed").format(editor=editor)
634
+ )
635
+ except OSError as e:
636
+ raise ClickException(
637
+ _("{editor}: Editing failed: {e}").format(editor=editor, e=e)
638
+ ) from e
639
+
640
+ @t.overload
641
+ def edit(self, text: bytes | bytearray) -> bytes | None: ...
642
+
643
+ # We cannot know whether or not the type expected is str or bytes when None
644
+ # is passed, so str is returned as that was what was done before.
645
+ @t.overload
646
+ def edit(self, text: str | None) -> str | None: ...
647
+
648
+ def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:
649
+ import tempfile
650
+
651
+ if text is None:
652
+ data: bytes | bytearray = b""
653
+ elif isinstance(text, (bytes, bytearray)):
654
+ data = text
655
+ else:
656
+ if text and not text.endswith("\n"):
657
+ text += "\n"
658
+
659
+ if WIN:
660
+ data = text.replace("\n", "\r\n").encode("utf-8-sig")
661
+ else:
662
+ data = text.encode("utf-8")
663
+
664
+ fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
665
+ f: t.BinaryIO
666
+
667
+ try:
668
+ with os.fdopen(fd, "wb") as f:
669
+ f.write(data)
670
+
671
+ # If the filesystem resolution is 1 second, like Mac OS
672
+ # 10.12 Extended, or 2 seconds, like FAT32, and the editor
673
+ # closes very fast, require_save can fail. Set the modified
674
+ # time to be 2 seconds in the past to work around this.
675
+ os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
676
+ # Depending on the resolution, the exact value might not be
677
+ # recorded, so get the new recorded value.
678
+ timestamp = os.path.getmtime(name)
679
+
680
+ self.edit_files((name,))
681
+
682
+ if self.require_save and os.path.getmtime(name) == timestamp:
683
+ return None
684
+
685
+ with open(name, "rb") as f:
686
+ rv = f.read()
687
+
688
+ if isinstance(text, (bytes, bytearray)):
689
+ return rv
690
+
691
+ return rv.decode("utf-8-sig").replace("\r\n", "\n")
692
+ finally:
693
+ os.unlink(name)
694
+
695
+
696
+ def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
697
+ import subprocess
698
+
699
+ def _unquote_file(url: str) -> str:
700
+ from urllib.parse import unquote
701
+
702
+ if url.startswith("file://"):
703
+ url = unquote(url[7:])
704
+
705
+ return url
706
+
707
+ if sys.platform == "darwin":
708
+ args = ["open"]
709
+ if wait:
710
+ args.append("-W")
711
+ if locate:
712
+ args.append("-R")
713
+ args.append(_unquote_file(url))
714
+ null = open("/dev/null", "w")
715
+ try:
716
+ return subprocess.Popen(args, stderr=null).wait()
717
+ finally:
718
+ null.close()
719
+ elif WIN:
720
+ if locate:
721
+ url = _unquote_file(url)
722
+ args = ["explorer", f"/select,{url}"]
723
+ else:
724
+ args = ["start"]
725
+ if wait:
726
+ args.append("/WAIT")
727
+ args.append("")
728
+ args.append(url)
729
+ try:
730
+ return subprocess.call(args)
731
+ except OSError:
732
+ # Command not found
733
+ return 127
734
+ elif CYGWIN:
735
+ if locate:
736
+ url = _unquote_file(url)
737
+ args = ["cygstart", os.path.dirname(url)]
738
+ else:
739
+ args = ["cygstart"]
740
+ if wait:
741
+ args.append("-w")
742
+ args.append(url)
743
+ try:
744
+ return subprocess.call(args)
745
+ except OSError:
746
+ # Command not found
747
+ return 127
748
+
749
+ try:
750
+ if locate:
751
+ url = os.path.dirname(_unquote_file(url)) or "."
752
+ else:
753
+ url = _unquote_file(url)
754
+ c = subprocess.Popen(["xdg-open", url])
755
+ if wait:
756
+ return c.wait()
757
+ return 0
758
+ except OSError:
759
+ if url.startswith(("http://", "https://")) and not locate and not wait:
760
+ import webbrowser
761
+
762
+ webbrowser.open(url)
763
+ return 0
764
+ return 1
765
+
766
+
767
+ def _translate_ch_to_exc(ch: str) -> None:
768
+ if ch == "\x03":
769
+ raise KeyboardInterrupt()
770
+
771
+ if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
772
+ raise EOFError()
773
+
774
+ if ch == "\x1a" and WIN: # Windows, Ctrl+Z
775
+ raise EOFError()
776
+
777
+
778
+ if sys.platform == "win32":
779
+ import msvcrt
780
+
781
+ @contextlib.contextmanager
782
+ def raw_terminal() -> cabc.Iterator[int]:
783
+ yield -1
784
+
785
+ def getchar(echo: bool) -> str:
786
+ # The function `getch` will return a bytes object corresponding to
787
+ # the pressed character. Since Windows 10 build 1803, it will also
788
+ # return \x00 when called a second time after pressing a regular key.
789
+ #
790
+ # `getwch` does not share this probably-bugged behavior. Moreover, it
791
+ # returns a Unicode object by default, which is what we want.
792
+ #
793
+ # Either of these functions will return \x00 or \xe0 to indicate
794
+ # a special key, and you need to call the same function again to get
795
+ # the "rest" of the code. The fun part is that \u00e0 is
796
+ # "latin small letter a with grave", so if you type that on a French
797
+ # keyboard, you _also_ get a \xe0.
798
+ # E.g., consider the Up arrow. This returns \xe0 and then \x48. The
799
+ # resulting Unicode string reads as "a with grave" + "capital H".
800
+ # This is indistinguishable from when the user actually types
801
+ # "a with grave" and then "capital H".
802
+ #
803
+ # When \xe0 is returned, we assume it's part of a special-key sequence
804
+ # and call `getwch` again, but that means that when the user types
805
+ # the \u00e0 character, `getchar` doesn't return until a second
806
+ # character is typed.
807
+ # The alternative is returning immediately, but that would mess up
808
+ # cross-platform handling of arrow keys and others that start with
809
+ # \xe0. Another option is using `getch`, but then we can't reliably
810
+ # read non-ASCII characters, because return values of `getch` are
811
+ # limited to the current 8-bit codepage.
812
+ #
813
+ # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
814
+ # is doing the right thing in more situations than with `getch`.
815
+
816
+ if echo:
817
+ func = t.cast(t.Callable[[], str], msvcrt.getwche)
818
+ else:
819
+ func = t.cast(t.Callable[[], str], msvcrt.getwch)
820
+
821
+ rv = func()
822
+
823
+ if rv in ("\x00", "\xe0"):
824
+ # \x00 and \xe0 are control characters that indicate special key,
825
+ # see above.
826
+ rv += func()
827
+
828
+ _translate_ch_to_exc(rv)
829
+ return rv
830
+
831
+ else:
832
+ import termios
833
+ import tty
834
+
835
+ @contextlib.contextmanager
836
+ def raw_terminal() -> cabc.Iterator[int]:
837
+ f: t.TextIO | None
838
+ fd: int
839
+
840
+ if not isatty(sys.stdin):
841
+ f = open("/dev/tty")
842
+ fd = f.fileno()
843
+ else:
844
+ fd = sys.stdin.fileno()
845
+ f = None
846
+
847
+ try:
848
+ old_settings = termios.tcgetattr(fd)
849
+
850
+ try:
851
+ tty.setraw(fd)
852
+ yield fd
853
+ finally:
854
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
855
+ sys.stdout.flush()
856
+
857
+ if f is not None:
858
+ f.close()
859
+ except termios.error:
860
+ pass
861
+
862
+ def getchar(echo: bool) -> str:
863
+ with raw_terminal() as fd:
864
+ ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
865
+
866
+ if echo and isatty(sys.stdout):
867
+ sys.stdout.write(ch)
868
+
869
+ _translate_ch_to_exc(ch)
870
+ return ch
python/Lib/site-packages/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)
python/Lib/site-packages/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."""
python/Lib/site-packages/click/_winconsole.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module is based on the excellent 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)
python/Lib/site-packages/click/core.py ADDED
The diff for this file is too large to render. See raw diff
 
python/Lib/site-packages/click/decorators.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
python/Lib/site-packages/click/exceptions.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
python/Lib/site-packages/click/formatting.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
python/Lib/site-packages/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
python/Lib/site-packages/click/parser.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
python/Lib/site-packages/click/py.typed ADDED
File without changes